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

Managing Timer Auto-Reload and Counter Registers

Configure timer registers to control the frequency and overflow behavior of hardware counters for precise timing intervals.

In this lesson, you will learn how to manipulate the Counter and Auto-Reload registers to precisely control how often a timer triggers an event.

The Mechanics of Counting

At the heart of every hardware timer is a Counter Register (CNT). This register acts like a digital odometer; it increments (or decrements) its value every time a clock pulse hits the timer. If the timer is fed by a 1MHz clock, the CNT register value increases exactly one million times per second.

However, a counter on its own is just a number that grows until it hits the hardware limit and rolls over to zero. To make this useful for timing specific intervals, we use the Auto-Reload Register (ARR).

Defining the Period

The ARR serves as a "limit" or "target" value. When the CNT register reaches the value stored in the ARR, two things happen:

  1. The hardware automatically resets the CNT back to zero.
  2. A status flag is set (often triggering an interrupt), signaling that your defined time interval has elapsed.

By changing the value in the ARR, you effectively change the frequency of the timer. If your timer clock is 1MHz:

  • Setting ARR = 999 means the timer resets every 1,000 pulses, giving you a 1kHz frequency (1ms period).
  • Setting ARR = 4999 means the timer resets every 5,000 pulses, giving you a 200Hz frequency (5ms period).

Implementation Example

To configure a timer to trigger an event at a specific interval, you write to these registers directly through the peripheral memory structure:

// Assume TIMER1 is mapped to a structure pointer
// Set the limit to 4999 to trigger every 5000 clock cycles
TIMER1->ARR = 4999; 

// Reset the current counter to start fresh
TIMER1->CNT = 0;

// The timer will now count from 0 to 4999 and wrap around

By combining the clock prescaler (which slows down the input clock) with the ARR (which defines the reset point), you gain complete control over the timing resolution of your application.

Key Takeaway: The Counter Register tracks elapsed clock cycles, while the Auto-Reload Register defines the threshold at which the timer resets, allowing you to generate precise, repeating intervals.