import machine
# -------------------------
# Global variables
# -------------------------
debounce_time_ms = 50 #ms
debouncing = False
debounce_timer = machine.Timer()
red_led_state = 0
# -------------------------
# Timer callback
# -------------------------
def end_debounce(timer):
global debouncing
debouncing = False
# NOTE: no print here (still IRQ context)
# -------------------------
# GPIO interrupt handler
# -------------------------
def gpio_handler(pin):
global debouncing, red_led_state
if debouncing:
return
debouncing = True
# Minimal work inside IRQ
debounce_timer.init(
period = debounce_time_ms,
mode = machine.Timer.ONE_SHOT,
callback = end_debounce
)
# Set a flag ONLY (safe)
red_led_state ^= 1 # toggle the value
led_red.value(red_led_state)
#print("Button pressed!") # OK for demos, but mention risk
# -------------------------
# GPIO setup
# -------------------------
button = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_DOWN)
button.irq(trigger = machine.Pin.IRQ_RISING, handler = gpio_handler)
led_red = machine.Pin(2, machine.Pin.OUT)
led_red.value(red_led_state)
print("Waiting for GPIO 5 interrupts with debounce...")
# -------------------------
# Main loop
# -------------------------
while True:
pass