0
0
Raspberry Piprogramming~5 mins

Button with interrupt (GPIO.add_event_detect) in Raspberry Pi

Choose your learning style9 modes available
Introduction

Using a button with an interrupt lets your Raspberry Pi react immediately when the button is pressed, without constantly checking its state.

You want to run a function right when a button is pressed without delay.
You want to save CPU power by not constantly checking the button state.
You want your program to do other tasks and only respond when the button is pressed.
You want to detect button presses in real-time for a project like a game or a remote control.
Syntax
Raspberry Pi
GPIO.add_event_detect(pin_number, GPIO.RISING or GPIO.FALLING, callback=function_name, bouncetime=milliseconds)

pin_number is the GPIO pin where the button is connected.

GPIO.RISING detects when the button is pressed (signal goes from low to high).

GPIO.FALLING detects when the button is released (signal goes from high to low).

callback is the function that runs when the event happens.

bouncetime helps ignore quick repeated signals caused by button noise.

Examples
Detects when the button connected to pin 17 is pressed and calls button_pressed function.
Raspberry Pi
GPIO.add_event_detect(17, GPIO.RISING, callback=button_pressed, bouncetime=200)
Detects when the button connected to pin 22 is released and calls button_released function.
Raspberry Pi
GPIO.add_event_detect(22, GPIO.FALLING, callback=button_released)
Sample Program

This program sets up a button on GPIO pin 18. When the button is pressed, it prints a message immediately using an interrupt. The program runs until you stop it with Ctrl+C.

Raspberry Pi
import RPi.GPIO as GPIO
import time

BUTTON_PIN = 18

GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def button_callback(channel):
    print("Button was pressed!")

GPIO.add_event_detect(BUTTON_PIN, GPIO.RISING, callback=button_callback, bouncetime=300)

print("Waiting for button press...")
try:
    while True:
        time.sleep(0.1)  # Keep program running
except KeyboardInterrupt:
    print("Program stopped")
finally:
    GPIO.cleanup()
OutputSuccess
Important Notes

Always use GPIO.cleanup() at the end to reset the pins safely.

Use bouncetime to avoid multiple triggers from one press due to button noise.

The callback function runs in a separate thread, so keep it short and simple.

Summary

Use GPIO.add_event_detect to react instantly to button presses without waiting.

Set the correct edge (RISING or FALLING) depending on your button wiring.

Always clean up GPIO pins when your program ends to avoid issues.