0
0
Raspberry Piprogramming~5 mins

PWM frequency and duty cycle relationship in Raspberry Pi

Choose your learning style9 modes available
Introduction

PWM helps control devices by turning power on and off quickly. Frequency and duty cycle decide how fast and how long the power is on.

To control the brightness of an LED by changing how long it stays on.
To adjust the speed of a motor by changing how fast the power pulses.
To create sounds by changing the frequency of the pulses.
To control heating elements by adjusting power delivery timing.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO
import time

pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)

pwm = GPIO.PWM(pin, frequency)  # frequency in Hz
pwm.start(duty_cycle)          # duty_cycle in percent (0-100)

# To change duty cycle later:
pwm.ChangeDutyCycle(new_duty_cycle)

# To change frequency later:
pwm.ChangeFrequency(new_frequency)

# Stop PWM
pwm.stop()
GPIO.cleanup()

Frequency is how many times the signal repeats per second (Hz).

Duty cycle is the percentage of time the signal is ON in each cycle.

Examples
This sets a PWM on pin 18 with 1000 pulses per second, ON half the time.
Raspberry Pi
pwm = GPIO.PWM(18, 1000)  # 1000 Hz frequency
pwm.start(50)               # 50% duty cycle
Now the signal stays ON 75% of each cycle, making the device brighter or faster.
Raspberry Pi
pwm.ChangeDutyCycle(75)  # Change duty cycle to 75%
This slows the pulses to 500 times per second, which can affect sound or motor smoothness.
Raspberry Pi
pwm.ChangeFrequency(500)  # Change frequency to 500 Hz
Sample Program

This program starts PWM on pin 18 at 1000 Hz with 10% duty cycle. It then increases the duty cycle in steps, making the device get brighter or faster. After that, it changes the frequency to 500 Hz and waits before cleaning up.

Raspberry Pi
import RPi.GPIO as GPIO
import time

pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)

pwm = GPIO.PWM(pin, 1000)  # 1000 Hz frequency
pwm.start(10)             # Start with 10% duty cycle

try:
    for dc in range(10, 101, 30):  # Increase duty cycle from 10% to 100%
        print(f"Setting duty cycle to {dc}%")
        pwm.ChangeDutyCycle(dc)
        time.sleep(1)
    pwm.ChangeFrequency(500)  # Change frequency to 500 Hz
    print("Frequency changed to 500 Hz")
    time.sleep(2)
finally:
    pwm.stop()
    GPIO.cleanup()
OutputSuccess
Important Notes

Higher frequency means faster pulses, which can make motors run smoother or LEDs flicker less.

Changing duty cycle changes how much power the device gets without changing frequency.

Always clean up GPIO pins to avoid warnings or errors on next run.

Summary

PWM frequency controls how fast the power pulses repeat.

Duty cycle controls how long the power stays ON in each pulse.

Changing frequency or duty cycle changes device behavior like brightness or speed.