🛠 Variation d'intensité d'une LED en PWM
Objectives
Vary the intensity of an LED using Pulse Width Modulation (PWM) on the Model B Rev 2: GPIO18 (P1-12) is the hardware PWM pin of the BCM2835; we will use the PWM object from RPi.GPIO here for a gradual fade.
Hardware
- Raspberry Pi Model B Rev 2, Raspbian legacy 32-bit
- LED + 330 Ω resistor on GPIO18 (P1-12) to GND
sudo apt install python-rpi.gpio- Reminder: there is no digital-to-analog converter on the board; PWM is the only simple way to "simulate" a variable voltage.
Complete Code
#!/usr/bin/env python
# fondu.py - balayage PWM sur GPIO18 (broche PWM materielle du BCM2835)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
p = GPIO.PWM(18, 1000) # 1 kHz
p.start(0)
try:
while True:
for duty in list(range(0, 101, 5)) + list(range(95, -5, -5)):
p.ChangeDutyCycle(duty) # variation du rapport cyclique
time.sleep(0.02)
except KeyboardInterrupt:
pass
finally:
p.stop
GPIO.cleanup
Expected Verification
The LED brightness increases then decreases in a loop (breathing fade). Upon stopping (Ctrl-C), it turns off completely. An oscilloscope on GPIO18 would show a 1 kHz square wave with a varying duty cycle.
Common Errors
- Forgetting
p.stopfollowed byGPIO.cleanup: the LED remains lit at full intensity after the script ends. - Setting the frequency too low (a few Hz): visible flickering, which the eye perceives.
- Confusing GPIO18 (hardware PWM) with GPIO17: the fade works in software on other pins, but only pin 18 has hardware PWM.
- Resistor too high (above 1 kΩ): the LED is barely visible even at 100%.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython