ES: Timers and Counters

Timers and counters are fundamental MCU peripherals that allow precise control of time, event counting, waveform generation, and system scheduling. Without them, there is no PWM, no RTOS tick, no baud-rate generation, and no time measurement.

What Is a Timer?

A timer is a hardware peripheral that increments (or decrements) a register based on a clock source.

It answers one simple question:

“How much time has passed?”

Basic Internal Structure

md
         +---------------------+
Clock -->|   Prescaler (PSC)   |----+
         +---------------------+    |
                                    v
                               +--------------+
                               | Counter (CNT)|----> Compare / Overflow
                               +--------------+
                                      |
                                      v
                               +--------------+
                               | Auto Reload  |
                               | Register ARR |
                               +--------------+

Main Components

  • Clock Source – Internal clock (AHB/APB) or external pin
  • Prescaler (PSC) – Divides clock frequency
  • Counter (CNT) – Increments or decrements
  • Auto Reload Register (ARR) – Defines overflow value
  • Capture/Compare Register (CCR) – Used for PWM or input capture
  • Interrupt generation logic

What Is a Counter?

A counter is a timer that increments based on external events, not time.

Instead of counting time, it counts pulses.

Example:

  • Counting encoder ticks
  • Counting button presses
  • Counting external signal frequency

md
External Pulse ----> [Counter Register] ---> Interrupt / Compare

So:

PeripheralIncrements From
TimerInternal clock
CounterExternal signal

Timer Operating Modes

Timers are not just “delay generators.” They operate in multiple modes.

Up Counter Mode

Counter increments from 0 → ARR.

CNT: 0 → 1 → 2 → 3 → ... → ARR → 0

Used for:

  • Periodic interrupts
  • Time base generation

Down Counter Mode

Counts from ARR → 0.

CNT: ARR → ... → 2 → 1 → 0

Used for:

  • Certain PWM modes
  • Advanced control timers

Up/Down (Center-Aligned)

0 → 1 → 2 → 3 → 2 → 1 → 0

Used in:

  • Motor control
  • Power electronics
  • Reducing EMI

Important for embedded security + safety systems where EMI matters.

Timer Time Calculation

To calculate the time from the timer.

md
Timer Frequency = Clock / (PSC + 1)

Overflow Time = (ARR + 1) / Timer Frequency

Example:

  • Clock = 72 MHz
  • PSC = 7199
  • ARR = 9999

md
Timer Frequency = 72MHz / 7200 = 10 kHz
Overflow Time = 10000 / 10000 Hz = 1 second

So this generates a 1-second interrupt.


Timer Interrupt Mechanism

When CNT reaches ARR:

  1. Overflow flag is set
  2. Interrupt request is generated
  3. NVIC handles interrupt
  4. ISR executes

md
        +--------+
        | Timer  |
        +--------+
             |
             v
      [Overflow Event]
             |
             v
        Interrupt Flag
             |
             v
            NVIC
             |
             v
        Timer ISR()

Example (Pseudo C)

cpp
void TIM2_IRQHandler(void)
{
    if (TIM2->SR & UIF)
    {
        TIM2->SR &= ~UIF;  // Clear flag
        toggle_led();
    }
}


Input Capture Mode

Used to measure:

  • Signal frequency
  • Pulse width
  • Period

When external signal edge occurs:

  • Current CNT value copied into CCRx register
  • Signal Edge ----> Capture ----> CCRx = CNT

Frequency Calculation:

Period = CCR2 - CCR1

Frequency = TimerClock / Period

This is how you measure frequency precisely in hardware.

Output Compare Mode

Timer compares CNT with CCR value.

When:

CNT == CCR

Action occurs:

  • Toggle pin
  • Set pin
  • Reset pin
  • Generate interrupt

Used for:

  • Precise waveform generation
  • Software scheduling

PWM Mode (Most Important in Practice)

PWM = Pulse Width Modulation

Used for:

  • Motor speed control
  • LED brightness
  • SMPS
  • Audio
  • DAC replacement

ARR = Period

CCR = Duty Cycle

Duty cycle:

Duty = 250 / 1000 = 25%

md
|■■■■□□□□□□|■■■■□□□□□□|

Where:

  • ■ = High
  • □ = Low

Watchdog Timer (Security & Safety)

A special timer that resets MCU if not refreshed.

md
Main Loop:
    feed_watchdog();

If firmware hangs:

Timer expires → MCU Reset

Critical for:

  • Automotive
  • Medical
  • Industrial

Security angle:

  • Protect against infinite loops
  • Protect against fault injection attacks