🛠 Variation d'intensité d'une LED en PWM

Raspberry Pi Model B Revision 2 (2012) — Board Sheet · intermediaire · Schéma : IMG-model-b-rev2-intermediaire-1-modelb2-pwm-led.svg — LED sur GPIO18 (broche PWM matériel du BCM2835) avec résistance, fondu lumineux en dégradé autour de la broche

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials