Skip to main content

Subsection 13.4.2 The Timer Arithmetic

For a pulse period \(T_p\text{,}\) the counter divides each period into ARR + 1 counts, so the smallest pulse width, and the smallest change in pulse width, is \(T_0 = T_p/(\text{ARR}+1)\text{.}\) The prescaler and the auto-reload value have to satisfy \(\text{prescaleFactor} \times (\text{ARR}+1) = 12\text{ MHz} \times T_p\text{,}\) with ARR at most 65,535. The number of steps between 1 ms and 2 ms is \(1\text{ ms}/T_0\text{,}\) the servo’s resolution counted in steps rather than in microseconds (Subsection 11.3.5 measures it the other way), and the angle per step is 180° divided by that number, using the ±90° convention. A step finer than the servo’s dead band, or than its gear train’s backlash, is more finely grained than is worth doing. What is written into the registers is each number minus one, because the prescaler and the counter both start counting at 0: TIM14->PSC = prescaleFactor-1 and TIM14->ARR = timerMax-1. In PWM mode 1 the pin is HIGH while the counter is below CCR1, so CCR1 is the number of counts the pin is HIGH.
A program that needs a periodic tick while TIM14 is in use producing a PWM signal uses a second timer. TIM16 (Reference Manual §18, General-purpose timers (TIM16/TIM17)) has the same prescaler, counter and auto-reload core, its interrupt is position 21 in the vector table, and its handler is TIM16_IRQHandler(). The initialization is the one from Day 8 on a different timer, with the period as a parameter.