# Experiment B: Button Debouncing (PULL_UP)
import machine
import utime
button = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP) # pressed = LOW
led = machine.Pin(16, machine.Pin.OUT)
debounce_delay = 20 # ms
last_stable_state = button.value()
last_raw_state = last_stable_state
last_change_time = utime.ticks_ms()
press_count = 0
print("š Debouncing started (PULL_UP). Pressed = LOW.")
try:
while True:
raw = button.value()
if raw != last_raw_state:
last_raw_state = raw
last_change_time = utime.ticks_ms()
if utime.ticks_diff(utime.ticks_ms(), last_change_time) > debounce_delay:
if raw != last_stable_state:
last_stable_state = raw
if last_stable_state == 0: # falling to LOW = press
led.value(1)
press_count += 1
print(f"ā
PRESSED! Count: {press_count}")
else: # rising to HIGH = release
led.value(0)
print("š RELEASED.")
utime.sleep_ms(5)
except KeyboardInterrupt:
led.value(0)
print(f"\nš Stopped. Total reliable presses: {press_count}")