Button press detection in Raspberry Pi - Time & Space Complexity
When detecting button presses on a Raspberry Pi, the program often waits and checks repeatedly for input.
We want to understand how the time the program takes grows as it keeps checking for button presses.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
if GPIO.input(18) == GPIO.LOW:
print("Button pressed!")
time.sleep(0.2) # debounce delay
This code continuously checks if a button connected to pin 18 is pressed and prints a message when it is.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that repeatedly reads the button state.
- How many times: It runs indefinitely, checking the button many times per second.
As time passes, the program keeps checking the button state over and over.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (seconds) | Many repeated checks, about 5 per second, so ~50 checks |
| 100 (seconds) | About 500 checks |
| 1000 (seconds) | About 5000 checks |
Pattern observation: The number of checks grows directly with time passed, increasing steadily.
Time Complexity: O(n)
This means the program's work grows linearly with how long it runs, checking the button repeatedly.
[X] Wrong: "The button check only happens once, so time doesn't grow with input."
[OK] Correct: The code uses a loop that runs forever, so it keeps checking many times, making the work grow with time.
Understanding how repeated checks affect program time helps you explain how real devices respond to inputs over time.
What if we changed the code to use an interrupt instead of a loop? How would the time complexity change?