🛠 Variation d'intensité d'une LED avec le PWM
Objectives
Vary the brightness of an LED using Pulse Width Modulation (PWM). On the Raspberry Pi 5, hardware PWM is available on GPIO 12, 13, 18, and 19, all driven by the RP1 chip. We will create a "breathing" effect (breathing LED) in Python using gpiozero.
Hardware
- Raspberry Pi 5 running 64-bit Raspberry Pi OS
- 1 LED + 470 Ω resistor
- Wire on physical pin 12 = GPIO18 (hardware PWM), GND on pin 6
- gpiozero preinstalled
Complete code
#!/usr/bin/env python3
# breathe.py — effet respiration sur LED PWM (GPIO18 = broche physique 12)
# PWM materiel Pi 5 : GPIO 12, 13, 18, 19 (pilotés par la puce RP1).
from gpiozero import PWMLED
from time import sleep
led = PWMLED(18, freq=1000) # 1 kHz : imperceptible pour l'œil
try:
while True:
# montée progressive de 0 % à 100 %
for duty in range(0, 101, 2):
led.value = duty / 100.0
sleep(0.02)
# descente progressive de 100 % à 0 %
for duty in range(100, -1, -2):
led.value = duty / 100.0
sleep(0.02)
except KeyboardInterrupt:
led.off
Command-line alternative using exported hardware PWM:
echo 18 | sudo tee /sys/class/pwm/pwmchip0/export
sleep 0.2
echo 1000000 | sudo tee /sys/class/pwm/pwmchip0/pwm0/period
echo 500000 | sudo tee /sys/class/pwm/pwmchip0/pwm0/duty_cycle
echo 1 | sudo tee /sys/class/pwm/pwmchip0/pwm0/enable
Expected verification
The LED brightens and then dims in a loop, without visible flickering. With the sysfs variant, the LED stays at 50% brightness (duty_cycle = half the period).
Common errors
- Choosing a GPIO without hardware PWM (for example GPIO17): gpiozero falls back to software PWM, which is less regular; prefer 12/13/18/19.
- Reusing pwmchip0 when PWM is already taken by an overlay: free it with
echo 18 > .../pwmchip0/unexportor checkconfig.txt. - LED blinking instead of varying: frequency too low, add
freq=1000to PWMLED. - Forgetting the resistor in PWM: the average current is lower but the peaks remain dangerous for the pin.
- Not turning off the LED when exiting the script: always call
led.offin the exception block.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython