"""
TURN ON LEDS - MICROPYTHON - TRAFFIC LIGHT
"""
import machine
import utime
# Define the LED pins
led_red = machine.Pin(11, machine.Pin.OUT)
led_yellow = machine.Pin(8, machine.Pin.OUT)
led_green = machine.Pin(5, machine.Pin.OUT)
def red_state():
led_red.value(1)
led_yellow.value(0)
led_green.value(0)
def yellow_state():
led_red.value(0)
led_yellow.value(1)
led_green.value(0)
def green_state():
led_red.value(0)
led_yellow.value(0)
led_green.value(1)
def yellow_state_short():
led_red.value(0)
led_yellow.value(1)
led_green.value(0)
# State handlers list
light_states = [
# STATE AND TIME
(red_state, 5000), # 0
(yellow_state, 3000), # 1
(green_state, 5000), # 2
(yellow_state_short, 2000) # 3
]
def traffic_light():
state = 0
while True:
# Get the current state tuple (handler function and sleep time)
current_light_time = light_states[state]
current_light = current_light_time[0]
current_duration_time = current_light_time[1]
# Execute light state and duration
current_light()
utime.sleep_ms(current_duration_time)
# UPDATE STATE (modulus)
state = (state + 1) % len(light_states)
# Example:
# state = 3
# state = (4) % (4) => 0
# state = 0
# Execute traffic light sequence
traffic_light()