In this lesson, you will learn how to expand the reach of your hardware timers by using interrupt handlers to track overflow events for long-duration timekeeping.
The Limitation of Hardware Timers
In our previous work, we used hardware timers to trigger events at fixed intervals. However, a timer register has a finite size—typically 8, 16, or 32 bits. If you are using a 16-bit timer running at 1 MHz, the timer will reach its maximum value (65535) and "roll over" to zero in just 65.5 milliseconds. If you need to track a duration of several seconds or minutes, a single register simply isn't big enough.
Extending Capacity with Interrupts
To measure intervals longer than the timer’s hardware limit, we utilize the Timer Overflow Interrupt. When the timer register transitions from its maximum value back to zero, it triggers a hardware interrupt. We can create a global variable (often called a "tick count" or "overflow counter") and increment it inside this Interrupt Service Routine (ISR).
By combining the current value of the hardware timer with our software-based overflow counter, we create a virtual "wide" timer:
volatile uint32_t overflow_count = 0;
// This ISR runs every time the hardware timer hits its limit
void TIMER_OVERFLOW_IRQHandler(void) {
overflow_count++;
// Clear the interrupt flag here
}
// To get the total time elapsed:
uint64_t get_total_ticks(void) {
return (overflow_count << 16) | TIMER_REG_VALUE;
}
Critical Considerations
When implementing this, you must ensure your system handles these variables safely. Because overflow_count is updated inside an ISR and accessed in your main code, it should be marked as volatile. Furthermore, because the timer might overflow while you are reading its register, you must be careful to handle "race conditions"—where the overflow occurs exactly between reading the timer value and the overflow counter. In such cases, reading the counter, the timer, and the counter again (and checking for consistency) ensures your timekeeping remains accurate over long periods.
Key Takeaway: By incrementing a software counter within a timer overflow interrupt, you effectively "stitch" together multiple hardware cycles to create an extended, high-precision timekeeping system.