Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 253 of 9363. Microcontroller Fundamentals and Bare-Metal CFree lesson

Initializing Internal Timer Clock Prescalers

Calculate and set prescaler values to divide the system clock frequency into a usable time base for peripheral operations.

Initializing Internal Timer Clock Prescalers

In this lesson, you will learn how to divide a high-frequency system clock into a slower, usable "heartbeat" for your peripheral timers.

Why Do We Need Prescalers?

Your microcontroller likely runs its CPU at a high frequency (e.g., 80 MHz). If you want to blink an LED every second using a 16-bit timer, that timer will overflow much too quickly if it counts every single CPU clock cycle. A 16-bit timer caps out at 65,535 counts. At 80 MHz, it would overflow in less than one millisecond!

A prescaler acts like a mechanical gear reduction system. It takes the fast input clock signal and only allows every Nth pulse to reach the timer's counter register. This slows down the timer's "time base," allowing it to measure much longer intervals.

The Calculation

The formula to determine your prescaler value (PSCPSC) is straightforward: TimerClock=SystemClockPSC+1TimerClock = \frac{SystemClock}{PSC + 1}

If you want your timer to tick at 1 MHz while your system is running at 80 MHz, you need to divide the frequency by 80. Since registers are typically zero-indexed, you set your prescaler register to 80−1=7980 - 1 = 79.

Implementation in C

Configuring the prescaler involves writing to a specific control register associated with the timer peripheral. Using the bitwise techniques you learned previously, you would modify the prescaler register (let's call it TIM_PSC) like this:

// Goal: Set prescaler to 79 to divide an 80MHz clock into a 1MHz timer base
void Timer_Init(void) {
    // Clear the existing prescaler bits (assuming they occupy bits 0-15)
    TIMER1->PSC &= ~0xFFFF;
    
    // Set the prescaler value
    TIMER1->PSC = 79; 
    
    // Enable the timer to start counting
    TIMER1->CR1 |= (1 << 0);
}

By adjusting the prescaler, you gain fine-grained control over how "fast" time passes for your peripheral, enabling everything from precise PWM motor control to simple delay loops without wasting CPU cycles.

Key Takeaway: The prescaler is a frequency divider that allows you to match the high speed of the system clock to the slower, predictable timing requirements of your hardware peripherals.