0
0
Raspberry Piprogramming~5 mins

PWM frequency and duty cycle relationship in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: PWM frequency and duty cycle relationship
O(frequency x duration)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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)
1050
100500
10005000

Pattern observation: The number of toggles grows linearly as frequency increases.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how PWM frequency affects program execution helps you reason about timing and performance in embedded systems, a useful skill in many technical roles.

Self-Check

What if we doubled the duration instead of the frequency? How would the time complexity change?