🛠 Variation d'intensité d'une LED avec le PWM matériel
Objectives
Vary the intensity of an LED using Pulse Width Modulation (PWM) on the Raspberry Pi 3 A+: hardware PWM on GPIO18 (pin 12, "PWM" signal on the 40-pin connector) versus software PWM with gpiozero, duty cycle, and frequency.
Hardware
- Raspberry Pi 3 A+ running Raspberry Pi OS Bookworm, LED + 330 Ω resistor
- LED + 330 Ω between GPIO18 (pin 12) and GND (pin 14); any GPIO works for software PWM
sudo apt install python3-gpiozero
Complete Code
#!/usr/bin/env python3
# pwm_led.py — respiration de LED (GPIO18 = PWM matériel)
from gpiozero import PWMLED
from time import sleep
led = PWMLED("GPIO18", pwm=True) # GPIO18 = broche 12, PWM matériel
led.pwm_frequency = 100 # Hz ; défaut gpiozero : 100 Hz
# respiration : montée puis descente du rapport cyclique
for i in range(0, 101, 5):
led.value = i / 100.0 # 0.0 = éteinte, 1.0 = pleine
sleep(0.05)
for i in range(100, -1, -5):
led.value = i / 100.0
sleep(0.05)
# clignotement précis piloté par le contrôleur PWM matériel
led.blink(on_time=0.5, off_time=0.5, fade_in_time=0.2, fade_out_time=0.2)
sleep(5)
led.off
python3 pwm_led.py
# Vérifier le brochage PWM : le site de référence du connecteur 40 broches
Expected Verification
The LED gradually increases in brightness over ~1 s, decreases, then blinks with fades. With a multimeter on GPIO18, the average voltage follows the duty cycle (≈1.65 V at 50% based on 3.3 V).
Common Errors
- Confusing hardware PWM (GPIO18, also GPIO12/13/19) and software PWM (any GPIO, less precise): on the 3 A+, the hardware controller is unique and shared.
- Frequency too low (<50 Hz): the LED starts to flicker visibly.
- Forgetting the resistor: at 100% duty cycle, the current exceeds the pin limits.
- For servomotors, force
pwm_frequency = 50; by default at 100 Hz the servo vibrates or burns out.
Other tutorials for this board
- Allumer une LED en C avec libgpiod sur le GPIO 40 broches
- Bouton poussoir et retour console avec gpiozero
- Premier script Python : inventaire du système
- Capteur I2C : température et pression avec BME280
- Connexion WiFi station et administration en SSH
- Démarrage SD/USB et récupération d'une carte qui ne boot plus
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython