ABC of Electronics cosycom.com
ESP32 BASICS · LESSON 07

PWM Output: Dimming an LED

Generating pulse-width-modulated signals with the LEDC peripheral to fade LEDs and drive small motors.

PWM (pulse-width modulation) switches a pin on and off very quickly. By changing the fraction of time it spends on — the duty cycle — you can make an LED look dimmer or brighter, or give a small DC motor a lower effective voltage, without an actual analog output pin.

25% 75% 50% Duty cycle changes average voltage seen by the LED / motor
Fig. Three PWM duty cycles at the same frequency.

Using the LEDC peripheral

The ESP32 has dedicated PWM hardware (called LEDC) rather than relying purely on software timing, which keeps the signal steady even while other code is running.

fade.ino
#define LED_PIN 5
#define PWM_CHANNEL 0
#define PWM_FREQ 5000
#define PWM_RES 8   // 8-bit: 0-255

void setup() {
  ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RES);
  ledcAttachPin(LED_PIN, PWM_CHANNEL);
}

void loop() {
  for (int duty = 0; duty <= 255; duty++) {
    ledcWrite(PWM_CHANNEL, duty);
    delay(10);
  }
  for (int duty = 255; duty >= 0; duty--) {
    ledcWrite(PWM_CHANNEL, duty);
    delay(10);
  }
}
KEY IDEA
Higher PWM frequency means less visible flicker but the same average brightness — the duty cycle, not the frequency, controls how bright or dim things look.