PWM Output: Fading an LED with Python
Software PWM on the Raspberry Pi, using RPi.GPIO's built-in PWM object to fade an LED smoothly.
You'll need: the same LED-and-resistor wiring from Lesson rpi-09.
Unlike the Arduino Uno, which generates PWM in dedicated hardware on specific marked pins (Lesson ard-08), most GPIO pins on the Raspberry Pi generate PWM in software, managed by the operating system rather than a dedicated timer circuit. This makes it usable on nearly any GPIO pin, at some cost to timing precision compared to true hardware PWM — perfectly fine for fading an LED, less ideal for something timing-critical.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
pwm = GPIO.PWM(17, 500) # pin 17, 500Hz
pwm.start(0)
try:
while True:
for duty in range(0, 101, 5):
pwm.ChangeDutyCycle(duty)
time.sleep(0.05)
for duty in range(100, -1, -5):
pwm.ChangeDutyCycle(duty)
time.sleep(0.05)
except KeyboardInterrupt:
pwm.stop()
GPIO.cleanup()GPIO.PWM(17, 500) creates a PWM controller object on pin 17, running at 500Hz. pwm.start(0) begins it at a 0% duty cycle (off), and pwm.ChangeDutyCycle(duty) updates it — note this takes a percentage from 0 to 100, unlike Arduino's analogWrite(), which uses a 0–255 range. The for loop here works exactly like the fade from Lesson ard-11, just stepping through percentages instead.
Always call pwm.stop() before GPIO.cleanup() when exiting — skipping it can leave the PWM signal running in an inconsistent state on that pin.