🛠 Variation d'intensité d'une LED avec le PWM

Raspberry Pi 5 (model-5) · intermediaire · Schéma : IMG-model-5-intermediaire-1-model5-i1-pwm-led.svg — LED sur GPIO18 (broche physique 12, PWM matériel) avec résistance 470 Ω, effet de respiration lumineuse

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials