Timers + PWM
Duty Cycle, Flicker, Timers, and Real Loads
The status LED on the robot is too bright for a dark room. The fan makes an annoying tone. A small DC motor needs to creep forward instead of jumping to full speed. None of those requests asks the microcontroller to invent an analog voltage. They ask it to control time.
A timer can switch a pin on and off with machine precision while the CPU does other work. If the on time is short, the load receives little energy. If the on time is long, the load receives more. That is pulse-width modulation: a digital pin pretending to be an adjustable knob by repeating one honest act very quickly.
PWM is one of the first places where firmware and electronics become the same subject. The register value in your code chooses a waveform. The waveform meets an LED, a motor, a MOSFET gate, a cable, a power rail and sometimes a human eye or ear. A good PWM design therefore asks three questions at once: what duty cycle, what frequency, and what load?
By the end, you can
- Define period, frequency, duty cycle and on-time from a PWM waveform
- Compute average voltage and average current for an ideal resistive load
- Explain why PWM frequency affects flicker, audible noise, timer resolution and switching loss
- Choose the right driver path for LEDs, motors and higher-current loads instead of abusing a GPIO pin
- Distinguish power PWM from hobby servo control pulses
- Use the ESP32 timer/channel mental model without treating LEDC as magic
The waveform is time sliced energy
A PWM output repeats the same period over and over. During the first part of the period the pin is HIGH. During the rest it is LOW. The fraction spent HIGH is the duty cycle.
The period T is the time for one complete cycle. Frequency is how many cycles happen
each second:
A 1 kHz PWM waveform has a period of 1 ms. At 30 percent duty, the pin is HIGH for 0.30 ms and LOW for 0.70 ms in every period. Nothing mystical happens between those edges. The pin is still digital. It is simply spending a controlled fraction of each period at the high voltage.
For an ideal resistive load connected between the PWM pin and ground, the average voltage is approximately the duty fraction times the high voltage:
The average current through a resistor follows Ohm's law:
Those equations are useful, but they are not universal laws for every load. A heater cares about average power over thermal time. An LED has a nonlinear current-voltage curve and your eye has nonlinear brightness perception. A motor winding stores energy in inductance. A capacitor turns the square wave into a ripple around a DC level. PWM is simple at the pin and specific at the load.
A 3.3 V PWM pin drives an ideal 220 ohm resistor at 25 percent duty. What average voltage does the resistor see?
-
Correct. For an ideal resistive average, multiply the high voltage by the duty fraction.
-
The instantaneous HIGH level is 3.3 V, but it is present for only one quarter of the time.
-
Only 50 percent duty averages to half supply in this ideal model.
-
Percent must be converted to a fraction before multiplying.
Use the scope view before the formula
The simulation below shows four visible PWM periods. The solid trace is the raw digital pin. The dashed line is the ideal average voltage. Frequency changes the period in the real circuit, but the display keeps four periods on screen so you can focus on shape and duty.
Try these moves:
- Set duty to 10 percent. Notice that the average voltage is small even though the HIGH level is still 3.3 V.
- Set duty to 90 percent. The pin is LOW only briefly, so the average moves close to 3.3 V.
- Slide frequency from 100 Hz to 20 kHz. The average value does not change, but the period changes by a factor of 200.
- Imagine an LED, a motor and a speaker on the output. The same average number can produce very different human effects.
Frequency is not just a speed knob
Duty cycle sets the average energy per period. Frequency decides how often those energy packets arrive. That choice changes what the rest of the system can feel.
At low LED PWM frequencies, the eye can see flicker, especially during motion. Around a few hundred hertz, a static LED may look steady, but a moving LED or a camera can still show bands. Many products use several kilohertz or more for visible LEDs because the goal is not merely "the LED turns on"; the goal is "the user never notices the carrier."
Motors add another human sense: hearing. A DC motor or its driver can make audible tones when PWM frequency lands in the audio band. Moving the carrier above hearing can help, but higher frequency also means more switching transitions per second. Each transition costs energy in the MOSFET and can radiate noise into nearby wiring.
There is no single perfect PWM frequency. A quiet LED indicator, a hobby motor, a buck converter and a speaker output all want different choices. The engineering habit is to name the load and the failure mode before picking the number.
You change PWM frequency from 500 Hz to 10 kHz but keep duty at 40 percent. In the ideal resistor model, what happens to average voltage?
-
Correct. In the ideal average model, Vavg is D times Vhigh. Frequency affects ripple, flicker, noise and losses, not that simple average.
-
Frequency changes how often periods occur, not the fraction HIGH inside each period.
-
A faster pulse is not automatically weaker. Real drivers may have switching limits, but that is a different effect.
-
PWM works over many frequencies; the right one depends on the load.
Resolution is the timer's staircase
The timer cannot choose every possible duty cycle. It counts integer ticks. If a PWM timer has 8 bits of duty resolution, it has 256 count values. If it has 12 bits, it has 4096 count values. More bits mean smaller duty steps.
For a 10-bit timer, the duty command has 1024 possible levels. The smallest step is about one part in 1023, roughly 0.098 percent if both endpoints are included.
But timer clocks are finite. Asking for very high PWM frequency leaves fewer timer ticks inside each period, so duty resolution falls. Asking for many bits of resolution usually limits the maximum carrier frequency. This is why microcontroller PWM peripherals talk about a trade between frequency and resolution.
On the ESP32, LEDC is the usual hardware block for this job. The exact register details vary by chip family, but the mental model is stable: a timer produces the counting base, channels compare their duty values against that counter, and GPIO routing sends the result to pins. Hardware keeps the waveform running while firmware updates duty when needed.
Why gamma correction makes LED fades look smoother
An LED's electrical current is not the same thing as perceived brightness. Human vision is much more sensitive to changes at the dim end than the bright end. A linear duty ramp, 0 percent, 1 percent, 2 percent and so on, often looks like it jumps out of black and then changes slowly near full brightness.
Many LED fades map a requested brightness through a gamma curve before writing PWM duty:
where b is the requested brightness from 0 to 1 and gamma is often near 2.2. The
exact curve depends on the LED, diffuser, ambient light and taste, but the principle is
important: PWM controls electrical time, not human perception directly.
A GPIO pin is not a power output
A microcontroller pin can produce a PWM logic signal. That does not mean the pin should power the load. GPIO current limits are small, and the package has total current and thermal limits too. Driving a status LED through a resistor may be fine. Driving a motor, LED strip, solenoid, heater or fan from a GPIO pin is not.
The usual pattern is:
- GPIO produces a PWM command.
- A transistor or driver switches the real load current.
- The power path uses a suitable supply, ground return, protection and thermal design.
- The microcontroller ground and driver ground share a reference where the logic signal needs it.
For a low-side N-channel MOSFET switch, the load connects to the positive supply, the MOSFET connects the load to ground, and the GPIO drives the gate through an appropriate gate path. Inductive loads need a path for current when the switch turns off. For a DC motor, that path may be inside an H-bridge or driver module. Without it, the collapsing magnetic field can create a voltage spike large enough to damage the switch or reset the microcontroller.
Why is a PWM-capable GPIO pin still the wrong place to connect a DC motor directly?
-
Correct. The GPIO can create the logic waveform, but the motor needs a driver, supply path and inductive-current handling.
-
A PWM pin is a digital output here. The problem is power and protection, not direction of data.
-
Motors are commonly controlled by PWM; they just need the right driver path.
-
The user interface is not the electrical issue.
Servos use pulses, but not the same promise
Hobby servos are often introduced as "PWM servos," which is true enough to wire one but sloppy enough to confuse power thinking. A standard hobby servo usually receives a repeated control pulse about every 20 ms. The width of the pulse, often near 1 ms to 2 ms, tells the internal servo controller what position to seek.
The servo does not average the pin voltage and use that as motor power. It has its own motor driver, feedback sensor and control loop inside the case. The signal wire is a timing command. The power wires deliver the actual motor current.
This distinction matters when debugging. If a servo chatters, browns out the board or resets the MCU, the fix is rarely "change duty average." You check the servo supply, grounding, decoupling, stall current and pulse timing. The control pulse is small; the mechanical work is not.
Design PWM from the load backward
Instead of starting with "what PWM frequency should I use?", start with the load:
- LED indicator: choose a current-limiting resistor or current driver, then choose a frequency high enough to avoid visible flicker. Consider gamma correction for fades.
- LED strip: use a MOSFET or LED driver, size the power supply and copper, and check heating. The GPIO only drives the gate or driver input.
- Small DC motor: use a motor driver or MOSFET with a freewheel path. Check stall current, audible noise, startup behavior and driver temperature.
- RC-filtered analog-ish output: choose the PWM frequency and RC time constant together so ripple is acceptable and response is not too slow.
- Hobby servo: generate the expected pulse-width command and supply the servo from a rail that can handle its current spikes.
At 2 kHz PWM and 35 percent duty, what are the period and on-time?
Show worked solution
Frequency is cycles per second, so
The on-time is the duty fraction times the period:
An idealized 3.3 V PWM output drives a 330 ohm resistor at 60 percent duty. Ignore LED forward voltage for this exercise. What average current does the resistor model predict?
Show worked solution
First compute average voltage:
Then use Ohm's law:
The real LED circuit will deviate because the LED is nonlinear, but the resistor model is the correct first calculation for duty scaling.
You are choosing a PWM frequency for a handheld product with a visible status LED and a small brushed DC vibration motor. Name one risk of choosing too low a frequency and one risk of choosing unnecessarily high frequency.
Show worked solution
Too low can create visible LED flicker, camera banding or audible motor whine. Too high can increase switching losses in the driver, make MOSFET transitions hotter, reduce available timer duty resolution or inject more high-frequency noise into nearby wiring. The exact compromise depends on the LED optics, motor, driver, enclosure and what the user can see or hear.
Key takeaways
- PWM is switching, not analog output: and .
- For an ideal resistive average, and .
- Frequency affects flicker, audible noise, ripple, switching loss and available timer resolution.
- GPIO PWM is a command signal for larger loads; motors, strips and heaters need a driver and protection path.
- A hobby servo pulse is a timing command to an internal controller, not a GPIO pin powering the motor.
PWM is a beautiful trick because it stays honest. The pin is either on or off. The subtlety lives in when, how often and into what. Once you see that, PWM stops being a slider in firmware and becomes a system design question: timing, load physics, power path, perception and measurement all meeting at the same edge.