</>EmbeddedInterview

How do timers generate PWM?

MediumMicrocontrollers & ARM Cortex-M

Short answer: A timer counts from 0 up to an auto-reload value (ARR) and then restarts, which sets the PWM period. In PWM mode, each channel compares the counter with a compare register (CCR): the output is active while the counter is below CCR and inactive after it, which sets the duty cycle. Changing CCR changes the duty cycle; changing ARR (or the prescaler) changes the frequency.

Formulas (up-counting, STM32-style)

f_PWM = f_timer / ((PSC + 1) × (ARR + 1))
duty  = CCR / (ARR + 1)
resolution = ARR + 1 steps (log2(ARR + 1) bits)

Example: 72 MHz timer clock, PSC = 71 → 1 MHz counter (1 µs per tick); ARR = 999 → period 1000 µs = 1 kHz; CCR = 250 → 25% duty.

Trade-off: for a given timer clock, higher PWM frequency means fewer counts per period, so less duty-cycle resolution. 72 MHz with ARR = 71 gives 1 MHz PWM but only 72 steps (≈6 bits).

Set-up steps

  1. Enable the timer clock and configure the GPIO pin as the timer's alternate function.
  2. Set PSC and ARR; enable ARR preload (ARPE).
  3. Configure the channel in PWM mode 1 with CCR preload enabled, set polarity, enable the channel output (and on advanced timers the main output enable, MOE).
  4. Generate an update event to load the shadow registers, then start the counter.

Why preload (shadow) registers: new ARR/CCR values are transferred at the next update event (end of period), so changing the duty cycle mid-period cannot create a glitch (an extra short or long pulse).

Modes and features

  • Edge-aligned (counts up, sawtooth) vs center-aligned (counts up and down, triangle): center-aligned gives symmetric pulses, and the switching of different phases is spread out, which reduces current ripple and EMI in motor control.
  • Complementary outputs with dead time (advanced timers): drive the high- and low-side transistors of a half bridge without both being on at the same time (shoot-through).
  • Break input: hardware disables outputs immediately on a fault signal.
  • DMA bursts to update CCR every period (LED strips like WS2812, sine generation).

Uses: LED dimming, motor speed control, servo control (50 Hz, 1–2 ms pulses), switching power supplies, generating analogue voltages through an RC filter, buzzers.