from machine import Pin
import time
led = Pin(23, Pin.OUT)
button = Pin(22, Pin.IN, Pin.PULL_DOWN)
isLedOn = False
lastReading = button.value()
stableState = lastReading
lastDebounceTime = time.ticks_ms()
debounce_ms = 50 # debounce time in milliseconds
i = 0
while True:
reading = button.value()
now = time.ticks_ms()
if reading != lastReading:
lastDebounceTime = now
if time.ticks_diff(now, lastDebounceTime) > debounce_ms:
if reading != stableState:
stableState = reading
# Detect button RELEASE (falling edge)
if stableState == 0:
isLedOn = not isLedOn
led.value(isLedOn)
print(
f"Button released | LED: {isLedOn} | time: {now} | loop: {i}"
)
lastReading = reading
i += 1