Skip to main content

Subsection 8.2.4 Part 4: Running blinkyTimerPolled.c

The timer is now counting. The remaining question is how the program notices each elapsed period. The first answer reuses what you know: check a status flag. When the counter wraps, hardware sets UIF in TIM14_SR; the main loop checks for it, and on finding it set, clears it and toggles the LED.
Look closely at the shape of that check, because it is deliberately not what we did when we waited for the UART or the ADC to finish:
Waiting for the ADC looked like this:
while (!(ADC1->ISR & ADC_ISR_EOC)) {}   // Day 7: BLOCKING -- stand here until done
Today’s check looks like this instead:
if (TIM14->SR & TIM_SR_UIF) { ... }     // today: check once, keep moving
The while wait stalls the program at the flag until it rises. Today’s if glances at the flag once per trip around the outer main loop and moves on either way. The rest of the main loop is then free for other work. The complete program is blinkyTimerPolled.c. We’ll run it next.
#include <stdio.h>
#include "ES28.h"
#define LED (1U<<5)        // on-board LED
#define PSC_FACTOR 12000   // 12 MHz / 12000 = 1 kHz
#define ARR_FACTOR 500     // 1 kHz / 500 = 2 Hz -> toggle every 500 ms

void tim14_500ms_init();

int main(void) {
    RCC->IOPENR |= RCC_IOPENR_GPIOAEN;
    GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODE5_Msk)
                 | (GPIO_OUTPUT << GPIO_MODER_MODE5_Pos);
    GPIOA->ODR &= ~(LED);              // LED starts off

    tim14_500ms_init();
    while (1) {
        if (TIM14->SR & TIM_SR_UIF) {  // did a period elapse?
            // Clear UIF in status register
            TIM14->SR = ~TIM_SR_UIF;
            GPIOA->ODR ^= LED;         // toggle LED
        }
        // Could do other stuff here, like poll a button.
    }
    return 0;
}

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;
}

Activity 8.2.2. Run the Polled Timer.

Everything that follows today builds on this program.

(a)

Make a copy of your TemplateProject and call the new project BlinkyTimerPolled.

(b)

Download blinkyTimerPolled.c from the book’s starter files and put it in the new project’s Src folder.

(c)

Build and run. The on-board LED should blink steadily, once per second (500 ms on, 500 ms off).
Not blinking? Two checks catch nearly everything: is blinkyTimerPolled.c actually in Src and part of the build, and is there exactly one main() in the project: a leftover main.c from the template is the classic conflict. Still stuck? We’re here to help!