Try Embedded

Timers and PWM

Prescalers, auto-reload, input capture, output compare and dead time.

A counter with superpowers

A hardware timer is a counter driven by a clock. Around that counter, comparators and capture registers let it generate precise periodic interrupts, produce PWM waveforms, measure pulse widths and frequencies, count external events and trigger other peripherals, all without the CPU.

The counting chain

timer clock --> [ prescaler PSC ] --> counter CNT --> compare with ARR --> update event
                                         |
                                         +--> compare with CCRx --> output / interrupt
                                         +--> capture into CCRx on an input edge
  • Prescaler (PSC): divides the timer clock. Counter frequency = f_timer / (PSC + 1).
  • Auto-reload (ARR): the counter counts 0 to ARR, then wraps and generates an update event. Period = (ARR + 1) counter ticks.
  • So the update frequency is f_timer / ((PSC + 1) * (ARR + 1)).

Count direction can be up, down or centre-aligned (up then down), which matters for motor control.

Choosing PSC and ARR

There are many solutions; prefer a counter tick that is a round number (1 µs or 1 MHz), and a large ARR for resolution.

#include <stdio.h>
#include <stdint.h>

/* Find PSC and ARR for a target frequency on a 16-bit timer. */
static int timer_config(uint32_t f_timer, uint32_t f_target, uint32_t *psc, uint32_t *arr) {
  uint32_t total = f_timer / f_target;             /* (PSC+1)*(ARR+1) */
  for (uint32_t p = 0; p <= 0xFFFF; p++) {
    uint32_t a = total / (p + 1);
    if (a <= 0x10000 && a > 0) { *psc = p; *arr = a - 1; return 0; }
  }
  return -1;
}

int main(void) {
  uint32_t psc, arr;
  uint32_t targets[3] = { 1000, 50, 20000 };       /* 1 kHz tick, 50 Hz servo, 20 kHz PWM */
  for (int i = 0; i < 3; i++) {
    if (timer_config(84000000u, targets[i], &psc, &arr) == 0) {
      uint32_t actual = 84000000u / ((psc + 1) * (arr + 1));
      printf("%5u Hz: PSC=%u ARR=%u -> %u Hz\n", targets[i], psc, arr, actual);
    }
  }
  return 0;
}

The smallest prescaler that fits gives the finest PWM duty resolution.

Pitfall: On STM32, timers on an APB bus whose prescaler is not 1 are clocked at twice the APB frequency. Using the bus clock in the formula gives timers running at the wrong rate.

Periodic interrupts

The simplest use: an update interrupt every N ms for a scheduler tick or a control loop. Hardware timing has no drift and no jitter from the main loop. Clear the update flag in the handler.

PWM: output compare

Pulse-width modulation switches a pin at a fixed frequency with a variable duty cycle. It drives LED brightness, motor speed, servo position, heater power, and (filtered) produces an analog voltage.

In PWM mode 1, the output is high while CNT < CCR and low after, so:

duty = CCR / (ARR + 1)

Changing CCR changes the duty. With preload enabled (recommended), the new value takes effect at the next update event, so a period is never cut short or doubled, which would otherwise cause glitches.

ApplicationTypical frequencyNotes
LED dimming200 Hz to 20 kHzAbove ~200 Hz to avoid visible flicker; high frequencies to avoid camera banding
Hobby servo50 HzPulse 1 to 2 ms encodes position
DC motor16 to 25 kHzAbove hearing
Switch-mode power100 kHz to MHzUsually a dedicated controller or high-resolution timer

Input capture

On an input edge, the timer copies CNT into a capture register. Two captures give a period; capturing both edges gives a pulse width. Uses: measuring a frequency, reading an ultrasonic sensor's echo, decoding an RC receiver, timestamping events precisely.

/* Period between two rising edges, with wrap-around handled by unsigned arithmetic */
uint16_t now = TIM2->CCR1;
uint16_t period_ticks = (uint16_t)(now - last_capture);
last_capture = now;

Many timers offer PWM input mode, which resets the counter on one edge and captures period and width in two channels with no software arithmetic.

Counting and encoders

  • External clock mode: the counter counts edges on a pin; read CNT for a pulse count (flow meters, Geiger counters).
  • Encoder mode: two inputs from a quadrature encoder; the counter counts up or down with direction, in hardware, at any speed.

Motor control features

Advanced timers (TIM1/TIM8 on STM32) add:

  • Complementary outputs: a channel and its inverse, to drive the high- and low-side transistors of a half bridge.
  • Dead time: a programmable delay between one transistor turning off and the other turning on, so both are never on together (shoot-through, which destroys the bridge).
  • Break input: a hardware fault input that forces all outputs to a safe state within nanoseconds, without software.
  • Centre-aligned mode: symmetric PWM, which reduces harmonics and gives a natural point in the middle of the period to trigger the ADC for current sensing.

Triggering other peripherals

A timer's update or compare event can trigger an ADC conversion, a DAC update or a DMA transfer, and timers can be chained (one timer's overflow clocks another). This is how precise sample rates are produced with zero CPU involvement.

Interview question: How would you measure the frequency of a square wave between 10 Hz and 100 kHz?

Answer: Use a timer's input capture: on each rising edge the hardware latches the counter, and the difference between consecutive captures (unsigned subtraction handles wrap) is the period in ticks; frequency = timer clock / period. Choose the prescaler so the slowest signal still fits in the counter range, or count overflows between captures. For high frequencies, counting edges in a fixed gate time (external clock mode plus a second timer as the gate) gives better resolution than measuring one period; switching method by range is common.

Interview question: What is dead time in PWM and why is it needed?

Answer: In a half bridge, the high-side and low-side switches are driven with complementary signals. Transistors take time to turn off, so if one turns on the instant the other is told to turn off, both conduct briefly and short the supply through the bridge (shoot-through), causing heating or destruction. Dead time inserts a short delay, typically tens to hundreds of nanoseconds, during which both are off at each transition. Advanced timers generate it in hardware on complementary outputs.

Build it: the greenhouse fan on 25 kHz PWM

This is step 2 of the module project: the ventilation fan, whose speed is set by a hardware timer, so the CPU does nothing while it runs.

Lab: Drive a 4-wire fan at 25 kHz PWM

The greenhouse uses a 4-wire PC-style fan. Its PWM input expects 25 kHz (above hearing, so the fan does not whine), and a duty cycle from 0 to 100 % sets its speed. The fan is on TIM3 channel 1.

  • fan_init(timer_clk_hz) sets TIM3 up for 25 kHz PWM with the prescaler at 0 (the finest duty steps): ARR = timer_clk_hz / 25000 - 1. Channel 1 is in PWM mode 1 with preload, so CCMR1 holds 0x68 (OC1M = 110, OC1PE = 1), with its output enabled and active high (CCER = 0x1). Start the counter with ARPE set, then trigger an update with EGR. The fan starts stopped (duty 0).
  • fan_set_percent(percent) sets the duty in CCR1, as (ARR + 1) * percent / 100. 100 % must be fully on: in PWM mode 1, CCR1 = ARR still leaves a short low pulse every period.
  • The fan's datasheet says it stalls below 20 % and may not start again, so any request from 1 to 19 % runs at 20 %. Values below 0 mean 0 and values above 100 mean 100.

Going deeper

Interview question: How would you drive a greenhouse fan quietly at any speed?

Answer: PWM a MOSFET from a hardware timer at about 25 kHz, above hearing, with a flyback diode across the motor, and map the requested speed to duty with a minimum running duty so the fan does not stall. Ramp changes rather than stepping, and read the fan's tachometer to detect a stalled or failed fan.

Interview question: What does the auto-reload preload (ARPE) bit do and why enable it?

Answer: With preload enabled, writes to the auto-reload register go into a shadow register and take effect only at the next update event, at the end of the current period. Without it, the new value takes effect immediately; if the counter is already past the new value it runs all the way to the maximum before wrapping, producing one very long period. Preload on ARR and on the compare registers avoids such glitches when changing frequency or duty.

Interview question: How would you generate a precise ADC sampling rate with no CPU involvement?

Answer: Configure a timer to produce an update or compare event at the sample rate and select that event as the ADC's external trigger, with DMA collecting the results. Each conversion then starts exactly on the timer edge regardless of interrupts or software latency, giving zero jitter.

Explain it: In your own words, explain how a timer generates a PWM signal and how you change its duty cycle.

Answer: The timer counts up from zero to the auto-reload value and wraps, which sets the period. A compare register is checked against the counter: in PWM mode 1 the output is high while the counter is below the compare value and low after it, so the fraction of the period spent high is compare value divided by period. Changing the compare value changes the duty cycle; with preload enabled the new value takes effect at the start of the next period so no cycle is cut short.