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

Raspberry Pi 3 Model B+ (2018) — Board Sheet · intermediaire · Schéma : IMG-model-3b-plus-intermediaire-1-model3bp-pwm-led.svg — LED sur GPIO18 (broche 12, PWM matériel) avec résistance, dégradé lumineux illustrant le rapport cyclique

Objectives

Understand Pulse Width Modulation (PWM): a digital output only provides 0 or 3.3 V, but by switching very rapidly, we can modulate the average power. You will use the hardware PWM on the 40-pin connector (GPIO18, pin 12) and a "breathing LED" in Python, then hardware PWM via pigpio in C.

Hardware

Complete Code

#!/usr/bin/env python3
"""Respiration LED sur GPIO18 (broche PWM matérielle)."""
from gpiozero import PWMLED
from time import sleep

led = PWMLED(18)          # PWM : valeur de 0.0 (éteinte) à 1.0 (pleine)
while True:
    for pas in range(0, 101, 2):      # montée 0 -> 100 %
        led.value = pas / 100.0
        sleep(0.02)
    for pas in range(100, -1, -2):    # descente 100 -> 0 %
        led.value = pas / 100.0
        sleep(0.02)
/* Version PWM matérielle : gcc servo.c -o servo -lpigpio (pigpiod lancé).
   50 Hz, impulsions 1-2 ms : la même mécanique pilote un servomoteur. */
#include <pigpio.h>
#include <stdio.h>

int main(void) {
    if (gpioInitial < 0) { fprintf(stderr, "demarrer pigpiod d'abord\n"); return 1; }
    int pulse_us = 1000, dir = 20;
    for (int i = 0; i < 250; i++) {
        gpioHardwarePWM(18, 20000, pulse_us * 10); /* 50 Hz, pulse en 0,1 us */
        if (pulse_us <= 1000 || pulse_us >= 2000) dir = -dir;
        pulse_us += dir;
        timeSleep(20000);
    }
    gpioHardwarePWM(18, 0, 0);   /* couper le PWM avant de sortir */
    gpioTerminate;
    return 0;
}

Expected Verification

The LED brightness rises and falls continuously ("breathing" effect of approximately 2 s per cycle) without visible flickering. With the C version, a logic analyzer (or a smartphone app) shows a 50 Hz square wave whose pulse width varies between 1 and 2 ms. pigs rgr 18 displays the active PWM configuration.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials