OTD ACADEMY
Sign in / Sign up
Library

LIBRARYPWM: a fake analog output.

How switching a digital pin on and off fast, with a controllable duty cycle, averages to an in-between level. The way one pin dims an LED or sets a motor's speed.

A microcontroller pin is digital: it can only be fully on or fully off. But switch it on and off fast, with a controllable on-fraction, and it averages to a level in between. That is PWM, for pulse-width modulation, and it is how one digital pin dims an LED or sets a motor's speed without any analog output hardware.

Duty cycle: the on-fraction

The duty cycle is the fraction of each cycle the pin spends high. At 25 percent duty the output averages a quarter of the supply; at 75 percent, three-quarters. Sweep the duty cycle and the average voltage follows it smoothly, which is the whole trick.

Vavg=DVsupplyV_{avg} = D \cdot V_{supply}

Frequency: fast enough to blur

The switching frequency has to be fast enough that whatever you are driving cannot follow the individual pulses. Your eye blurs a fast-blinking LED into a steady brightness; a motor's inertia smooths the pulses into a steady pull. Too slow, and the LED visibly flickers or the motor whines at the switching rate. Fast enough, and only the average shows.

What PWM drives

PWM sets LED brightness, motor speed, a servo's position (through a specific pulse width), a buzzer's tone, and, once you smooth it with an RC filter, a rough analog voltage. On the ESP32 the LEDC peripheral generates PWM in hardware on any output pin, so your code just sets a duty cycle and the hardware toggles the pin at the frequency you chose, with no CPU effort per pulse.

Deep dive· Duty-cycle resolution, and its trade with frequency

The duty cycle is not truly continuous: it is set as a count out of two-to-the-bits, an ADC in reverse. A higher PWM resolution gives finer brightness or speed steps, but on the ESP32 the resolution and the frequency both come from dividing one source clock, so they trade against each other. Push the frequency very high and you are left with fewer usable duty-cycle bits; drop it and you get more. For LED dimming a few kilohertz with 10 or more bits is plenty; a fast switching converter would flip the balance the other way.

Three PWM waveforms at 25, 50, and 75 percent duty cycle, each with a dashed line showing the averaged output level rising with the duty.
Three duty cycles and the average each one produces: the on-fraction sets the level.

The fundamentals guide on reactive parts and filtering shows the RC low-pass that averages a PWM signal into a real, steady voltage, if you want the analog output rather than just the blinking.

Checkpoint

Quick check

What sets a PWM output's average level?
Why must the PWM frequency be fast enough?
A hobby servo's position is set by what kind of PWM signal?
0 / 3 correct

One Thousand Drones engineering team · verified 2026-07