Software PWM with RPi.GPIO in Raspberry Pi - Time & Space Complexity
When using software PWM on a Raspberry Pi, the program repeatedly changes pin states to create a signal.
We want to understand how the time spent grows as we increase the PWM frequency or duration.
Analyze the time complexity of the following software PWM code using RPi.GPIO.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm_pin = 18
frequency = 50 # Hz
period = 1 / frequency
duty_cycle = 0.5 # 50%
for i in range(100):
GPIO.output(pwm_pin, GPIO.HIGH)
time.sleep(period * duty_cycle)
GPIO.output(pwm_pin, GPIO.LOW)
time.sleep(period * (1 - duty_cycle))
This code creates a 50 Hz PWM signal on pin 18 by turning it on and off 100 times.
Look at what repeats in the code.
- Primary operation: The loop that sets the pin HIGH and LOW repeatedly.
- How many times: Exactly 100 times, as set by the for-loop.
The total time grows directly with the number of PWM cycles we run.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 cycles of HIGH and LOW switching |
| 100 | 100 cycles of HIGH and LOW switching |
| 1000 | 1000 cycles of HIGH and LOW switching |
Pattern observation: If you double the number of cycles, the total operations double too.
Time Complexity: O(n)
This means the time to run the PWM signal grows directly in proportion to the number of cycles you want.
[X] Wrong: "The time to run PWM stays the same no matter how many cycles I run."
[OK] Correct: Each cycle requires turning the pin on and off, so more cycles mean more work and more time.
Understanding how loops affect timing is important when controlling hardware like LEDs or motors with a Raspberry Pi.
This skill shows you can reason about how your code's running time changes as you ask it to do more.
"What if we changed the loop to run indefinitely until stopped? How would the time complexity be described then?"