import utime
import machine
# ---------------------------------------------------------
# 1. HARDWARE SETUP
# ---------------------------------------------------------
# Onboard LED (GP25 on Pico / Pico W)
led = machine.Pin("LED", machine.Pin.OUT)
# Push button on GP5, connected to 3.3V
# We enable an internal pull-down resistor:
# Button not pressed -> 0
# Button pressed -> 1
button = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_DOWN)
# ---------------------------------------------------------
# 2. VARIABLES FOR BUTTON STATE & DEBOUNCE
# ---------------------------------------------------------
previous_state = 0 # last stable reading of the button (0 or 1)
press_count = 0 # how many times the button has been pressed
last_change_time = utime.ticks_ms() # timestamp of last state change
DEBOUNCE_MS = 2 # minimum time for stable signal
# ---------------------------------------------------------
# 3. FUNCTION: CHECK BUTTON WITH DEBOUNCE
# ---------------------------------------------------------
def update_button():
"""
Reads the button, applies a debounce filter,
and increases press_count on every complete
press-and-release cycle.
"""
global previous_state, press_count, last_change_time
# Read the raw button value (0 or 1)
current_state = button.value()
now = utime.ticks_ms()
# Did the button reading change?
if current_state != previous_state:
# Has the state been stable for long enough?
if utime.ticks_diff(now, last_change_time) > DEBOUNCE_MS:
# Count only a RELEASE (1 -> 0)
if previous_state == 1 and current_state == 0:
press_count += 1
print("Button press detected! Total =", press_count)
# Update stored values
previous_state = current_state
last_change_time = now
# ---------------------------------------------------------
# 4. MAIN PROGRAM LOOP
# ---------------------------------------------------------
print("Program started. Press the button 3 times.")
led.value(1) # LED on while waiting
while press_count < 3: # stop after three presses
update_button()
led.value(0) # LED turns OFF to show program finished
print("Finished! Final count:", press_count)