Timers count up or down in embedded systems. When they reach their limit, they overflow and start again. Understanding this helps control time-based actions.
Timer overflow behavior in Embedded C
void TIMER_ISR(void) {
if (TIMER_OVERFLOW_FLAG) {
TIMER_OVERFLOW_FLAG = 0; // Clear overflow flag
// Your code here to handle overflow
}
}The overflow flag is set automatically when the timer reaches its max value.
You must clear the overflow flag inside the interrupt to avoid repeated triggers.
if (timer_count == 0xFFFF) { // Timer overflow happened timer_count = 0; // Reset count }
void TimerOverflowISR(void) {
TIMER_OVERFLOW_FLAG = 0; // Clear flag
led_state = !led_state; // Toggle LED on overflow
}This program simulates a 16-bit timer counting up. When it overflows (goes from 65535 to 0), it calls an interrupt function that sets a flag and resets the count. The main loop prints a message each time overflow happens.
#include <stdint.h> #include <stdio.h> volatile uint16_t timer_count = 0; volatile int overflow_flag = 0; void TimerOverflowISR(void) { overflow_flag = 1; // Set overflow flag timer_count = 0; // Reset timer count } int main() { // Simulate timer counting up to max 16-bit value for (int i = 0; i < 70000; i++) { timer_count++; if (timer_count == 0) { // Overflow happened TimerOverflowISR(); } if (overflow_flag) { printf("Timer overflow occurred at count %d\n", i); overflow_flag = 0; } } return 0; }
Timer overflow happens when the timer reaches its maximum value and wraps to zero.
Always clear the overflow flag inside the interrupt to prevent repeated triggers.
Use overflow interrupts to handle long time delays beyond timer max count.
Timers count up to a max value and then overflow back to zero.
Overflow triggers an interrupt or flag you can use to run code.
Handling overflow lets you measure longer times and create repeating events.