from machine import Pin, Timer
from time import sleep
# GPIO pins for 7-segment display segments (a-g)
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)]
# Digit patterns for 7-segment display
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
]
# Variables for stopwatch
seconds = 0
running = False
def update_display():
"""Update 7-segment display to show the current digit."""
digit = seconds % 10
for j in range(7):
pins[j].value(digits[digit][j])
def timer_callback(tmr):
""" timer callback function to update the time and display."""
global seconds
if running:
seconds += 1
print(f"Stopwatch: seconds={seconds}")
update_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)
# Setup Push Button
button = Pin(16, Pin.IN, Pin.PULL_UP)
# Main loop
while True:
# Poll button state
if not button.value(): # Button is pressed
running = not running
print("Button pressed: Stopwatch running" if running else "Button pressed: Stopwatch stopped")
sleep(0.5) # Debounce delay
sleep(0.1) # Sleep to reduce CPU usage