How do timers work in MCUs?

ampheoampheo
2 min read

Timers in microcontrollers (MCUs) are hardware peripherals that count clock pulses to measure time intervals or generate precise time-based events. They’re fundamental for tasks like delays, PWM generation, event counting, and real-time control.


How Timers Work

A timer counts up (or down) based on a clock source. When the counter reaches a specific value (overflow or match), it can trigger an interrupt or an output event.


🔧 Core Components of a Timer

  1. Counter Register

    • Stores the current count value.

    • Can be 8-bit, 16-bit, or 32-bit depending on the MCU.

  2. Prescaler

    • Divides the input clock to slow down counting (e.g., divide 16 MHz by 16 = 1 MHz).

    • Allows adjusting the time base.

  3. Auto-Reload or Compare Register

    • Sets the value at which the timer resets or triggers an interrupt.
  4. Interrupt Logic

    • Fires an interrupt when the counter overflows or matches a value.
  5. Control Registers

    • Configure mode (up/down count, one-shot, continuous), enable/disable, etc.

Common Timer Modes

ModeDescription
Basic TimerSimple counting, delay generation
Periodic TimerRepeats at fixed intervals (e.g., 1ms tick for RTOS)
PWM ModeGenerates Pulse Width Modulated signals
Input CaptureCaptures timer value on an external event (e.g., signal edge)
Output CompareTriggers an action when timer reaches a set value
Encoder InterfaceReads position data from rotary encoders (used in motor control)

Example: Delay Generation

Assume:

  • MCU clock = 16 MHz

  • Prescaler = 16000 → Timer ticks at 1 kHz (1 ms per tick)

  • Auto-reload = 1000 → Timer overflows every 1000 ms (1 second)

So the timer interrupt occurs once per second.


Use Cases

  • Delays & timeouts

  • PWM for motor control, LEDs

  • Capturing signal duration (ultrasonic sensors)

  • Scheduling tasks in RTOS

  • Frequency and pulse measurement

0
Subscribe to my newsletter

Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ampheo
ampheo