Skip to main content

Subsection 8.2.3 Part 3: Five Lines of Initialization

Turning the (prescale, count) pair chosen in Subsection 8.2.2 into a running timer takes five register writes, and every one of them is a pattern you have used before. Here they are, one at a time.
The clock. Like every peripheral, TIM14 is unreachable until its clock is enabled. All five timers live on the APB bus. TIM1, TIM14, TIM16, and TIM17 are enabled in RCC_APBENR2, the same register where you enabled the ADC’s clock; TIM3’s enable bit is one register over, in RCC_APBENR1.
RCC->APBENR2 |= RCC_APBENR2_TIM14EN;   // enable clock access to TIM14
Figure 8.2.8. The RCC peripheral-clock-enable registers, with TIM14EN boxed in RCC_APBENR2 (offset 0x40). Familiar neighbors are visible: RCC_IOPENR, where the GPIO port clocks are enabled, sits at 0x34, and ADCEN, Day 7’s clock enable, lives in the same APBENR2 row. Until TIM14EN is set, TIM14’s registers do not respond.
The rate and the range. The prescaler and auto-reload values you chose go into PSC and ARR, each written to the register as value minus one:
#define PSC_FACTOR 12000   // 12 MHz / 12000 = 1 kHz: one tick per ms
#define ARR_FACTOR 500     // 500 ticks = 500 ms per update event

TIM14->PSC = PSC_FACTOR - 1;   // counting starts at 0, so minus one
TIM14->ARR = ARR_FACTOR - 1;
Figure 8.2.9. Three TIM14 registers from the register map: the counter itself (CNT, offset 0x24), the prescaler (PSC, 0x28), and the auto-reload value (ARR, 0x2C), each 16 bits. The hardware divides by PSC + 1 and counts from 0 through ARR, so both PSC and ARR are written as the desired factor minus one.
A clean start. The counter register CNT holds whatever it held before: starting a 500-count period from a leftover 437 would make the first blink arrive early. Zero it:
TIM14->CNT = 0;   // don't start counting from a leftover value
Go. The CEN bit (counter enable) in the control register TIM14_CR1 starts the counting. From this line on, the timer runs by itself:
TIM14->CR1 |= TIM_CR1_CEN;   // start the counter
Figure 8.2.10. An excerpt of the TIM14 register map (RM0490 Table 73) with today’s two key bits marked: CEN in TIM14_CR1 starts the counter, and UIF (update interrupt flag) in TIM14_SR is set by hardware each time the counter wraps to 0 after reaching the auto-reload value, and is your responsibility to clear.
Assembled in order (clock, rate, range, clean start, go) the five lines make the day’s first new function:
void tim14_500ms_init() {
    // enable clock access to timer 14 (on APB bus)
    RCC->APBENR2 |= RCC_APBENR2_TIM14EN;
    // Set prescaler value
    TIM14->PSC = PSC_FACTOR - 1;   // starts counting at 0
    // Set auto-reload value
    TIM14->ARR = ARR_FACTOR - 1;
    // Clear counter
    TIM14->CNT = 0;
    // Enable timer
    TIM14->CR1 |= TIM_CR1_CEN;
}