bouton-interruption.py
The button wired to GP15 toggles the LED through a hardware interrupt (irq): no CPU cycle wasted polling the pin. A 50 ms filter inside the handler removes mechanical contact bounce.
Hardware
A generic RP2040 (dual Cortex-M0+) board programmed with MicroPython. 1 push button (one leg to GP15, other leg to GND).
Wiring
Button between GP15 and GND; the pull-up resistor is enabled by Pin.PULL_UP on the board side.
How it works
BTN.irq triggers on the falling edge (press to ground). The handler compares time.ticks_ms() with the last edge, ignores bounces shorter than 50 ms, then flips the LED state.
Running it
Flash MicroPython via BOOTSEL (.uf2 file), then copy the script to the board drive. Check your board's user LED pin (often GP25) and adapt if needed.
Variants
Set the trigger to Pin.IRQ_RISING | Pin.IRQ_FALLING to count every edge, or stack several buttons with one handler per pin.
bouton-interruption.py
# Bascule LED sur appui bouton : interruption materielle + anti-rebond.
from machine import Pin
import time
BTN = Pin(15, Pin.IN, Pin.PULL_UP) # bouton vers GND
LED = Pin(25, Pin.OUT)
etat_led = [0] # liste mutable : modifiable dans le handler
dernier = [0] # horodatage du dernier front valide
def sur_appui(pin):
maintenant = time.ticks_ms()
# Anti-rebond : on ignore les fronts de moins de 50 ms apres le dernier.
if time.ticks_diff(maintenant, dernier[0]) < 50:
return
dernier[0] = maintenant
etat_led[0] = 1 - etat_led[0]
LED.value(etat_led[0])
print("Appui -> LED", "ON" if etat_led[0] else "OFF")
BTN.irq(trigger=Pin.IRQ_FALLING, handler=sur_appui)
print("Pret : appuyez sur le bouton (GP15)")
while True:
time.sleep_ms(100) # le handler s'execute en interruption