🛠 Fondu de LED avec le PWM LEDC
Objectives
Control the brightness of an LED using the ESP32's LEDC peripheral: PWM is generated by 8 independent channels (with configurable frequency and resolution), unlike a simple digitalWrite. You will learn how to configure a channel, attach it to a pin, and perform a rising and falling fade.
Hardware
- 1 ESP32 DevKit v1 board
- 1 LED + 1 330 Ω resistor
- Jumper wires (GPIO25 → resistor → LED → GND)
Complete code
const uint8_t LED_PIN = 25; // eviter GPIO2, broche de strapping
const uint8_t CANAL = 0; // 0 a 7 sur ESP32
void setup {
ledcSetup(CANAL, 5000, 8); // 5 kHz, resolution 8 bits (0..255)
ledcAttachPin(LED_PIN, CANAL);
}
void loop {
for (int v = 0; v <= 255; v++) { ledcWrite(CANAL, v); delay(8); }
for (int v = 255; v >= 0; v--) { ledcWrite(CANAL, v); delay(8); }
}
Expected verification
The LED turns on and off gradually (a smooth fade of approximately 2 seconds per cycle), without visible steps. With an oscilloscope on GPIO25, you observe a 5 kHz square wave whose duty cycle follows the ramp.
Common errors
- analogWrite does not exist in the Arduino-ESP32 2.x core: you must use ledcSetup/ledcAttachPin/ledcWrite.
- LED wired to GPIO2: this is a strapping pin (along with GPIO0 and GPIO12); a load connected to it can disrupt startup. Prefer GPIO25, 26, 27…
- Forgetting the resistor: the LED burns out or the pin supplies too much current.
- Each LEDC channel is a hardware resource limited to 8 on the ESP32: plan your PWM channels in advance.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino