← all lessons
Microcontrollers · #9 of 48

Timers + PWM

LEDC: Duty, Frequency, Resolution

Why it matters

PWM is the workhorse for controlling brightness, motor speed, and power using only digital pins.

The idea

PWM rapidly switches a pin HIGH/LOW. The load (LED, motor, filter capacitor) averages it. The duty cycle sets the average output.

Demo

The trace is the raw digital PWM output across four periods; the dashed line is the averaged voltage the load actually sees. Slide duty cycle to scale the on-time. Slide frequency to change the period (the trace stays the same shape — frequency affects flicker, switching losses, and audible whine on motors).

duty: 40% Vavg: 1.32 V Iavg: 6.00 mA

Key takeaways

Math details

Definitions:
  duty = t_on / T
  frequency = 1 / T

Average output (ideal):
  V_avg ≈ duty * V_high

Duty resolution:
  steps = 2^bits
  duty_quantized = round(duty*(steps-1)) / (steps-1)

Going deeper

LEDs are not linear to human vision. Many projects apply gamma correction (e.g. duty ≈ brightness^2.2) so dimming feels smooth. Motors often need a driver (H-bridge / MOSFET) and a flyback path; do not drive motors directly from GPIO pins.

full glossary →