Ever wondered how your microcontroller knows how long to keep an LED on or how to blink it every second?

That’s the job of a timer.

Timers are the unsung heroes of embedded systems—they help us implement accurate delays, generate PWM signals, time events, and more. Today, we dig deep into:

🕒 Hardware Timers in Embedded Systems


🧠 What is a Timer?

A timer is a special peripheral that counts up (or down) at a known frequency. It’s driven by the MCU’s system clock and helps in measuring or generating time-based events.

Timers are essential for:

  • Delays
  • Pulse Width Modulation (PWM)
  • Event Counting
  • Timeouts
  • Scheduling Tasks

🔁 Busy Wait vs Hardware Timer

🚫 Busy-Wait Delay (Not Recommended):

for (volatile int i = 0; i < 100000; i++);
  • CPU is stuck in the loop
  • Not power-efficient
  • No multitasking possible

✅ Hardware Timer Delay:

Use a hardware timer that runs independently of your code.


🔧 How a Basic Timer Works

Let’s say you have:

  • System Clock = 16 MHz
  • Prescaler = 64
  • Timer counts: 16,000,000 / 64 = 250,000 ticks/sec

Now, to generate a 1 second delay, just wait until the timer reaches 250,000 counts.


🛠️ Register-Level Timer Example (STM32/AVR-style)

#define TIMER_COUNT    (*((volatile uint32_t*)0x40038048))
#define TIMER_CONTROL  (*((volatile uint32_t*)0x40038040))

void timer_init() {
    TIMER_CONTROL = 0x01; // Enable timer, prescaler config
}

void delay_ms(uint32_t ms) {
    uint32_t target = ms * 250; // Adjust based on clock/prescaler
    TIMER_COUNT = 0; // Reset
    while (TIMER_COUNT < target);
}

Note: Addresses & values depend on your MCU. Always refer to the datasheet!


🧪 Example: Blinking an LED Every 1 Second Using a Timer

void led_blink_loop() {
    while (1) {
        toggle_led();      // Toggle GPIO
        delay_ms(1000);    // Wait 1 second
    }
}

💬 PWM with Timers

Timers can also generate PWM signals (used in motors, dimming LEDs, servos).

Key registers:

  • Period Register → Total cycle time
  • Duty Cycle Register → How long the signal is HIGH
// Pseudo-code for PWM
set_pwm_period(20000);    // 20 ms period
set_pwm_duty_cycle(1500); // 1.5 ms high = center servo

📘 Real-Life Timer Applications

ApplicationUse of Timer
LED BlinkFixed delay loop
Servo MotorPWM signal generation
Debouncing ButtonSoftware delay check
Real-Time ClockLong-running timer
Sensor PollingTimed intervals

⚠️ Pro Tip

Always choose the right prescaler and timer width (8-bit, 16-bit, 32-bit) for your application. For long delays, either use:

  • A larger timer (e.g., 32-bit)
  • Cascaded timers
  • External RTC

🔍 Up Next (Day 7):

📡 UART Basics – Serial Communication with Your Microcontroller
Learn how your microcontroller talks to your PC or other devices over serial (RS-232, USB-Serial).

LEAVE A REPLY

Please enter your comment!
Please enter your name here