DEV Community

Hedy
Hedy

Posted on

How do timers work in microprocessor systems?

In microprocessor systems, timers are essential peripherals that provide time-related functionality such as delays, pulse generation, event counting, and task scheduling.

Let’s break down how timers work:

1. What is a Timer?
A timer is a hardware counter that increases (or decreases) at a defined rate, usually driven by the system clock or a prescaled version of it.

2. Timer Core Components

3. How Timers Work
a) Basic Timer Operation

  1. Timer receives a clock input (e.g., 16 MHz).
  2. Prescaler divides it (e.g., by 16000 → 1 kHz).
  3. Counter starts from 0 and counts up to a set value (e.g., 999).
  4. When the counter reaches the top value:
  • It resets (or rolls over).
  • Triggers an interrupt (if enabled).
  • Optionally toggles a pin (PWM).

4. Common Timer Modes
a) Delay or Timekeeping

  • Generate accurate delays using overflow interrupts.
  • Example: Millisecond timer (like Arduino’s millis() function).

b) PWM Generation (Pulse Width Modulation)

  • Use timer to generate variable duty cycle square waves.
  • Example: Control LED brightness or motor speed.

c) Input Capture

  • Records timestamp when a signal edge (rising/falling) occurs.
  • Used to measure frequency or pulse width.

d) Output Compare
Triggers an action (e.g., pin toggle) when timer matches a compare value.

e) Event Counting / Quadrature Decoding
Timers can count external pulses, useful in tachometers or encoders.

5. Example: 8-bit Timer Operation

  • Timer with 8-bit resolution (counts 0–255).
  • Prescaler = 64, system clock = 16 MHz → Timer ticks at 250 kHz.
  • Overflow occurs every:256/250,000=1.024 ms
  • Useful for periodic interrupts.

6. Code Example: Arduino Timer Delay Using millis()

cpp

unsigned long prevTime = 0;
unsigned long interval = 1000;  // 1 second

void loop() {
  if (millis() - prevTime >= interval) {
    prevTime = millis();
    Serial.println("1 second passed");
  }
}
Enter fullscreen mode Exit fullscreen mode

Internally, millis() uses Timer0 on Arduino Uno (ATmega328P), counting overflows every ~1 ms.

7. Advanced Use: STM32 or ARM Cortex Timer

  • Multiple timers (TIM1, TIM2, etc.).
  • 16/32-bit counters.
  • Can be chained or triggered by other timers/events.
  • Used in RTOS tick timers, motor control, sensor timing, etc.

Summary Table

Real-Time Use Cases

Top comments (0)