from machine import Pin
import time
# Pico onboard LED
led = Pin("LED", Pin.OUT)
# Button input with pullup
button = Pin(15, Pin.IN, Pin.PULL_UP)
# Shared state
interrupt_count = 0
press_count = 0
release_count = 0
event_pending = False
# Debounce timing
last_interrupt_ms = 0
DEBOUNCE_MS = 50
def button_isr(pin):
global interrupt_count
global press_count
global release_count
global event_pending
global last_interrupt_ms
now = time.ticks_ms()
# Debounce
if time.ticks_diff(now, last_interrupt_ms) < DEBOUNCE_MS:
return
last_interrupt_ms = now
interrupt_count += 1
if pin.value() == 0:
press_count += 1
else:
release_count += 1
event_pending = True
# Trigger on both edges
button.irq(
trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING,
handler=button_isr
)
print("GPIO Interrupt Demo")
print("Press and release the button on GP15")
last_report = time.ticks_ms()
while True:
# Process interrupt events outside ISR
if event_pending:
event_pending = False
led.toggle()
print(
"Interrupts:",
interrupt_count,
"Presses:",
press_count,
"Releases:",
release_count
)
# Periodic status report
if time.ticks_diff(time.ticks_ms(), last_report) > 5000:
last_report = time.ticks_ms()
print("\n--- Status ---")
print("Total interrupts:", interrupt_count)
print("Press events:", press_count)
print("Release events:", release_count)
print("----------------")
time.sleep_ms(10)