from machine import Pin
import time
# Define pins
buzzerPed = Pin(21, Pin.OUT)
buzzerCar = Pin(10, Pin.OUT)
greenPed = Pin(27, Pin.OUT)
redPed = Pin(28, Pin.OUT)
greenCar = Pin(4, Pin.OUT)
yellowCar = Pin(3, Pin.OUT)
redCar = Pin(5, Pin.OUT)
# Segment pin definitions for two 7-segment displays
segment1 = [
Pin(0, Pin.OUT), Pin(1, Pin.OUT), Pin(2, Pin.OUT),
Pin(6, Pin.OUT), Pin(7, Pin.OUT), Pin(9, Pin.OUT), Pin(8, Pin.OUT)
]
segment2 = [
Pin(11, Pin.OUT), Pin(12, Pin.OUT), Pin(16, Pin.OUT),
Pin(18, Pin.OUT), Pin(20, Pin.OUT), Pin(26, Pin.OUT), Pin(22, Pin.OUT)
]
# Number map for 7-segment display (digit 0-9)
number_map = [
[1,1,1,1,1,1,0], # 0
[0,1,1,0,0,0,0], # 1
[1,1,0,1,1,0,1], # 2
[1,1,1,1,0,0,1], # 3
[0,1,1,0,0,1,1], # 4
[1,0,1,1,0,1,1], # 5
[1,0,1,1,1,1,1], # 6
[1,1,1,0,0,0,0], # 7
[1,1,1,1,1,1,1], # 8
[1,1,1,1,0,1,1] # 9
]
# Function to display a number on the 7-segment display
def display(num, seg):
segment_map = number_map[num]
for x in range(len(seg)):
seg[x].value(segment_map[x])
# Countdown function for displaying time on two 7-segment displays
def count_down(start, seg1, seg2):
for i in range(start, -1, -1): # Countdown from start to 0
tens = i // 10 # Get the tens digit using floor division
ones = i % 10 # Get the ones digit using modulus
# Update the first and second segments
display(tens, seg1) # Display the tens digit on segment1
display(ones, seg2) # Display the ones digit on segment2
print(f"Time remaining: {i} seconds")
time.sleep(1) # Delay between steps for countdown
# Main traffic light control loop
while True:
# Red light for cars and green light for pedestrians
redCar.on()
yellowCar.off()
greenCar.off()
redPed.off()
greenPed.on()
buzzerPed.on() # Activate buzzer for pedestrians to move
print("Pedestrians can cross now, cars should stop")
# Countdown for pedestrians to cross (from 20 to 0)
count_down(20, segment1, segment2) # Segment1 and Segment2 show countdown from 20 to 0
# Turn off buzzer after pedestrian time is over
buzzerPed.off()
# Switch to yellow light for cars, pedestrian lights remain red
redPed.on()
greenPed.off()
yellowCar.on()
redCar.off()
buzzerCar.on() # Optional: You could use buzzerCar to indicate the transition
print("Cars should be ready to move, pedestrians wait")
# Countdown for cars to get ready (from 20 to 0)
count_down(20, segment1, segment2) # Segment1 and Segment2 show countdown from 20 to 0 for cars
# Turn off buzzer and yellow light, turn on green for cars
buzzerCar.off()
yellowCar.off()
greenCar.on()
redCar.off()
buzzerCar.on() # Activate buzzer for cars to move
print("Cars can go now, pedestrians should stop")
# Keep the green light on for cars and red light on for pedestrians for a while
time.sleep(10) # Cars move for 10 seconds
# Turn off buzzer and set pedestrian light to green after 1