🛠 Variateur de luminosité LED en PWM
Objectives
Vary the brightness of an LED using PWM (Pulse Width Modulation) on the Raspberry Pi 3 Model B. Understand the duty cycle, the difference between software PWM (available on all pins, controlled by software) and hardware PWM (available on GPIO12/13/18/19 on the Pi 3B, generated by the SoC), and create a "breathing" effect.
Hardware
- Raspberry Pi 3 Model B running Raspberry Pi OS Lite
- LED + 330 Ω resistor on GPIO18 (physical pin 12 — hardware PWM pin of the BCM2837)
- Breadboard, Dupont cables
gpiozero(pre-installed) for the software version- Optional hardware PWM: access to
/boot/firmware/config.txt
Complete Code
Simple version with software PWM using gpiozero (works on any pin):
#!/usr/bin/env python3
"""respiration.py — effet respiration sur LED GPIO18 (broche physique 12).
PWM logiciel gpiozero ; pour le PWM matériel voir plus bas."""
from gpiozero import PWMLED
from time import sleep
led = PWMLED(18, pwm=True) # GPIO18 accepte aussi le PWM matériel
while True:
for pas in range(0, 101, 5): # montée 0 -> 100 %
led.value = pas / 100.0
sleep(0.05)
for pas in range(100, -1, -5): # descente 100 % -> 0
led.value = pas / 100.0
sleep(0.05)
For hardware PWM on GPIO18, enable the overlay in /boot/firmware/config.txt and then reboot:
echo 'dtoverlay=pwm-2chan,pin=18,func=2' | sudo tee -a /boot/firmware/config.txt
sudo reboot
Expected Verification
The LED gradually brightens and dims (breathing effect of approximately 4 seconds per cycle), without visible steps. With sudo python3 respiration.py running in parallel with watch -n1 cat /sys/class/pwm/*/* 2>/dev/null, you can observe the PWM files after enabling the overlay. An LED at 20% PWM appears significantly dimmer than at 80% — perception is not linear, which is normal.
Common Errors
- Choosing a pin without hardware PWM and being surprised: only GPIO12/13/18/19 support hardware PWM on the Pi 3B; elsewhere, software PWM consumes CPU and may jitter.
- Forgetting
sudo rebootafter adding thedtoverlay: no PWM controller appears in/sys/class/pwm. - Confusing GPIO18 (physical pin 12) with pin 18 (GPIO24): check the pinout.
led.valueoutside the range 0..1:gpiozeroignores it or raises an error; keeppas / 100.0.- LED always fully lit in hardware PWM mode: the pin is not routed to PWM (incorrect
func=in the overlay). - On an SBC board like Banana Pi/Orange Pi with the same connector: the PWM pin mapping differs — refer to the board's datasheet. >
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython