Skip to content
GEEKnodes

Electronics

PWM Explained: Duty Cycle, Arduino analogWrite and ESP32 LEDC

What PWM is, how duty cycle and frequency work, and how to use analogWrite on Arduino and LEDC on ESP32 to drive LEDs, motors and servos.

PWM is how microcontrollers “fake” an analog output using only two states: on and off. With it you can dim an LED, control a motor’s speed or set a servo’s position. In this guide you’ll learn what duty cycle and frequency are, and how to generate PWM with analogWrite on Arduino and with LEDC on ESP32.

In short

  • PWM = a square wave that switches on and off very fast; what changes is how long it stays on.
  • The duty cycle is that percentage: 50% on a 5 V pin averages out to 2.5 V.
  • On the Arduino Uno, analogWrite(pin, 0–255) runs at about 490 Hz (980 Hz on pins 5 and 6).
  • On the ESP32 (core 3.x) you use ledcAttach(pin, frequency, resolution) and ledcWrite(pin, value).

What PWM is

PWM stands for Pulse Width Modulation. A digital pin can only be at 0 V or at the supply voltage (5 V or 3.3 V). But if you switch it on and off hundreds or thousands of times per second, the load “sees” an average value.

Two parameters define the signal:

  • Frequency: how many complete cycles there are per second (Hz).
  • Duty cycle: what percentage of each cycle the signal is high.

Duty cycle and average voltage

The average voltage is proportional to the duty cycle:

V average = duty cycle × V supply
Three 5 V PWM signals at 25%, 50% and 75% duty cycle with average voltages of 1.25 V, 2.5 V and 3.75 V
Same frequency, different time high: the average voltage follows the duty cycle
Duty cycleanalogWrite value (8-bit)Average voltage at 5 VAverage voltage at 3.3 V
0%00 V0 V
25%641.25 V0.83 V
50%1282.5 V1.65 V
75%1913.75 V2.48 V
100%2555 V3.3 V

Important: this isn’t a true analog voltage. A multimeter will show you the average value, but an oscilloscope will show the square wave. For a real analog voltage you need an RC filter or a DAC.

Which frequency to use

ApplicationTypical frequencyWhy
LED brightness500 Hz – 5 kHzAbove a few hundred Hz the eye doesn’t see flicker
DC motor1 kHz – 20 kHzAt audible frequencies the motor “whines”; above 20 kHz you can’t hear it
Hobby servo50 Hz (20 ms period)It’s what the servo expects
4-pin PC fan25 kHzThe PWM fan specification

PWM on Arduino: analogWrite

On classic Arduino boards, analogWrite() generates PWM with 8-bit resolution (0–255).

analogWrite(pin, valor);  // value from 0 (off) to 255 (always on)

You don’t need to set the pin up with pinMode() before using it.

Pins and frequencies according to the official reference

BoardPWM pinsFrequency
Uno R3, Nano, Mini3, 5, 6, 9, 10, 11490 Hz (pins 5 and 6: 980 Hz)
Uno R4 Minima / WiFi3, 5, 6, 9, 10, 11490 Hz
Uno WiFi Rev2, Nano Every3, 5, 6, 9, 10976 Hz

On the board, PWM pins are usually marked with the ~ symbol.

Example: an LED that fades in and out

LED with its resistor (220 Ω) on pin 9. If you’re unsure about the value, use the LED resistor calculator.

const int LED = 9;

void setup() {
  // analogWrite doesn't need pinMode
}

void loop() {
  for (int brillo = 0; brillo <= 255; brillo++) {
    analogWrite(LED, brillo);
    delay(5);
  }
  for (int brillo = 255; brillo >= 0; brillo--) {
    analogWrite(LED, brillo);
    delay(5);
  }
}

Brightness isn’t linear

The human eye perceives brightness logarithmically: going from 0 to 25 is very noticeable, going from 200 to 255 barely at all. For a fade that looks even, you apply gamma correction, for example by squaring or cubing the normalized value before writing it.

PWM on ESP32: LEDC

The ESP32 generates PWM with its LEDC (LED Control) peripheral. Unlike the Arduino Uno, it lets you choose frequency and resolution on almost any output pin.

Arduino-ESP32 core 3.x API

Since version 3.0 of the core, ledcSetup() and ledcAttachPin() have been removed and replaced by a single function. Channels are assigned automatically.

ledcAttach(pin, frecuencia, resolucion);  // resolution in bits
ledcWrite(pin, ciclo);                    // duty from 0 to (2^resolution - 1)
ledcDetach(pin);                          // release the pin

According to Espressif’s documentation, resolution can generally range from 1 to 14 bits, and up to 20 bits on the original ESP32. The higher the frequency, the lower the maximum resolution available.

Example: LED fade on ESP32

const int LED = 2;
const int FRECUENCIA = 5000;  // 5 kHz
const int RESOLUCION = 8;     // 0–255

void setup() {
  ledcAttach(LED, FRECUENCIA, RESOLUCION);
}

void loop() {
  for (int ciclo = 0; ciclo <= 255; ciclo++) {
    ledcWrite(LED, ciclo);
    delay(5);
  }
  for (int ciclo = 255; ciclo >= 0; ciclo--) {
    ledcWrite(LED, ciclo);
    delay(5);
  }
}

If you copy an older example with ledcSetup(canal, ...) and it won’t compile, this API change is why: adapt it to ledcAttach or install version 2.0.17 of the core to keep the old code.

Resolution and maximum values

ResolutionValuesMaximum for ledcWrite
8 bits256255
10 bits1,0241,023
12 bits4,0964,095

Practical uses of PWM

LED and LED strip brightness

A single LED connects to the pin with its resistor. For a 12 V LED strip you need a logic-level MOSFET between the strip and GND, controlled by the PWM pin. We explain it in the transistor as a switch.

DC motor speed

The motor never connects directly to the pin. Use:

  • A MOSFET plus a flyback diode if you only need one direction of rotation.
  • An H-bridge (L298N, TB6612FNG, DRV8833) if you need to change direction.
Microcontroller PWM pin to the gate of a MOSFET that switches a DC motor with a flyback diode in parallel
The pin only provides the signal: the MOSFET handles the current and the diode protects against the spike

PWM controls the speed: with a low duty cycle, the motor may not start because of friction. You usually need a minimum (for example, 30–40%) for it to start turning.

Servos

A hobby servo isn’t controlled by duty cycle as a percentage, but by pulse width within a 50 Hz signal:

Pulse widthTypical position
~1 msOne end (0°)
~1.5 msCenter (90°)
~2 msOther end (180°)

The exact ranges vary by model. The easiest way is to use the Servo library:

#include <Servo.h>

Servo servo;

void setup() {
  servo.attach(9);
}

void loop() {
  servo.write(0);
  delay(1000);
  servo.write(90);
  delay(1000);
  servo.write(180);
  delay(1000);
}

On the Arduino Uno, the Servo library uses a timer that disables analogWrite() on pins 9 and 10. On the ESP32 you use a dedicated library, such as ESP32Servo.

Common mistakes

MistakeSymptomFix
analogWrite on a pin without ~The LED only turns fully on or offUse a PWM pin
Motor wired straight to the pinResets or a damaged pinMOSFET or H-bridge
Old LEDC code on core 3.xCompile error with ledcSetupUse ledcAttach and ledcWrite(pin, …)
ledcWrite with a value above the resolutionOutput always at maximumMatch the range: 8 bits = 0–255
Whining motorPWM at an audible frequencyRaise the frequency above 20 kHz (if the driver supports it)
Jittery servoPowered from the Arduino’s 5 V pinUse a separate supply with a common GND

Accessibility preferences

Quick profiles

Text and reading

Text size
Default
Line height
Default
Letter spacing
Default
Word spacing
Default

Colour

Motion and orientation

Cursor