Embedded Systems · Microcontrollers

Timer Prescalers, Auto-Reload and the Arithmetic Behind a Period

How the prescaler and auto-reload registers divide a clock into a period, why the achievable periods are quantised, and how update events and preload buffering change when a new period takes effect.

A general-purpose timer is a counter, a comparator, and two registers that divide the clock feeding it. Almost every timing requirement in a microcontroller ends up expressed through those registers, and almost every mistake in timer configuration is an arithmetic mistake: the period computed from the clock frequency does not fit the register width, or the prescaler’s reset value is off by one, or the value written to the auto-reload register is the period rather than the period minus one.

The counting chain

The timer’s input is a clock derived from the bus clock through a prescaler. The prescaler divides by an integer, and the counter increments once per divided clock. The counter counts up from zero to the value in the auto-reload register, then wraps to zero and generates an update event. The period is therefore the auto-reload value plus one, times the prescaler divisor, times the input clock period.

Both registers are sixteen bits on most general-purpose timers, which bounds the achievable periods in both directions. The shortest period is one input clock cycle with a prescaler of one and an auto-reload of zero, which is a counter that wraps every cycle. The longest is 65536 counts times a prescaler divisor of 65536, which is 2^32 input cycles. At 84 MHz that is about 51 seconds, and a requirement longer than that needs either a wider timer or a software counter that increments on the update event.

The arithmetic to hit a target period T with an input clock f is:

total_ticks = T * f
div         = ceil(total_ticks / 65536)   /* prescaler divisor */
psc         = div - 1                     /* value written to the prescaler register */
arr         = round(total_ticks / div) - 1

The order matters. Choosing the divisor as the smallest value that brings the total tick count within the sixteen-bit range maximises the resolution: the counter then has as many distinct values as possible, and the rounding error in arr is a fraction of one tick rather than a fraction of a prescaled tick.

The achievable periods are quantised, and the quantisation is the prescaler’s fault. With a divisor of P, the period can only be a multiple of P input cycles, so the error is up to P/2 cycles. For a 1 Hz period at 84 MHz the divisor is about 1282, and the nearest achievable period is within 641 cycles of the target — a relative error of about 7.6 parts per million, which is smaller than the crystal’s own tolerance. For a 10 kHz period at the same clock, the divisor is 1 and the error is a fraction of a cycle.

The relative error is therefore worst at low frequencies, which is the opposite of the intuition that slow timers are easy. A one-second period derived from a fast clock is quantised to a step of P/2 cycles, and P is large. The standard fix is to use a slower clock source for the timer — a 32.768 kHz crystal on a dedicated timer input — where the same period needs only 32768 ticks and the divisor is small.

Off-by-one in both registers

Both registers count from zero, and both are written with a value one less than the divisor they implement.

A prescaler register holding P divides by P + 1. Writing zero divides by one, which is the reset state and the pass-through setting. Writing 1 divides by two. Firmware that computes a prescaler of 84 for an 84 MHz clock and writes 84 gets a division of 85, and every derived period is long by about 1.2 percent.

An auto-reload register holding A produces a period of A + 1 counts, because the counter spends one tick at each value from zero through A inclusive. Writing the desired count instead of the count minus one makes every period one tick too long, which is a much smaller error than the prescaler’s but a systematic one.

The two errors compound when the code is written the natural way: a prescaler that is one too large and an auto-reload that is one too large both lengthen the period, and the resulting frequency is off by roughly 1/P + 1/A. For a prescaler of 1000 and an auto-reload of 1000, that is about 0.2 percent, which is large enough to break a protocol’s timing tolerance and small enough that the error is easy to miss.

There is a third off-by-one that is not arithmetic: the counter itself. A timer started by setting its enable bit begins counting from whatever value the counter register holds. If the counter was left at a non-zero value by a previous configuration, the first period is short by that many ticks. Writing zero to the counter before enabling removes it, and the order — write the counter, then enable — is the one that works, because a write to the counter while the timer is running takes effect on the next update event on some parts and immediately on others.

Update events and preload buffering

The auto-reload register is usually double-buffered: the value written goes into a preload register, and it is transferred to the active register at the next update event. The purpose is to change the period without producing a short or long cycle in the middle of a waveform.

Without buffering, writing a new auto-reload while the counter is running compares the counter against a value it may already have passed. If the new value is below the current count, the counter runs to its full width before wrapping, and the period is 65536 ticks instead of the intended one. With buffering, the new value takes effect only at the wrap, and every period is either the old one or the new one.

The same mechanism applies to the prescaler, and to the compare registers that generate PWM duty cycles. A duty-cycle update written mid-period that took effect immediately would produce a pulse of the wrong width, which in a motor drive is a torque disturbance and in a display is a visible flicker. The buffering makes the update atomic with respect to the period.

The transfer is triggered by the update event, which is also the event that generates the update interrupt. Firmware that wants a new period to take effect immediately can set the update-generation bit, which forces the transfer without waiting for the wrap. Doing so also sets the update flag and, if the interrupt is enabled, raises the interrupt — a side effect that produces one spurious interrupt per forced update unless the flag is cleared before the interrupt is enabled.

One-pulse mode and the period as a deadline

A timer in one-pulse mode counts one period and then stops. The mode exists for generating a precisely timed pulse or for implementing a timeout: the counter is started, the output is asserted, and when the counter reaches the auto-reload value the output is de-asserted and the timer halts. A timer that paces a converter’s start-of-conversion input has a second deadline attached to it, the acquisition window covered in the SAR converter article.

The timeout use is the more interesting one. A peripheral that must respond within a bounded time is started alongside a timer, and the timer’s update interrupt signals that the response did not arrive. The timer’s period is the deadline, and its accuracy is the accuracy of the clock it derives from, which for an internal RC oscillator is a few percent over temperature and for a crystal is tens of parts per million.

The accuracy matters because the deadline has to be longer than the peripheral’s worst-case response and shorter than the time the system can tolerate waiting. A deadline computed from a nominal period with no allowance for the oscillator’s tolerance can expire before a legitimate response arrives, and the resulting spurious timeout is intermittent and temperature-dependent.

PWM as a ratio of two registers

A PWM channel compares the counter against a compare register and drives the output high while the counter is below it. The duty cycle is the compare value divided by the period, and the resolution is one count.

The relationship between frequency and resolution is a direct trade. At a fixed clock, a longer period gives more counts and finer duty resolution but a lower PWM frequency. A motor driver that needs a 20 kHz switching frequency and a 12-bit duty resolution needs 4096 counts per period at 20 kHz, which is an 81.9 MHz timer clock. A converter that needs only 8-bit resolution needs 256 counts at 20 kHz, which is 5.1 MHz. Choosing the resolution first and deriving the clock from it is the calculation that avoids both an inaudible whine from a motor and a visible step in a dimmed LED.

The compare register’s buffering is what makes a duty change clean, and the counter’s direction is what makes it symmetric. A timer in centre-aligned mode counts up to the auto-reload value and back down, so the period is twice the auto-reload value and the compare match happens twice per cycle. Centre alignment halves the effective frequency for the same period register and produces a symmetric waveform whose harmonics are lower and whose edges are evenly spaced, which is why it is used for motor control and not for audio.

The output’s polarity and idle state are separate register fields, and their reset values are the ones that matter at the moment the timer is enabled. An output that comes up asserted drives whatever it is connected to for the interval between the timer’s enable and the first compare match, and for a gate driver that interval is a shoot-through. Setting the idle state and the polarity before enabling the output, and enabling the output only after the counter is running, is the sequence that avoids it.

Chaining timers for periods beyond the register width

A requirement longer than 2^32 input cycles, or a requirement that combines a long period with fine resolution, is met by chaining. One timer’s update event drives another timer’s clock input, and the pair counts as a single wider counter.

The chaining is configured in the timer’s internal trigger mapping, and the slave timer must be configured in external clock mode with the trigger as its source. The master’s period becomes the slave’s tick, so the combined period is the product of the two periods and the resolution is the master’s period. A master counting 1000 ticks and a slave counting 1000 ticks give a combined period of 10^6 ticks with a resolution of 1000 ticks, which is the same quantisation problem as a large prescaler and for the same reason.

The alternative for long periods is to count update events in software. The timer runs at its natural period, and each update interrupt increments a counter. The period is then the timer’s period times the software count, with no quantisation penalty, at the cost of an interrupt per timer period and the latency of the interrupt handler in the total. For periods of seconds, an interrupt every millisecond is 1000 interrupts per second, which is a real load on a small core and a real source of the jitter described in the interrupt controller article.

The choice between chaining and software counting turns on whether the period must be exact. A wall-clock timekeeping counter can tolerate the interrupt latency because the error is bounded and correctable; a waveform generator cannot, because the latency is jitter in the output. For the waveform the hardware chain wins, and for the clock the software count wins on flexibility.

References

  1. STM32F4 Series Reference Manual (RM0090) — STMicroelectronics
  2. ARMv7-M Architecture Reference Manual (ARM DDI 0403) — Arm Limited
  3. Cortex-M3 Devices Generic User Guide (ARM DUI 0552) — Arm Limited