0
0
Embedded Cprogramming~7 mins

Timer prescaler and clock division in Embedded C

Choose your learning style9 modes available
Introduction

Timers count clock pulses to measure time. A prescaler slows down the timer clock so it counts slower, letting you measure longer times easily.

You want to create a delay longer than the timer's maximum count.
You need to measure slow events with a fast microcontroller clock.
You want to reduce power by running the timer at a slower speed.
You want to generate a specific frequency output using a timer.
You want to adjust timer resolution for different applications.
Syntax
Embedded C
TIMx->PSC = prescaler_value; // Set prescaler register
TIMx->ARR = auto_reload_value; // Set timer max count
TIMx->CR1 |= TIM_CR1_CEN; // Enable timer

The prescaler divides the main clock by (prescaler_value + 1).

Setting prescaler to 0 means no division (timer runs at full clock speed).

Examples
This sets the timer to count every 1 ms if the clock is 8 MHz (8 MHz / 8000 = 1 kHz).
Embedded C
TIM2->PSC = 7999; // Divide clock by 8000
TIM2->ARR = 999;  // Count up to 1000
TIM2->CR1 |= TIM_CR1_CEN; // Start timer
Timer counts very fast, useful for short precise timing.
Embedded C
TIM3->PSC = 0; // No prescaler, timer runs at full clock speed
TIM3->ARR = 65535; // Max count for 16-bit timer
TIM3->CR1 |= TIM_CR1_CEN; // Start timer
Sample Program

This program sets up a timer to count 1 second intervals by using a prescaler and auto-reload value. The timer clock is slowed down by the prescaler to make counting easier.

Embedded C
#include <stdint.h>
#include "stm32f4xx.h" // Example MCU header

void timer_init(void) {
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN; // Enable clock for TIM2
    TIM2->PSC = 7999; // Prescaler: divide clock by 8000
    TIM2->ARR = 999;  // Auto-reload: count to 1000
    TIM2->CNT = 0;    // Reset counter
    TIM2->CR1 |= TIM_CR1_CEN; // Start timer
}

int main(void) {
    timer_init();
    while(1) {
        if (TIM2->SR & TIM_SR_UIF) { // Check update interrupt flag
            TIM2->SR &= ~TIM_SR_UIF; // Clear flag
            // Timer reached 1 second (assuming 8 MHz clock)
        }
    }
}
OutputSuccess
Important Notes

Prescaler value is always one less than the division factor.

Changing prescaler affects timer speed and resolution.

Always clear timer interrupt flags after handling to avoid repeated triggers.

Summary

Prescaler slows down the timer clock by dividing the main clock.

Use prescaler to measure longer times or slower events.

Timer count speed = main clock / (prescaler + 1).