0
0
Raspberry Piprogramming~5 mins

Software PWM with RPi.GPIO in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Software PWM with RPi.GPIO
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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

The total time grows directly with the number of PWM cycles we run.

Input Size (n)Approx. Operations
1010 cycles of HIGH and LOW switching
100100 cycles of HIGH and LOW switching
10001000 cycles of HIGH and LOW switching

Pattern observation: If you double the number of cycles, the total operations double too.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the PWM signal grows directly in proportion to the number of cycles you want.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we changed the loop to run indefinitely until stopped? How would the time complexity be described then?"