How to Use Button Interrupts with MicroPython?

Estimated read time 2 min read

To use button interrupts with MicroPython, you can utilize the machine.Pin module to configure and handle interrupts. Here’s an example of how you can use button interrupts in MicroPython:

import machine

# Button pin configuration
button_pin = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)

# Interrupt handler function
def button_interrupt_handler(pin):
    print("Button pressed!")

# Configure button pin for interrupt
button_pin.irq(trigger=machine.Pin.IRQ_FALLING, handler=button_interrupt_handler)

# Example code to keep the program running
while True:

In the example above, we import the machine module, which provides access to hardware-specific features.

We initialize the button pin by creating an instance of machine.Pin. In this case, the button is connected to pin 12. We set the pin mode to machine.Pin.IN for input and specify machine.Pin.PULL_UP to enable the internal pull-up resistor.

Next, we define a callback function called button_interrupt_handler. This function will be executed when the button interrupt is triggered.

We configure the button pin for interrupt using the irq method. We set the trigger parameter to machine.Pin.IRQ_FALLING to detect when the button transitions from high to low (button press). We pass the button_interrupt_handler as the handler parameter to specify the function to be called when the interrupt occurs.

Finally, we have a while True loop to keep the program running indefinitely. This ensures that the program continues to respond to button interrupts.

You can modify the pin number, the trigger type, and the behavior of the button_interrupt_handler function to suit your specific requirements. When the button is pressed, the interrupt handler function will be called, and it can perform any desired actions, such as printing a message or triggering other functionality.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply