🛠 Variateur d'intensité : faire varier une LED en PWM matériel
Objectives
Use the BCM2711 hardware PWM output (the SoC has a hardware PWM) to vary the brightness of an LED: duty cycle, frequency, breathing. You will enable the device tree overlay and then control it via the command line and Python.
Hardware
- Raspberry Pi 4B, LED, 330 ohm resistor
- GPIO18 = physical pin 12 (hardware PWM channel 0)
- sudo apt install gpiod python3-gpiozero
Complete code
# 1) Activer le PWM : sudo raspi-config -> Interface Options -> PWM
# ou ajouter dtoverlay=pwm-2chan dans /boot/firmware/config.txt
sudo reboot
gpioset --pwm gpiochip0 18=100=0 # 0 % de rapport cyclique
for d in 100 75 50 25 0; do echo "Duty $d %"; gpioset --pwm gpiochip0 18=$d=0; sleep 1; done
# breathing.py - respiration de la LED via gpiozero
from gpiozero import PWMLED
from signal import pause
led = PWMLED(18) # GPIO18, PWM materiel
led.pwm_frequency = 1000 # Hz
led.source = "pulse" # oscillation continue du rapport cyclique
pause
Expected verification
The LED fades progressively at each step of the shell script, then breathes continuously with the Python script. At 0% it is off, at 100% it is fully on; the eye perceives the variation thanks to a frequency of a few hundred Hz.
Common errors
- Choosing a pin without hardware PWM: the overlay is only routed to GPIO12/13/18/19.
- Forgetting
dtoverlay=pwmthengpioset --pwm: the line rejects the pwm flag. - Confusing frequency (speed of the cycle) and duty cycle (proportion of high state): it is the duty that controls brightness.
- Frequency too low (< 100 Hz): the LED flickers visibly.
- Physical/BCM confusion: pin 12 = GPIO18.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython