from machine import Pin
import time
# =========================
# LEDs Setup
# =========================
green_led = Pin(18, Pin.OUT)
blue_led = Pin(17, Pin.OUT)
# =========================
# Push Button (Reset Only)
# =========================
push_reset = Pin(15, Pin.IN, Pin.PULL_UP)
# =========================
# 7-Segment Pins (a-g)
# =========================
segments = [
Pin(0, Pin.OUT), # a
Pin(1, Pin.OUT), # b
Pin(2, Pin.OUT), # c
Pin(3, Pin.OUT), # d
Pin(4, Pin.OUT), # e
Pin(5, Pin.OUT), # f
Pin(6, Pin.OUT) # g
]
# =========================
# Digit Map (0-9)
# =========================
numbers = [
[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
]
def display_number(number):
"""Update 7-segment display according to current number."""
for i in range(7):
segments[i].value(numbers[number][i])
def update_leds(number):
"""Switch LEDs based on the counter range (0-4: Blue, 5-9: Green)."""
if number <= 4:
blue_led.on()
green_led.off()
else:
blue_led.off()
green_led.on()
def reset_system():
"""Reset global counter state and LEDs."""
global count, last_tick
count = 0
update_leds(count)
display_number(count)
last_tick = time.ticks_ms()
print("System Reset -> Counter set to 0")
# =========================
# Initialization
# =========================
count = 0
INTERVAL_MS = 1000 # 1 second auto-increment interval
last_tick = time.ticks_ms()
# Initial state display
reset_system()
# =========================
# Main Non-Blocking Loop
# =========================
while True:
current_time = time.ticks_ms()
# 1. Check for Manual Reset Button
if push_reset.value() == 0:
time.sleep_ms(20) # Debounce delay
if push_reset.value() == 0:
reset_system()
# Wait for button release
while push_reset.value() == 0:
time.sleep_ms(10)
# 2. Automatic Non-Blocking Interval Check
if time.ticks_diff(current_time, last_tick) >= INTERVAL_MS:
last_tick = current_time
update_leds(count)
display_number(count)
print(f"Count = {count}")
count += 1
if count > 9:
count = 0
time.sleep_ms(10) # Short polling delay to prevent CPU overload