🛠 Variateur de lumière : PWM sur une LED

Raspberry Pi 2 Model B (2015) — Board Sheet · intermediaire · Schéma : IMG-model-2b-intermediaire-1-model2b-pwm-led.svg — LED sur GPIO18 (sortie PWM matérielle du Pi 2), oscillogramme de rapport cyclique variable et rampe d'intensité lumineuse

Objectives

Understand Pulse Width Modulation (PWM): vary the brightness of an LED by changing the duty cycle. The J8 connector on the Pi 2 exposes a hardware PWM output on GPIO18; you will first use the software PWM from RPi.GPIO (simple and flexible), then enable hardware PWM via config.txt.

Hardware

Complete Code

#!/usr/bin/env python3
"""pwm_led.py — rampe d'intensite PWM (logiciel) sur GPIO18."""
import RPi.GPIO as GPIO
from time import sleep

PIN = 18  # aussi la sortie PWM materielle du J8
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)
pwm = GPIO.PWM(PIN, 1000)  # frequence 1 kHz
pwm.start(0)
try:
    while True:
        for dc in range(0, 101, 5):    # monte doucement
            pwm.ChangeDutyCycle(dc)
            sleep(0.05)
        for dc in range(100, -1, -5):  # descend doucement
            pwm.ChangeDutyCycle(dc)
            sleep(0.05)
except KeyboardInterrupt:
    pass
pwm.stop
GPIO.cleanup

Expected Verification

The LED brightens and then dims in a continuous loop (breathing effect). At 0 % it is off, at 100 % it is at full intensity. For hardware PWM, add dtoverlay=pwm (or pwm-2chan) to /boot/config.txt, reboot, then control /sys/class/pwm: the signal remains accurate even under load, unlike software PWM.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials