from machine import Pin, Timer
import time
# Define the GPIO pins for the 7-segment display segments
segments = [Pin(pin, Pin.OUT) for pin in [2, 4, 5, 18, 19, 21, 22]]
digit_pins = [Pin(pin, Pin.OUT) for pin in [25, 26, 27, 14]]
colon = Pin(33, Pin.OUT)
# Segment patterns for displaying numbers 0-9 on a common cathode 7-segment display
num_patterns = [
[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, 0, 0, 1, 1] # 9
]
# Function to display a digit on a specific 7-segment display
def display_digit(digit, number):
pattern = num_patterns[number]
for segment, value in zip(segments, pattern):
segment.value(value)
for dp in digit_pins:
dp.value(1)
digit_pins[digit].value(0)
print(f"Displaying digit {number} on position {digit}")
# Countdown timer function
def countdown_timer(t):
global counter, current_digit, update_time
current_time = time.ticks_ms()
# Update the display every 10 milliseconds
if time.ticks_diff(current_time, update_time) > 10:
if counter >= 0:
# Extract individual digits
digits = [int(d) for d in f"{counter:04}"]
display_digit(current_digit, digits[current_digit])
current_digit = (current_digit + 1) % 4
update_time = current_time
if current_digit == 0:
counter -= 1
colon.value(not colon.value()) # Toggle the colon every second
print(f"Counter: {counter}")
else:
t.deinit() # Stop the timer when the countdown is complete
print("Countdown complete")
# Initialize the countdown value
counter = 100 # 100 seconds
current_digit = 0
update_time = time.ticks_ms()
# Initialize the timer
timer = Timer(0)
timer.init(period=10, mode=Timer.PERIODIC, callback=countdown_timer)
# Keep the script running
while True:
time.sleep(1)