First GPIO program (LED blink) in Raspberry Pi - Time & Space Complexity
When we write a program to blink an LED on a Raspberry Pi, it runs some instructions repeatedly. Understanding how the time it takes grows helps us know if the program will run smoothly or slow down.
We want to see how the program's running time changes as it blinks more times.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
for i in range(10):
GPIO.output(18, GPIO.HIGH)
time.sleep(1)
GPIO.output(18, GPIO.LOW)
time.sleep(1)
GPIO.cleanup()
This code turns an LED on and off 10 times, waiting 1 second each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that repeats turning the LED on and off.
- How many times: Exactly 10 times in this example.
Each blink cycle takes a fixed amount of time. If we increase the number of blinks, the total time grows directly with that number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 blink cycles |
| 100 | 100 blink cycles |
| 1000 | 1000 blink cycles |
Pattern observation: The total time grows in a straight line as the number of blinks increases.
Time Complexity: O(n)
This means the time to run the program grows directly in proportion to how many times the LED blinks.
[X] Wrong: "The program runs in the same time no matter how many times the LED blinks because each blink is simple."
[OK] Correct: Each blink adds more steps, so more blinks mean more total time. The program takes longer if you blink more times.
Understanding how repeated actions affect running time is a key skill. It helps you explain how your code behaves when it runs longer or with more data, which is useful in many real projects.
"What if we changed the for-loop to blink the LED forever without stopping? How would the time complexity change?"