import machine
import time
# Setup ADC and LEDs for 4-bit display
adc = machine.ADC(28) # ADC0
leds_display = [machine.Pin(i, machine.Pin.OUT) for i in range(10, 14)]
# Setup LEDs for different actions
pb = machine.Pin(20, machine.Pin.IN, machine.Pin.PULL_UP)
array_leds = [machine.Pin(i, machine.Pin.OUT) for i in range(2, 10)]
fade_leds = [machine.Pin(14, machine.Pin.OUT), machine.Pin(15, machine.Pin.OUT)]
# Idle LED setup
idle_led = machine.Pin(16, machine.Pin.OUT)
# Function to read ADC, constrain to 1-4, and display on 4-bit LEDs
def read_adc_and_display():
adc_value = adc.read_u16()
adc_value = (adc_value // (65536 // 4)) + 1 # Map to 1-4
# Display on 4-bit LEDs
for i in range(4):
leds_display[i].value((adc_value >> i) & 1)
return adc_value
# Define behaviors for each ADC value
def running_light():
for led in array_leds:
led.on()
time.sleep(0.1)
led.off()
def knight_rider():
for _ in range(2): # Repeat twice
for i in range(len(array_leds)):
array_leds[i].on()
time.sleep(0.1)
array_leds[i].off()
for i in range(len(array_leds) - 2, -1, -1):
array_leds[i].on()
time.sleep(0.1)
array_leds[i].off()
def blink_all_leds():
for _ in range(5): # Blink 5 times
for led in array_leds:
led.on()
time.sleep(0.5)
for led in array_leds:
led.off()
time.sleep(0.5)
def fade_leds_in_out():
pwm_leds = [machine.PWM(fade_leds[0]), machine.PWM(fade_leds[1])]
for _ in range(3): # Fade in and out 3 times
for duty in range(0, 65535, 5000): # Fade up
for pwm in pwm_leds:
pwm.duty_u16(duty)
time.sleep(0.01)
for duty in range(65535, 0, -5000): # Fade down
for pwm in pwm_leds:
pwm.duty_u16(duty)
time.sleep(0.01)
for pwm in pwm_leds:
pwm.deinit() # Turn off PWM after fading
# Function to check button and execute behavior based on ADC value
def check_button_and_execute(adc_value):
if pb.value() == 0: # If push button is pressed
if adc_value == 1:
running_light()
elif adc_value == 2:
knight_rider()
elif adc_value == 3:
blink_all_leds()
elif adc_value == 4:
fade_leds_in_out()
# Idle blink function for GPIO16
def idle_blink():
idle_led.toggle() # Blink at 10 Hz
time.sleep(0.2)
# Main loop
while True:
adc_value = read_adc_and_display() # Read ADC and update display
check_button_and_execute(adc_value) # Execute behavior if button pressed
idle_blink() # Blink idle LED at 10 Hz if no action is active