🛠 Variation d'intensité LED avec le PWM matériel (et son piège)
Objectives
Vary the brightness of an LED using Pulse Width Modulation (PWM). Major pitfall of the BCM2835: there is only one hardware PWM output, on GPIO18 (physical pin 12). If another use case (audio, another motor) requires this channel, everything else must rely on software PWM, which is less precise. This tutorial demonstrates the approach using RPi.GPIO and illustrates this constraint.
Hardware
- Raspberry Pi Model B Rev 1 running a legacy 32-bit image
- LED + 330 Ω resistor on GPIO18 (pin 12) and GND (pin 6)
sudo apt install -y python3-rpi.gpio- GPIO18 is also the PWM audio pin: a speaker connected to it will conflict with your LED.
Complete Code
#!/usr/bin/env python3
"""Respiration LED sur GPIO18 - PWM materiel UNIQUE du BCM2835."""
import RPi.GPIO as GPIO
import time
LED = 18 # SEULE broche PWM materielle du Model B Rev 1 (broche 12)
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
p = GPIO.PWM(LED, 100) # frequence 100 Hz
p.start(0)
try:
while True: # montee puis descente du rapport cyclique
for dc in range(0, 101, 5):
p.ChangeDutyCycle(dc)
time.sleep(0.05)
for dc in range(100, -1, -5):
p.ChangeDutyCycle(dc)
time.sleep(0.05)
except KeyboardInterrupt:
pass
finally:
p.stop
GPIO.cleanup
Expected Verification
The LED "breathes": brightness increases and decreases in a loop. Check with cat /sys/kernel/debug/pwm (if available) that the hardware PWM channel is indeed claimed. Test the pitfall: launch a second PWM script on GPIO18; the second one will fail or take over the single channel.
Common Errors
- Choosing GPIO17 for hardware PWM: RPi.GPIO silently switches to software (simulated) PWM; only pin 18 supports hardware PWM.
- Audio conflict: sound via the jack connector uses the same PWM module; running
aplaymay disturb the LED (and vice versa). - Frequency too low (< 50 Hz): visible flickering; software PWM at high frequency: the ARM11 cannot handle it.
- Forgetting
p.stopbeforeGPIO.cleanup: the pin remains active. - Expecting an analog output: PWM provides an average voltage, not a true DAC (the BCM2835 has no DAC).
Other tutorials for this board
- Allumer une LED via le GPIO avec libgpiod
- Lire un bouton poussoir et afficher l'état dans la console
- Premier script Python : faire clignoter la LED
- Lire un capteur I2C (température/humidité) sur le bus 1
- Configurer l'Ethernet 10/100 et piloter le Pi en SSH
- Boot sur SD, partitions et procédure de recouvrement
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython