Subsection 8.1.3 How Fast and How Far to Count
Configuring a timer means answering two questions: how fast should it count, and how far? You do not program the timer with an amount of time. You program it with a counting rate (via the prescaler) and how far to count (via the auto-reload value), and the time period follows from the arithmetic.
Start from the clock. The STM32C031C6 runs at \(f_{clock} = 12\) MHz, so a desired waiting period \(t\) converts to a number of clock cycles you need to count through to get that wait as \(\text{cycles} = f_{clock} \times t\text{.}\) A one-second period is \(12{,}000{,}000\) cycles, and there is the problem: the counter and the auto-reload register are 16 bits wide, so each holds \(2^{16} = 65{,}536\) distinct values, numbered 0 through 65,535. Twelve million does not fit into a 16-bit register.
The prescaler is the fix. It sits between the clock and the counter and divides the clock rate by any integer from 1 to 65,536, so the counter can count slower instead of farther. For example, with the prescaler dividing by 12,000, the counter ticks at \(12{,}000{,}000 / 12{,}000 = 1000\) ticks per second, one tick per millisecond, and one second is a count of just 1000, which fits easily. The waiting period comes from the product: \(\text{period} = (\text{prescale factor} \times
\text{count}) / f_{clock}\text{.}\)
One convention will trip you if you are not warned: both registers are written as the desired value minus one since both start counting from zero (the prescaler works by counting also). The prescaler divides by \(\text{PSC} + 1\text{,}\) and the counter counts from 0 to ARR inclusive: 0 through 499 is 500 ticks. So a divide-by-12,000 prescale is written as
PSC=11999, and a count of 1000 is written as ARR=999. The worked example, in full:
One update event per second, from a 12 MHz clock: write \(\text{PSC} = 12{,}000 - 1\text{,}\) so the counter ticks at 1 kHz; write \(\text{ARR} = 1000 - 1\text{,}\) so the counter wraps every 1000 ticks. Check: \(12{,}000 \times 1000 =
12{,}000{,}000\) cycles, exactly one second. Exactly, that is, in counts: the 12 MHz clock derives from the chip’s HSI48 RC oscillator, which the datasheet (Table 41) specifies at 47.92 to 48.40 MHz over temperature, so the arithmetic is exact and the second itself is good to about one percent.
One more thing to bring: the prescaler gives you freedom. Many (prescale, count) pairs produce the same period, as long as the product is right and both values fit in 16 bits. In class you will choose among such pairs for a different period, and walk the hardware’s own timing diagram step by step, so bring the arithmetic, not just the answer.
