Why LED and button projects build hardware confidence in Raspberry Pi - Performance Analysis
When working with LED and button projects on a Raspberry Pi, it's helpful to understand how the time your program takes grows as you add more components.
We want to see how the program's running time changes when you control many LEDs or read many buttons.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
led_pins = [17, 27, 22]
button_pins = [5, 6, 13]
for pin in led_pins:
GPIO.setup(pin, GPIO.OUT)
for pin in button_pins:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
for pin in led_pins:
GPIO.output(pin, GPIO.HIGH)
# wait for button press here (simplified)
GPIO.output(pin, GPIO.LOW)
This code sets up three LEDs and three buttons, then turns each LED on and off, waiting for a button press in between.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through LED pins to set up and control each LED.
- How many times: The loops run once per LED or button, so 3 times each in this example.
As you add more LEDs and buttons, the program runs more setup and control commands.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | About 9 (3 LEDs + 3 buttons setup + 3 LED controls) |
| 10 | About 30 (10 LEDs + 10 buttons setup + 10 LED controls) |
| 100 | About 300 (100 LEDs + 100 buttons setup + 100 LED controls) |
Pattern observation: The number of operations grows roughly in direct proportion to the number of LEDs and buttons.
Time Complexity: O(n)
This means the time your program takes grows in a straight line as you add more LEDs and buttons.
[X] Wrong: "Adding more LEDs or buttons won't affect how long the program runs."
[OK] Correct: Each LED and button requires setup and control steps, so more components mean more work for the program.
Understanding how your program's time grows with hardware components shows you can think about real devices and their limits, a useful skill for many projects.
"What if we controlled all LEDs at the same time instead of one by one? How would the time complexity change?"