0
0
Embedded Cprogramming~5 mins

Why timers are needed in Embedded C

Choose your learning style9 modes available
Introduction

Timers help microcontrollers keep track of time and do tasks at the right moment without stopping everything else.

To blink an LED on and off every second without stopping other code.
To measure how long a button is pressed.
To create delays without freezing the whole program.
To count events happening in a certain time.
To generate precise signals like sound or communication pulses.
Syntax
Embedded C
/* Timer setup example in embedded C */
void timer_init() {
    // Configure timer registers
    TIMER_CONTROL = TIMER_ENABLE | TIMER_MODE;
    TIMER_PRESCALER = 64; // Slow down timer clock
    TIMER_INTERRUPT_ENABLE = 1; // Enable timer interrupt
}

Timer setup depends on the microcontroller model.

Timers usually have control registers to start, stop, and set speed.

Examples
This starts the timer and sets its speed slower by dividing the clock by 64.
Embedded C
/* Start timer with prescaler 64 */
TIMER_CONTROL = TIMER_ENABLE | TIMER_PRESCALER_64;
This stops the timer by clearing its control register.
Embedded C
/* Stop timer */
TIMER_CONTROL = 0;
This sets the timer count back to zero to start counting fresh.
Embedded C
/* Reset timer count */
TIMER_COUNT = 0;
Sample Program

This program simulates a timer triggering an event 5 times. Each time the timer "interrupt" happens, it prints a message.

Embedded C
#include <stdio.h>

volatile int timer_flag = 0;

void timer_interrupt_handler() {
    timer_flag = 1; // Set flag when timer overflows
}

int main() {
    // Simulate timer setup
    printf("Timer started\n");

    // Simulate waiting for timer event
    for (int i = 0; i < 5; i++) {
        // Simulate timer interrupt
        timer_interrupt_handler();

        if (timer_flag) {
            printf("Timer event %d\n", i + 1);
            timer_flag = 0; // Reset flag
        }
    }

    printf("Timer stopped\n");
    return 0;
}
OutputSuccess
Important Notes

Timers let your program do other things while waiting for time to pass.

Using interrupts with timers makes your program more efficient.

Summary

Timers help track time without stopping the whole program.

They are useful for blinking lights, measuring time, and creating delays.

Timers often use interrupts to signal when time is up.