🛠 Variation d'intensité d'une LED avec le PWM matériel (GPIO18)

Raspberry Pi Model B+ (2014) — Board Sheet · intermediaire · Schéma : IMG-model-b-plus-intermediaire-1-modelbp-pwm-led.svg — LED avec résistance 330 Ω sur GPIO18 (broche 12), la broche PWM matérielle du BCM2835, GND en broche 14 ; le signal carré 200 Hz est dessiné en encart.

Objectives

Get to grips with Pulse Width Modulation (PWM): make an LED "breathe" by varying the duty cycle. The BCM2835 on the Model B+ exposes a hardware PWM output on GPIO18 (pin 12) — the only one on the 40-pin header by default — guaranteed glitch-free even under CPU load.

Hardware

Complete code

sudo apt install -y python3-rpi.gpio
sudo python3 fade.py
#!/usr/bin/env python3
"""Respiration LED sur GPIO18 (PWM matérielle) — Model B+."""
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
p = GPIO.PWM(18, 200)                 # 200 Hz : inodore pour l'œil
p.start(0)
try:
    while True:
        up = range(0, 101, 5)         # rampe montante
        down = range(95, -1, -5)      # rampe descendante
        for dc in list(up) + list(down):
            p.ChangeDutyCycle(dc)     # 0 % = éteinte, 100 % = pleine
            time.sleep(0.05)
finally:
    p.stop
    GPIO.cleanup

Expected verification

The LED brightness rises and falls in a loop, without perceptible flickering. An oscilloscope on GPIO18 shows a 200 Hz square wave whose duty cycle varies. Ctrl+C stops the program cleanly.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials