Button with interrupt (GPIO.add_event_detect) in Raspberry Pi - Time & Space Complexity
When using a button with an interrupt on a Raspberry Pi, it is important to understand how the program reacts over time as button presses happen.
We want to know how the program's work grows as more button presses occur.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
import time
def button_pressed(channel):
print("Button was pressed!")
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(18, GPIO.FALLING, callback=button_pressed, bouncetime=200)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
This code sets up a button on pin 18 and uses an interrupt to call a function when the button is pressed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The callback function
button_pressedruns each time the button is pressed. - How many times: It runs once per button press, which depends on user interaction.
Each button press triggers the callback once, so the work grows directly with the number of presses.
| Input Size (button presses) | Approx. Operations (callback calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows linearly with the number of button presses.
Time Complexity: O(n)
This means the program's work increases directly in proportion to how many times the button is pressed.
[X] Wrong: "The program runs the callback constantly, even without button presses."
[OK] Correct: The callback only runs when the button is pressed, so the program is mostly idle and does not waste time.
Understanding how interrupts handle events efficiently is a useful skill for real-world projects where resources are limited and responsiveness matters.
"What if we replaced the interrupt with a loop constantly checking the button state? How would the time complexity change?"
Practice
What is the main purpose of using GPIO.add_event_detect with a button on a Raspberry Pi?
Solution
Step 1: Understand what
This function listens for changes on a GPIO pin and triggers a callback or event without needing to check the pin repeatedly.GPIO.add_event_detectdoesStep 2: Compare options to the function's purpose
Only To detect button presses instantly without constantly checking in a loop correctly describes the purpose: detecting button presses instantly without polling.Final Answer:
To detect button presses instantly without constantly checking in a loop -> Option DQuick Check:
Event detection = instant button press response [OK]
- Confusing input and output pin setup
- Thinking it disables the button
- Assuming it changes voltage levels
Which of the following is the correct syntax to add an event detect for a button press on GPIO pin 17 for a falling edge?
GPIO.add_event_detect(____, GPIO.FALLING, callback=my_callback)
Solution
Step 1: Identify the pin number argument
The first argument toGPIO.add_event_detectis the pin number as an integer, here 17.Step 2: Check the options for correct type
17 uses integer 17, which is correct. '17' uses a string which is invalid. Options C and D are incorrect because they are not pin numbers.Final Answer:
17 -> Option AQuick Check:
Pin number must be integer 17 [OK]
- Using pin number as a string
- Passing edge type or callback as pin number
- Missing required arguments
Consider this code snippet:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
button_pressed = False
def button_callback(channel):
global button_pressed
button_pressed = True
GPIO.add_event_detect(18, GPIO.FALLING, callback=button_callback, bouncetime=200)
print("Waiting for button press...")
while not button_pressed:
time.sleep(0.1)
print("Button was pressed!")
GPIO.cleanup()What will be printed when the button connected to pin 18 is pressed?
Solution
Step 1: Understand program flow before button press
The program prints "Waiting for button press..." and then waits in a loop untilbutton_pressedbecomes True.Step 2: Effect of button press and callback
When the button is pressed, the callback setsbutton_pressed = True, breaking the loop and printing "Button was pressed!" before cleanup.Final Answer:
Waiting for button press... Button was pressed! -> Option CQuick Check:
Prints before and after button press [OK]
- Thinking callback prints directly
- Ignoring the loop waiting for flag
- Assuming no output before press
What is wrong with this code snippet that tries to detect a button press on GPIO pin 22?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN)
def on_press(channel):
print("Button pressed")
GPIO.add_event_detect(22, GPIO.RISING, callback=on_press)
while True:
pass
GPIO.cleanup()Solution
Step 1: Check pin setup for input
The code sets pin 22 as input but does not specify pull-up or pull-down resistors, which can cause floating input and unreliable detection.Step 2: Review other options
Callback functions do not need to return values. The cleanup call is unreachable but not an error. Both RISING and FALLING edges are valid depending on wiring.Final Answer:
Missing pull-up or pull-down resistor setup on pin 22 -> Option AQuick Check:
Input pins need pull resistors to avoid floating [OK]
- Ignoring pull-up/down resistor setup
- Expecting callback to return a value
- Misunderstanding edge types
You want to detect both button press and release events on GPIO pin 5 using interrupts. Which code snippet correctly sets up event detection for both edges and avoids multiple triggers due to button bounce?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def button_event(channel):
if GPIO.input(channel) == GPIO.LOW:
print("Button pressed")
else:
print("Button released")
# Which line correctly adds event detection?Solution
Step 1: Identify edge detection for press and release
To detect both press and release, useGPIO.BOTHto catch rising and falling edges.Step 2: Add debounce to avoid multiple triggers
Button bounce causes multiple events; settingbouncetime=300ms helps debounce effectively.Final Answer:
GPIO.add_event_detect(5, GPIO.BOTH, callback=button_event, bouncetime=300) -> Option BQuick Check:
Both edges + debounce = correct setup [OK]
- Using only RISING or FALLING edge misses events
- Forgetting debounce causes multiple prints
- Not setting pull-up resistor on input pin
Ready to prove it?
Pass the test and this pattern moves unknown
