🛠 Variateur de lumière : PWM sur une LED
Objectives
Understand Pulse Width Modulation (PWM): vary the brightness of an LED by changing the duty cycle. The J8 connector on the Pi 2 exposes a hardware PWM output on GPIO18; you will first use the software PWM from RPi.GPIO (simple and flexible), then enable hardware PWM via config.txt.
Hardware
- Raspberry Pi 2 Model B running 32-bit Raspberry Pi OS
- LED + 330 Ω resistor on GPIO18 (pin 12 of J8)
- Package: sudo apt install python3-rpi.gpio
Complete Code
#!/usr/bin/env python3
"""pwm_led.py — rampe d'intensite PWM (logiciel) sur GPIO18."""
import RPi.GPIO as GPIO
from time import sleep
PIN = 18 # aussi la sortie PWM materielle du J8
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)
pwm = GPIO.PWM(PIN, 1000) # frequence 1 kHz
pwm.start(0)
try:
while True:
for dc in range(0, 101, 5): # monte doucement
pwm.ChangeDutyCycle(dc)
sleep(0.05)
for dc in range(100, -1, -5): # descend doucement
pwm.ChangeDutyCycle(dc)
sleep(0.05)
except KeyboardInterrupt:
pass
pwm.stop
GPIO.cleanup
Expected Verification
The LED brightens and then dims in a continuous loop (breathing effect). At 0 % it is off, at 100 % it is at full intensity. For hardware PWM, add dtoverlay=pwm (or pwm-2chan) to /boot/config.txt, reboot, then control /sys/class/pwm: the signal remains accurate even under load, unlike software PWM.
Common Errors
- Confusion between hardware and software PWM: the software PWM from RPi.GPIO works on any pin but degrades under heavy CPU load; the hardware PWM (GPIO18) remains precise.
- Forgetting GPIO.cleanup: the pin remains occupied and the next script fails.
- Frequency too low: below ~100 Hz the LED flickers visibly; stay at 1 kHz.
- Using pin 12 for hardware PWM without editing config.txt or rebooting: nothing appears in /sys/class/pwm.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython