LED brightness control in Raspberry Pi - Time & Space Complexity
When controlling LED brightness on a Raspberry Pi, we often adjust values repeatedly in a loop.
We want to understand how the time it takes grows as we change the number of brightness steps.
Analyze the time complexity of the following code snippet.
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
LED_PIN = 18
GPIO.setup(LED_PIN, GPIO.OUT)
pwm = GPIO.PWM(LED_PIN, 1000)
pwm.start(0)
for brightness in range(0, 101):
pwm.ChangeDutyCycle(brightness)
time.sleep(0.01)
pwm.stop()
GPIO.cleanup()
This code gradually increases LED brightness from 0% to 100% in steps, pausing briefly at each step.
- Primary operation: The for-loop that changes brightness 101 times.
- How many times: Once for each brightness level from 0 to 100.
As the number of brightness steps increases, the loop runs more times, increasing total operations.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 brightness changes |
| 100 | 100 brightness changes |
| 1000 | 1000 brightness changes |
Pattern observation: The total work grows directly with the number of brightness steps.
Time Complexity: O(n)
This means the time to complete grows in a straight line as you increase brightness steps.
[X] Wrong: "Changing brightness a few more times won't affect the total time much."
[OK] Correct: Each brightness change takes time, so more steps add up and increase total time linearly.
Understanding how loops affect time helps you explain how your code scales, a key skill in many programming tasks.
"What if we changed the loop to increase brightness in steps of 5 instead of 1? How would the time complexity change?"