🛠 Variation d'intensité d'une LED en PWM
Objectives
Understand Pulse Width Modulation (PWM): a digital output only provides 0 or 3.3 V, but by switching very rapidly, we can modulate the average power. You will use the hardware PWM on the 40-pin connector (GPIO18, pin 12) and a "breathing LED" in Python, then hardware PWM via pigpio in C.
Hardware
- Raspberry Pi 3 Model B+ (or similar) running Raspberry Pi OS
- LED + 330 Ω resistor on GPIO18 (pin 12, hardware PWM pin)
- Option C:
sudo apt install pigpiothensudo pigpiod
Complete Code
#!/usr/bin/env python3
"""Respiration LED sur GPIO18 (broche PWM matérielle)."""
from gpiozero import PWMLED
from time import sleep
led = PWMLED(18) # PWM : valeur de 0.0 (éteinte) à 1.0 (pleine)
while True:
for pas in range(0, 101, 2): # montée 0 -> 100 %
led.value = pas / 100.0
sleep(0.02)
for pas in range(100, -1, -2): # descente 100 -> 0 %
led.value = pas / 100.0
sleep(0.02)
/* Version PWM matérielle : gcc servo.c -o servo -lpigpio (pigpiod lancé).
50 Hz, impulsions 1-2 ms : la même mécanique pilote un servomoteur. */
#include <pigpio.h>
#include <stdio.h>
int main(void) {
if (gpioInitial < 0) { fprintf(stderr, "demarrer pigpiod d'abord\n"); return 1; }
int pulse_us = 1000, dir = 20;
for (int i = 0; i < 250; i++) {
gpioHardwarePWM(18, 20000, pulse_us * 10); /* 50 Hz, pulse en 0,1 us */
if (pulse_us <= 1000 || pulse_us >= 2000) dir = -dir;
pulse_us += dir;
timeSleep(20000);
}
gpioHardwarePWM(18, 0, 0); /* couper le PWM avant de sortir */
gpioTerminate;
return 0;
}
Expected Verification
The LED brightness rises and falls continuously ("breathing" effect of approximately 2 s per cycle) without visible flickering. With the C version, a logic analyzer (or a smartphone app) shows a 50 Hz square wave whose pulse width varies between 1 and 2 ms. pigs rgr 18 displays the active PWM configuration.
Common Errors
- Choosing a pin without hardware PWM: software PWM (gpiozero) works on any pin but may jitter if the board is under load; GPIO18 is the proper hardware PWM pin.
- Forgetting
sudo pigpiodbefore running the C binary:gpioInitialfails immediately. - Leaving PWM active when exiting the script: the LED remains lit at half power — always reset with
gpioHardwarePWM(18, 0, 0). - Confusing duty cycle and frequency: here the frequency remains 50 Hz, only the pulse width changes.
- Weak power supply: under heavy PWM + USB load, a 1 A power supply causes brownouts; use a 2.5 A supply.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython