The Messy Real World — Day 1 of 4
'F' → Fullscreen
Leave Activity 2.6's five-LED array exactly as it is. Create a new MicroPython program named 2-8-analog-input.
3V3 and GND, its middle leg to A0.ADC and print the reading in a loop.The analog pins are the six on the bottom header, labeled A0 through A5. A0 is at the far right:
It does not matter which outer leg goes to 3V3 and which to GND — swapping them just reverses which way you turn the knob to get a bigger number.
from machine import Pin, ADCimport time
pot = ADC(Pin(40))
while True: print(pot.read_u16()) time.sleep(0.2)Do not assume the answer. A knob turned fully one way may not read 0, and fully the other way may not read 65535. Find out what your knob does.
from machine import Pin, ADCimport time
pot = ADC(Pin(40))
lowest = 65535highest = 0
while True: reading = pot.read_u16() if reading < lowest: lowest = reading if reading > highest: highest = reading print("now:", reading, " lowest:", lowest, " highest:", highest) time.sleep(0.2)bar_height(reading, led_count) that converts a reading into a whole number of LEDs.from machine import Pin, ADCimport time
leds = [ Pin(28, Pin.OUT), Pin(29, Pin.OUT), Pin(30, Pin.OUT), Pin(31, Pin.OUT), Pin(32, Pin.OUT),]pot = ADC(Pin(40))
def bar_height(reading, led_count): return reading * (led_count + 1) // 65536
while True: reading = pot.read_u16() print("reading:", reading, " bar:", bar_height(reading, len(leds))) time.sleep(0.2)show_bar(leds, count) that lights the first count LEDs and turns the rest off.This is the function that needs leds[i]. Work out for yourself why for led in leds: cannot do it before you read the code below.
from machine import Pin, ADCimport time
leds = [ Pin(28, Pin.OUT), Pin(29, Pin.OUT), Pin(30, Pin.OUT), Pin(31, Pin.OUT), Pin(32, Pin.OUT),]pot = ADC(Pin(40))
def bar_height(reading, led_count): return reading * (led_count + 1) // 65536
def show_bar(leds, count): for i in range(len(leds)): if i < count: leds[i].value(1) else: leds[i].value(0)
while True: reading = pot.read_u16() height = bar_height(reading, len(leds)) show_bar(leds, height) print("reading:", reading, " bar:", height) time.sleep(0.1)chase() function over from Activity 2.6.0.02 and 0.5 seconds works well — scale the reading into that range.Turning the knob from one end to the other should print something like this, and move the bar with it:
reading: 148 bar: 0reading: 11302 bar: 1reading: 24907 bar: 2reading: 38455 bar: 3reading: 51100 bar: 4reading: 65216 bar: 5Answer the following questions before submitting your work.
for led in leds:, but show_bar() needs leds[i]. Explain what the bar graph asks for that a plain traversal cannot give.Submit the required files to the appropriate dropbox.