0
0
Raspberry Piprogramming~3 mins

Why Button with interrupt (GPIO.add_event_detect) in Raspberry Pi? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your Raspberry Pi could listen for button presses without wasting energy or missing a single tap?

The Scenario

Imagine you want to detect when a button is pressed on your Raspberry Pi. You write a program that constantly checks the button's state in a loop, waiting for it to change.

The Problem

This constant checking, called polling, wastes CPU power and can miss quick button presses if your loop is slow. It also makes your program less responsive and harder to manage.

The Solution

Using GPIO.add_event_detect lets your program wait quietly and only react when the button is actually pressed. This is like setting an alarm that rings only when needed, saving resources and improving response.

Before vs After
Before
while True:
    if GPIO.input(button_pin) == GPIO.HIGH:
        print('Button pressed')
After
GPIO.add_event_detect(button_pin, GPIO.RISING, callback=button_pressed)
What It Enables

This lets your Raspberry Pi respond instantly to button presses without wasting energy or missing events.

Real Life Example

Think of a doorbell system where the Raspberry Pi only rings the chime when someone presses the button, instead of constantly checking if the button is pressed.

Key Takeaways

Polling wastes CPU and can miss quick presses.

GPIO.add_event_detect waits efficiently for button events.

Improves responsiveness and saves resources.