Timer Counter in Microcontroller Explained with Embedded C Example
timer counter in a microcontroller is a hardware feature that counts clock pulses to measure time intervals or events. In Embedded C, it is used to create delays, measure time, or count external events by configuring and reading special registers.How It Works
Think of a timer counter as a stopwatch inside the microcontroller. It counts pulses from a clock source, which can be the main system clock or an external signal. Each pulse increases the counter value by one, like ticking seconds on a watch.
When the counter reaches a set limit, it can trigger an action, such as generating an interrupt or resetting to zero. This helps the microcontroller keep track of time or count events without using the main processor constantly.
For example, if you want to blink an LED every second, the timer counter counts clock pulses until one second passes, then tells the microcontroller to toggle the LED.
Example
This example shows how to configure a timer counter in Embedded C to create a simple delay using an 8-bit timer on an AVR microcontroller.
#include <avr/io.h> #include <util/delay.h> void timer0_init() { // Set timer0 with prescaler 64 TCCR0 |= (1 << CS01) | (1 << CS00); TCNT0 = 0; // Initialize counter to 0 } void delay_1sec() { TCNT0 = 0; // Reset counter while (TCNT0 < 250) { // Wait until counter reaches 250 // With prescaler 64 and 16MHz clock, 250 counts ~1ms (not 1 second) // This is a simplified example; actual delay calculation depends on clock and prescaler } } int main(void) { DDRB |= (1 << PB0); // Set PB0 as output (LED) timer0_init(); while (1) { PORTB ^= (1 << PB0); // Toggle LED delay_1sec(); } return 0; }
When to Use
Use timer counters when you need precise time measurement or event counting without blocking the main program. They are ideal for:
- Generating accurate delays (e.g., blinking LEDs, timing sensors)
- Measuring time intervals (e.g., pulse width, frequency)
- Counting external events (e.g., button presses, rotations)
- Creating periodic interrupts for multitasking
For example, in a washing machine controller, timers help manage wash cycles by counting time automatically.
Key Points
- Timer counters count clock pulses to measure time or events.
- They work independently from the main CPU, freeing it for other tasks.
- Configuring timers involves setting registers for clock source and count limits.
- Timers can trigger interrupts when they overflow or reach a set value.
- Embedded C code accesses timer registers to control and read timer counters.