← all lessons
Microcontrollers · #9 of 20

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

The core idea

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

Demo

The top plot is the digital PWM output. The bottom plot shows a smoothed

Key takeaways

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.

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)

Implementation

LLM Prompt: PWM Control