0
0
Embedded Cprogramming~5 mins

Timer overflow behavior in Embedded C

Choose your learning style9 modes available
Introduction

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.

You want to measure time intervals longer than the timer's max count.
You need to trigger an action every time the timer resets.
You want to create a repeating event like blinking an LED.
You want to avoid errors caused by timer count wrapping around.
You want to handle timer interrupts correctly when overflow happens.
Syntax
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.

Examples
This checks if a 16-bit timer reached its max value and resets it.
Embedded C
if (timer_count == 0xFFFF) {
    // Timer overflow happened
    timer_count = 0; // Reset count
}
This interrupt toggles an LED every time the timer overflows.
Embedded C
void TimerOverflowISR(void) {
    TIMER_OVERFLOW_FLAG = 0; // Clear flag
    led_state = !led_state; // Toggle LED on overflow
}
Sample Program

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.

Embedded C
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.