import machine
import utime
led_red = machine.Pin(1, machine.Pin.OUT)
led_yellow = machine.Pin(4, machine.Pin.OUT)
led_green = machine.Pin(9, machine.Pin.OUT)
def handle_red_state():
led_red.value(1)
led_yellow.value(0)
led_green.value(0)
def handle_yellow_state():
led_red.value(0)
led_yellow.value(1)
led_green.value(0)
def handle_green_state():
led_red.value(0)
led_yellow.value(0)
led_green.value(1)
def handle_yellow_state_short():
led_red.value(0)
led_yellow.value(1)
led_green.value(0)
state_handlers = [
(handle_red_state, 5000),
(handle_yellow_state, 3000),
(handle_green_state, 5000),
(handle_yellow_state_short, 2000)
]
def traffic_light():
state = 0
while True:
current_handler_and_time = state_handlers[state]
handler_func = current_handler_and_time[0]
sleep_duration_ms = current_handler_and_time[1]
handler_func()
utime.sleep_ms(sleep_duration_ms)
state = (state + 1) % len(state_handlers)
traffic_light()