🛠 Variateur de lumière : PWM matériel sur GPIO18
Objectives
- Understand PWM: frequency and duty cycle to simulate an analog voltage.
- Use the hardware PWM output (GPIO18, pin 12 of the 26-pin connector).
- Create a breathing LED effect in Python.
Hardware
- Raspberry Pi Model A, LED + 330 Ω resistor on GPIO18.
- Raspberry Pi OS legacy; hardware PWM may require
dtoverlay=pwmin config.txt depending on the image. - Stable power supply: the polyfuse on the Model A does not tolerate overconsumption.
Complete code
#!/usr/bin/env python3
"""Fondu PWM matériel sur GPIO18 (broche 12)."""
import RPi.GPIO as GPIO, time
PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)
p = GPIO.PWM(PIN, 500) # 500 Hz
p.start(0)
try:
while True:
for d in list(range(0, 101, 5)) + list(range(95, -5, -5)):
p.ChangeDutyCycle(d) # rapport cyclique 0..100 %
time.sleep(0.03)
except KeyboardInterrupt:
pass
finally:
p.stop
GPIO.cleanup
# Vérifier le brochage PWM matériel
pinout # ou consulter https://pinout.xyz
Expected verification
The LED gradually brightens and dims without perceptible flickering. At 0% it is off, at 100% it is at full intensity; only pin 12 (GPIO18) provides hardware PWM on the 26-pin connector.
Common errors
- Applying PWM to a pin without hardware capability: RPi.GPIO then switches to software PWM, which is less stable.
- Forgetting
p.stop/GPIO.cleanup: the pin remains occupied when rerunning the script. - Frequency too low (a few Hz): visible flickering, the LED appears to blink.
- Confusing pin 12 and GPIO12: it is indeed physical pin 12 that carries GPIO18/PWM.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython