from machine import Pin, Timer
import time
# Define GPIO pins for LEDs and 7-segment display
RED_LED_PIN = 4
GREEN_LED_PIN = 5
YELLOW_LED_PIN = 6
SEGMENT_PINS = [7, 8, 9, 10, 11, 12, 13]
# Initialize LED pins
red_led = Pin(RED_LED_PIN, Pin.OUT)
green_led = Pin(GREEN_LED_PIN, Pin.OUT)
yellow_led = Pin(YELLOW_LED_PIN, Pin.OUT)
# Initialize 7-segment display pins
segment_pins = [Pin(pin, Pin.OUT) for pin in SEGMENT_PINS]
# Define the pattern for each number on the 7-segment display
# Segments: A, B, C, D, E, F, G
# [0, 1, 2, 3, 4, 5, 6]
NUMBERS = {
0: [0, 0, 0, 0, 0, 0, 1],
1: [1, 0, 0, 1, 1, 1, 1],
2: [0, 0, 1, 0, 0, 1, 0],
3: [0, 0, 0, 0, 1, 1, 0],
4: [1, 0, 0, 1, 1, 0, 0],
5: [0, 1, 0, 0, 1, 0, 0],
6: [0, 1, 0, 0, 0, 0, 0],
7: [0, 0, 0, 1, 1, 1, 1],
8: [0, 0, 0, 0, 0, 0, 0],
9: [0, 0, 0, 0, 1, 0, 0],
}
# Function to display a number on the 7-segment display
def display_number(number):
for i, pin in enumerate(SEGMENT_PINS):
segment_pins[i].value(NUMBERS[number][i])
# Function to control the traffic light
def control_traffic_light():
# Green light phase
green_led.on()
for i in range(1, 10):
display_number(i)
time.sleep(1)
green_led.off()
# Yellow light phase
yellow_led.on()
for i in range(1, 4):
display_number(i)
time.sleep(1)
yellow_led.off()
# Red light phase
red_led.on()
for i in range(9, 0, -1):
display_number(i)
time.sleep(1)
red_led.off()
# Start the traffic light control loop
while True:
control_traffic_light()
# By Lamar Ashraf , Ammar Ahmed and Mostafa Rashed