0
0
Raspberry Piprogramming~30 mins

Button with interrupt (GPIO.add_event_detect) in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
Button with interrupt (GPIO.add_event_detect)
📖 Scenario: You have a Raspberry Pi connected to a physical button. You want to detect when the button is pressed without constantly checking its state. Using an interrupt, your program will respond immediately when the button is pressed.
🎯 Goal: Build a Python program that sets up a button on GPIO pin 18 and uses GPIO.add_event_detect to run a function when the button is pressed.
📋 What You'll Learn
Use the RPi.GPIO library
Set up GPIO pin 18 as input with a pull-up resistor
Create a function called button_pressed that prints 'Button was pressed!'
Use GPIO.add_event_detect to call button_pressed on a falling edge
Keep the program running to listen for button presses
💡 Why This Matters
🌍 Real World
Physical buttons are often used in Raspberry Pi projects to control devices or trigger actions immediately without delay.
💼 Career
Understanding GPIO interrupts is important for embedded systems, IoT devices, and hardware interfacing roles.
Progress0 / 4 steps
1
Set up GPIO and button pin
Import the RPi.GPIO library as GPIO. Set the GPIO mode to GPIO.BCM. Create a variable called button_pin and set it to 18. Set up button_pin as an input with a pull-up resistor using GPIO.setup.
Raspberry Pi
Need a hint?

Use GPIO.setmode(GPIO.BCM) to select pin numbering. Use GPIO.setup with pull_up_down=GPIO.PUD_UP to enable the pull-up resistor.

2
Create the button press handler function
Define a function called button_pressed that takes one argument called channel. Inside the function, write a print statement that outputs exactly "Button was pressed!".
Raspberry Pi
Need a hint?

The function must have one parameter named channel. Use print("Button was pressed!") inside the function.

3
Add event detection for the button press
Use GPIO.add_event_detect on button_pin to detect a falling edge. Set the callback to the button_pressed function.
Raspberry Pi
Need a hint?

Use GPIO.add_event_detect(button_pin, GPIO.FALLING, callback=button_pressed, bouncetime=200) to detect button presses and avoid bouncing.

4
Keep the program running to listen for button presses
Write a try block with an infinite while True loop that does nothing (use pass). Add an except KeyboardInterrupt block that calls GPIO.cleanup(). This keeps the program running and cleans up GPIO on exit.
Raspberry Pi
Need a hint?

The program should run forever until you press Ctrl+C. When the button is pressed, it prints the message. On Ctrl+C, GPIO pins are cleaned up.