from machine import Pin
import time
# Define pin numbers for the traffic lights
green_pins = [2, 4, 15, 13]
yellow_pins = [5, 18, 19, 23]
red_pins = [14, 12, 21, 22]
# Function to set lights on/off
def set_lights(pins, state):
for pin in pins:
Pin(pin, Pin.OUT).value(state)
# Set up LED pins
def setup():
for pin in green_pins + yellow_pins + red_pins:
Pin(pin, Pin.OUT).value(1) # Set all lights to red initially
time.sleep_ms(500)
# Main traffic control logic
def traffic_control():
while True:
# Traffic light sequence for direction 1
set_lights(red_pins[1:], 1)
set_lights([red_pins[0]], 0)
set_lights([green_pins[0]], 1)
time.sleep(5) # Green light for 5 seconds
set_lights([green_pins[0]], 0)
set_lights([red_pins[0]], 1)
set_lights([yellow_pins[0]], 1)
time.sleep(2) # Yellow light for 2 seconds
set_lights([yellow_pins[0]], 0)
# No delay after red1
# Traffic light sequence for direction 2
set_lights(red_pins[::2], 1)
time.sleep_ms(100)
set_lights([green_pins[1]], 1)
time.sleep(5) # Green light for 5 seconds
set_lights([green_pins[1]], 0)
time.sleep_ms(100)
set_lights([red_pins[0]], 1)
set_lights([yellow_pins[1]], 1)
time.sleep(2) # Yellow light for 2 seconds
set_lights([yellow_pins[1]], 0)
set_lights([red_pins[0]], 0)
# No delay after red2
# Traffic light sequence for direction 3
set_lights(red_pins[1:3], 1)
time.sleep_ms(100)
set_lights([green_pins[2]], 1)
time.sleep(5) # Green light for 5 seconds
set_lights([green_pins[2]], 0)
time.sleep_ms(100)
set_lights([red_pins[0]], 1)
set_lights([yellow_pins[2]], 1)
time.sleep(2) # Yellow light for 2 seconds
set_lights([yellow_pins[2]], 0)
set_lights([red_pins[0]], 0)
# No delay after red3
# Traffic light sequence for direction 4
set_lights(red_pins[1:], 1)
time.sleep_ms(100)
set_lights([green_pins[3]], 1)
time.sleep(5) # Green light for 5 seconds
set_lights([green_pins[3]], 0)
time.sleep_ms(100)
set_lights([red_pins[0]], 1)
set_lights([yellow_pins[3]], 1)
time.sleep(2) # Yellow light for 2 seconds
set_lights([yellow_pins[3]], 0)
set_lights([red_pins[0]], 0)
# No delay after red4
# Simulate conflicting situation (Green on one direction, Red on another)
set_lights([green_pins[0]], 1)
set_lights([red_pins[2]], 1)
time.sleep(5) # Simulate a potential conflict for 5 seconds
set_lights([green_pins[0], red_pins[2]], 0) # Turn off conflicting lights
# Run the setup function
setup()
# Run the traffic control logic
traffic_control()