How to Use Interrupts on Raspberry Pi Pico: Simple Guide
To use an
interrupt on Raspberry Pi Pico, attach an interrupt handler function to a GPIO pin using Pin.irq(). This lets your program respond immediately to events like button presses without constantly checking the pin state.Syntax
Use the Pin.irq() method to set up an interrupt on a GPIO pin. You provide a handler function and specify the trigger event.
handler: The function called when the interrupt triggers.trigger: The event that triggers the interrupt, e.g.,Pin.IRQ_FALLINGfor button press.debounce: Optional, to ignore rapid repeated triggers.
python
pin.irq(handler=callback_function, trigger=Pin.IRQ_FALLING)
Example
This example shows how to use an interrupt to detect a button press on GPIO 15 and toggle an LED on GPIO 25.
python
from machine import Pin import time led = Pin(25, Pin.OUT) button = Pin(15, Pin.IN, Pin.PULL_UP) # Interrupt handler toggles the LED interrupt_triggered = False def button_handler(pin): global interrupt_triggered interrupt_triggered = True # Attach interrupt on falling edge (button press) button.irq(handler=button_handler, trigger=Pin.IRQ_FALLING) print("Press the button to toggle the LED.") while True: if interrupt_triggered: led.toggle() interrupt_triggered = False time.sleep(0.1)
Output
Press the button to toggle the LED.
Common Pitfalls
Common mistakes when using interrupts on Raspberry Pi Pico include:
- Doing heavy or blocking work inside the interrupt handler, which can cause missed interrupts.
- Not using
Pin.PULL_UPorPin.PULL_DOWNresistors, leading to noisy signals. - Failing to debounce the button, causing multiple triggers from one press.
- Not declaring variables as
globalwhen modified inside the handler.
python
from machine import Pin # Wrong: heavy work inside handler # def button_handler(pin): # for i in range(1000000): # pass # This blocks and is bad # Right: just set a flag interrupt_triggered = False def button_handler(pin): global interrupt_triggered interrupt_triggered = True
Quick Reference
| Term | Description |
|---|---|
| Pin.irq() | Attach an interrupt handler to a pin |
| handler | Function called on interrupt |
| trigger | Event type: IRQ_FALLING, IRQ_RISING, or both |
| Pin.PULL_UP / PULL_DOWN | Internal resistor to stabilize input |
| Debounce | Ignore rapid repeated triggers |
Key Takeaways
Use Pin.irq() with a handler function to respond to GPIO events immediately.
Keep interrupt handlers short and avoid heavy processing inside them.
Use internal pull-up or pull-down resistors to prevent noisy signals.
Set a flag in the interrupt handler and handle logic in the main loop.
Debounce buttons to avoid multiple triggers from a single press.