Skip to main content

Subsection 8.2.2 Part 2: Designing the 500 ms Timer

The reading worked the arithmetic for a one-second period: cycles needed \(= f_{clock} \times t\text{,}\) split into a prescale factor and a count whose product hits the target. Remember that counters start counting at 0, so when writing these values to their registers we subtract one from them (Subsection 8.1.3). Today’s timer toggles the LED every 500 ms, which at 12 MHz is \(6{,}000{,}000\) cycles. Before any code, decide what to put in the two registers.
Before choosing values, watch the machine run. The reference manual’s own timing diagram for the prescaler tells the whole story, one stage at a time: the clock arrives and the counter starts; the counter reaches the auto-reload value, wraps to 0, and the update event fires; a new prescaler value written mid-period waits in a buffer; and at the next update event it takes effect and the counter clock slows.
Figure 8.2.1. The prescaler’s timing diagram (RM0490 Figure 167), first stage: the input clock CK_PSC runs; when CEN (counter enable) is set, the counter clock CK_CNT starts.
Figure 8.2.2. Second stage: the counter register climbs (F7, F8, … FC here), reaches the auto-reload value, wraps to 00, and at that instant the update event (UEV) pulse fires.
Figure 8.2.3. Third stage: software writes a new value into TIMx_PSC mid-period. The prescaler control register shows the write immediately, but the working copy, the prescaler buffer, holds the old value until the next update event.
Figure 8.2.4. The complete diagram. At the update event the buffered prescaler value takes effect: the prescaler counter begins cycling 0–3 and CK_CNT visibly slows: the division has changed from 1 to 4. A new prescaler value never changes the counting rate mid-period; it waits for the boundary to take effect.

Activity 8.2.1. Pick the Pair.

Here are four candidate (prescale factor, count) pairs for the 500 ms period. For each one, decide whether TIM14 can actually be configured that way, and why or why not. Commit an answer for all four before we discuss.
The first two work: \(10{,}000 \times 600\) and \(6000 \times 1000\) are both exactly 6,000,000, and every value fits. The third fails because 100,000 does not fit in a 16-bit counter; the fourth fails because a counter cannot count to a fraction. The code we’ll work with later uses a third good pair: prescale by 12,000 and count to 500. It earns its place by making the counter tick at exactly 1 kHz, one tick per millisecond, so the count is the period in milliseconds, and changing the blink rate later means changing one self-explanatory number.