bouton-interruption.py

RP2350 (generic / RP2350-based boards) · File : bouton-interruption.py · Language : Python · Use case : Basculer une LED sur appui bouton avec interruption matérielle

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 RP2350 (dual Cortex-M33) 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 the « RP2350 » MicroPython build via BOOTSEL (.uf2), then copy the script to the drive. The user LED pin varies by manufacturer: check the board documentation.

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

← Back to the board