🛠 Variation d'intensité LED avec le PWM matériel (et son piège)

Raspberry Pi Model B (Rev 1, 2012) — Board Sheet · intermediaire · Schéma : IMG-model-b-rev1-intermediaire-1-modelb1-pwm-led.svg — LED sur GPIO18 (broche 12), unique sortie PWM matérielle du BCM2835, signal carré animé montrant le rapport cyclaire variable

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials