Skip to main content

Subsection 8.1.2 A Circuit Whose Whole Job Is Counting

A hardware timer is a small digital circuit inside the STM32C031C6, separate from the CPU, built around one job: counting clock pulses. At its core (Figure 8.1.1) it is a register that stores the current count and an adder that increments it; on each tick of its input clock, the stored count is replaced by the count plus one. Once started, it counts whether the CPU is computing, sitting in a delay, or doing nothing at all. The timer (also called counter) needs no attention to keep running: it runs entirely in hardware.
Figure 8.1.1. The core of a counter: a register holds the current count \(n\text{;}\) multiplexers select the next value: one more than the current count, or 0 to restart. (The general circuit can also count down; our timers count up.) The register updates on the rising edge of its clock. The slash marks indicate multi-wire (bus) connections.
The STM32C031C6 has five of these timers (TIM1, TIM3, TIM14, TIM16, and TIM17), all built around 16-bit counters, each independently configurable. They range from simple to elaborate: TIM14 is the simplest, and it is the one this chapter uses. All five, TIM14 included, can also measure the width of input pulses and generate output waveforms such as PWM with no CPU involvement; those abilities return in the motor chapters.
Two registers turn a bare counter into a programmable timer. The prescaler (PSC) divides the timer’s input clock down to a chosen counting rate. The auto-reload register (ARR) holds the count at which the timer wraps: the counter (CNT) runs 0, 1, 2, … up to the auto-reload value, then resets to 0 and signals that a period has elapsed. That signal is called the update event. Rate, range, wrap: that is the whole machine. (The chip’s full block diagram, with much more bolted around this core, is in Subsection 8.3.3 when you want it.)
The update event leaves a footprint your code can see: the hardware sets the update interrupt flag (UIF), a bit in the timer’s status register TIM14_SR. The division of labor mirrors what you saw with the ADC: the hardware sets the flag; noticing it, and then clearing it so the next period can be seen, is your code’s job.
If you have used Arduino’s millis(), one adjustment before going on: millis() reads a free-running counter fed by a timer you never configured. This chapter hands you exactly what millis() hides: choosing the count rate, noticing the wrap, and clearing the flag yourself.