🛠 Variation d'intensité d'une LED avec le PWM matériel (GPIO18)
Objectives
Get to grips with Pulse Width Modulation (PWM): make an LED "breathe" by varying the duty cycle. The BCM2835 on the Model B+ exposes a hardware PWM output on GPIO18 (pin 12) — the only one on the 40-pin header by default — guaranteed glitch-free even under CPU load.
Hardware
- Raspberry Pi Model B+ running 32-bit legacy Raspberry Pi OS
- 1 LED + 330 Ω resistor
- Dupont wires: pin 12 (GPIO18) → resistor → LED → pin 14 (GND)
- Optionally an NPN transistor (BC547) to drive an LED strip, with GPIO18 connected to the base via a 1 kΩ resistor
Complete code
sudo apt install -y python3-rpi.gpio
sudo python3 fade.py
#!/usr/bin/env python3
"""Respiration LED sur GPIO18 (PWM matérielle) — Model B+."""
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
p = GPIO.PWM(18, 200) # 200 Hz : inodore pour l'œil
p.start(0)
try:
while True:
up = range(0, 101, 5) # rampe montante
down = range(95, -1, -5) # rampe descendante
for dc in list(up) + list(down):
p.ChangeDutyCycle(dc) # 0 % = éteinte, 100 % = pleine
time.sleep(0.05)
finally:
p.stop
GPIO.cleanup
Expected verification
The LED brightness rises and falls in a loop, without perceptible flickering. An oscilloscope on GPIO18 shows a 200 Hz square wave whose duty cycle varies. Ctrl+C stops the program cleanly.
Common errors
- Software PWM on another pin: possible with RPi.GPIO, but the single-core BCM2835 produces glitches under load — prefer GPIO18.
- Frequency too low (a few Hz): the LED blinks instead of varying in brightness.
- Forgetting p.stop: signal residue remains after Ctrl+C if outside the finally block.
- Confusing PWM with analog output: the B+ has no analog-to-digital converter or DAC; PWM is just rapid on/off signals.
Other tutorials for this board
- Allumer une LED depuis la GPIO 17 avec libgpiod
- Lire un bouton et afficher les appuis dans la console
- Premier script Python : faire clignoter la LED
- Interroger un capteur I2C (BME280) sur le bus du 40 broches
- Mettre le B+ en réseau par Ethernet et piloter en SSH
- Amorçage microSD, pannes de boot et procédure de recouvrement
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython