from machine import Pin, Timer
from time import sleep
# GPIO pins for 7-segment display segments (a-g)
display_pins = [Pin(32, Pin.OUT), Pin(33, Pin.OUT), Pin(25, Pin.OUT), Pin(26, Pin.OUT),
Pin(27, Pin.OUT), Pin(12, Pin.OUT), Pin(14, Pin.OUT)]
# GPIO pins for LEDs
green_led = Pin(2, Pin.OUT)
red_led = Pin(5, Pin.OUT)
yellow_led = Pin(4, Pin.OUT)
# Digit patterns for 7-segment display (common anode, 0 = ON, 1 = OFF)
digits = [
[0, 0, 0, 0, 0, 0, 1], # 0
[1, 0, 0, 1, 1, 1, 1], # 1
[0, 0, 1, 0, 0, 1, 0], # 2
[0, 0, 0, 0, 1, 1, 0], # 3
[1, 0, 0, 1, 1, 0, 0], # 4
[0, 1, 0, 0, 1, 0, 0], # 5
[0, 1, 0, 0, 0, 0, 0], # 6
[0, 0, 0, 1, 1, 1, 1], # 7
[0, 0, 0, 0, 0, 0, 0], # 8
[0, 0, 0, 0, 1, 0, 0] # 9
]
# Initialize countdown value
seconds = 10
led_cycle_time = 10 # Time for one full LED cycle in seconds
led_state = 0 # 0: Green, 1: Red, 2: Yellow
def update_display():
"""Update 7-segment display to show the current digit."""
digit = seconds % 10
for j in range(7):
display_pins[j].value(digits[digit][j])
def clear_display():
"""Turn off all segments to prevent initial ghosting."""
for pin in display_pins:
pin.value(1) # Turn all segments off initially (assuming common anode)
def toggle_leds():
"""Update LEDs based on the current state."""
if led_state == 0: # Green
green_led.value(1)
red_led.value(0)
yellow_led.value(0)
elif led_state == 1: # Yellow
green_led.value(0)
yellow_led.value(1)
red_led.value(0)
elif led_state == 2: # Red
green_led.value(0)
yellow_led.value(0)
red_led.value(1)
def timer_callback(tmr):
""" Timer callback function to update the time and display."""
global seconds, led_cycle_time, led_state
seconds -= 1
if seconds < 0:
seconds = 9 # Reset countdown after reaching 0
# Update display
update_display()
# Change LED state every 10 seconds
if (10 - seconds) % led_cycle_time == 0:
led_state = (led_state + 1) % 3 # Cycle through 0, 1, 2
toggle_leds()
# Initialize LEDs state
toggle_leds()
# Clear the display before starting the countdown
clear_display()
# Setup a Timer
timer = Timer(0)
# The timer period is set to 1000 milliseconds (1 second)
timer.init(period=1000, mode=Timer.PERIODIC, callback=timer_callback)
# Main loop (no button logic needed)
while True:
sleep(0.1) # Small delay to prevent high CPU usage