PWM frequency and duty cycle relationship in Raspberry Pi - Time & Space Complexity
When working with PWM on a Raspberry Pi, it's important to understand how changing frequency and duty cycle affects the program's running time.
We want to see how the program's work grows as we change these PWM settings.
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)
pwm = GPIO.PWM(18, 1000) # 1000 Hz frequency
pwm.start(50) # 50% duty cycle
time.sleep(5)
pwm.stop()
GPIO.cleanup()
This code sets up PWM on pin 18 with a frequency of 1000 Hz and a 50% duty cycle, runs it for 5 seconds, then stops.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The PWM signal toggling the pin on and off repeatedly at the set frequency.
- How many times: The pin toggles approximately frequency x duration times (e.g., 1000 Hz x 5 seconds = 5000 times).
As the PWM frequency increases, the number of pin toggles grows proportionally for the same duration.
| Input Size (Frequency in Hz) | Approx. Operations (toggles in 5 sec) |
|---|---|
| 10 | 50 |
| 100 | 500 |
| 1000 | 5000 |
Pattern observation: The number of toggles grows linearly as frequency increases.
Time Complexity: O(frequency x duration)
This means the work done grows directly with how fast the PWM signal toggles and how long it runs.
[X] Wrong: "Changing the duty cycle changes how many times the pin toggles."
[OK] Correct: The duty cycle changes how long the pin stays on versus off, but the total number of toggles depends mainly on frequency and duration, not duty cycle.
Understanding how PWM frequency affects program execution helps you reason about timing and performance in embedded systems, a useful skill in many technical roles.
What if we doubled the duration instead of the frequency? How would the time complexity change?