LED toggle with button in Raspberry Pi - Time & Space Complexity
We want to understand how the time it takes to run the LED toggle program changes as we press the button more times.
How does the program's work grow when the button is pressed repeatedly?
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
LED_PIN = 18
BUTTON_PIN = 23
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
led_state = False
while True:
button_state = GPIO.input(BUTTON_PIN)
if button_state == GPIO.LOW:
led_state = not led_state
GPIO.output(LED_PIN, led_state)
time.sleep(0.3) # debounce delay
This code waits for a button press and toggles an LED on or off each time the button is pressed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that continuously checks the button state.
- How many times: It runs forever, repeating as many times as the program runs.
Each time the button is pressed, the program does a small fixed amount of work to toggle the LED.
| Input Size (button presses) | Approx. Operations |
|---|---|
| 10 | About 10 toggles and checks |
| 100 | About 100 toggles and checks |
| 1000 | About 1000 toggles and checks |
Pattern observation: The work grows directly with the number of button presses, one toggle per press.
Time Complexity: O(n)
This means the program's work grows in a straight line with the number of button presses.
[X] Wrong: "The program does a lot more work each time the button is pressed because it loops forever."
[OK] Correct: The loop runs continuously, but the main work only happens when the button is pressed, so work grows only with presses, not time running.
Understanding how repeated actions affect program work helps you explain how your code behaves in real devices, showing you can think about efficiency clearly.
"What if we added a second button to toggle the LED off only? How would the time complexity change?"