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?"