bouton-interruption.py
The button wired to GP14 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 Raspberry Pi Pico W (RP2040 + 2.4 GHz Wi-Fi radio chip) with MicroPython installed, powered over USB. 1 push button (one leg to GP14, other leg to GND).
Wiring
Button between GP14 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
Install the « Pico W » MicroPython build (BOOTSEL + .uf2), copy the script via Thonny. Since the user LED sits behind the radio chip, output examples use an external LED.
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(14, Pin.IN, Pin.PULL_UP) # bouton vers GND
LED = Pin(15, 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 (GP14)")
while True:
time.sleep_ms(100) # le handler s'execute en interruption