🛠 Variateur de luminosité LED en PWM

Raspberry Pi 3 Model B (model-3b) · intermediaire · Schéma : IMG-model-3b-intermediaire-1-model3b-pwm-led.svg — LED sur GPIO18 (broche 12, broche PWM matérielle du BCM2837) avec résistance, signal PWM en dents de scie et variation du rapport cyclique

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials