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
- Timer receives a clock input (e.g., 16 MHz).
- Prescaler divides it (e.g., by 16000 → 1 kHz).
- Counter starts from 0 and counts up to a set value (e.g., 999).
- 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");
}
}
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)