STM32 Programming· Live

How a timer counts

A timer is a peripheral that counts clock pulses on its own, while the CPU does other work. Three settings decide how it counts: the prescaler, the counter and the auto-reload value.

Clock and timer are not the same

The clock is the oscillator that drives the whole chip. A timer is a peripheral that counts clock ticks and fires events. Timers measure time, make PWM signals on a pin, interrupt the CPU at a fixed rate and measure outside signals.

Timer block diagram: the clock goes through the prescaler into the counter

Three settings

  1. Prescaler (PSC) divides the input clock, so the timer counts slower.
  2. Counter: the register that goes up by one on every timer tick. On TIM1 it is 16 bits wide: 0 to 65535.
  3. Auto-reload register (ARR): the top value. After the counter reaches ARR, the next tick takes it back to 0. That moment is called an update event. In CubeMX, ARR is called Counter Period.

ftimer = fclock / (PSC + 1)

The +1 is there because PSC = 0 means "divide by 1". fclock is the clock going into the timer; ftimer is how fast it counts.

Example: a 16 MHz clock and PSC = 15999 give 16 000 000 / 16 000 = 1000 counts per second: one count every millisecond.

Counting modes

  • Up (the default): 0 up to ARR, then back to 0
  • Down: ARR down to 0, then back to ARR
  • Center-aligned: 0 up to ARR, then back down to 0