PWM helps control devices like motors or lights smoothly by turning power on and off very fast. This makes them act like they get different power levels, even though the power is just on or off.
0
0
Why PWM is needed for analog-like control in Raspberry Pi
Introduction
You want to dim an LED light smoothly instead of just on or off.
You need to control the speed of a small motor in a robot.
You want to adjust the brightness of a screen backlight.
You want to control the position of a servo motor precisely.
You want to save power by giving only the needed amount of energy.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO import time pin_number = 18 frequency = 1000 gpio.setmode(GPIO.BCM) gpio.setup(pin_number, GPIO.OUT) pwm = GPIO.PWM(pin_number, frequency) pwm.start(0) # Change duty cycle to control power pwm.ChangeDutyCycle(50) # Stop PWM when done pwm.stop() GPIO.cleanup()
pin_number is the GPIO pin connected to your device.
frequency is how fast the PWM signal switches on and off (in Hz).
Examples
This example sets up PWM on pin 18 with 1 kHz frequency and 50% power, running for 5 seconds.
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 1000) # 1 kHz frequency pwm.start(50) # 50% duty cycle # Run for 5 seconds time.sleep(5) pwm.stop() GPIO.cleanup()
Change the power level to 75% without stopping PWM.
Raspberry Pi
pwm.ChangeDutyCycle(75) # Increase power to 75%
Sample Program
This program slowly increases the power to a device connected to pin 18 in steps, showing how PWM changes the power level smoothly.
Raspberry Pi
import RPi.GPIO as GPIO import time # Setup pin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(pin, GPIO.OUT) # Create PWM instance at 500 Hz pwm = GPIO.PWM(pin, 500) # Start PWM at 0% duty cycle (off) pwm.start(0) # Gradually increase brightness for dc in range(0, 101, 20): # 0%, 20%, 40%, 60%, 80%, 100% print(f"Setting duty cycle to {dc}%") pwm.ChangeDutyCycle(dc) time.sleep(1) # Stop PWM and cleanup pwm.stop() GPIO.cleanup()
OutputSuccess
Important Notes
PWM does not change voltage but changes how long the power is on in each cycle.
Devices like LEDs or motors respond to the average power they get, so PWM makes them act like they get different power levels.
Always clean up GPIO pins after use to avoid warnings or errors.
Summary
PWM lets you control power smoothly by switching it on and off quickly.
This helps devices behave like they get different power levels without needing special hardware.
Using PWM on Raspberry Pi is easy with the RPi.GPIO library.