Timers and Counters

7 min read Last updated Fri Jun 12 2026 06:54:12 GMT+0000 (Coordinated Universal Time)

A timer/counter is a hardware register that increments on each clock edge: the system clock in timer mode, or an external signal in counter mode. It runs independently of the CPU and can trigger interrupts or drive output pins on specific count values.

Key Registers

  • Count register
    Holds the current counter value. Increments each clock (or prescaled clock) cycle.
  • Period / TOP register
    The value at which the counter resets to zero. Sets the timer’s overflow frequency.
  • Compare register
    When the count matches this value, the timer fires a compare-match event or toggles an output pin.
  • Control register
    Selects operating mode, clock source, prescaler value, and output behaviour.

Operating Modes

  • Normal mode
    Counter increments from 0 to MAX, overflows to 0, and fires an overflow interrupt. Used for simple periodic tasks.
  • CTC mode (Clear Timer on Compare)
    Counter resets to 0 when it matches the compare register. Fires a compare-match interrupt at a precise, configurable frequency. Used for task scheduling and waveform generation.
  • Fast PWM
    Counter counts from 0 to TOP. Output pin goes HIGH at 0 and LOW at compare match. Generates a PWM signal whose frequency is fclk/(P×(TOP+1))f_{clk} / (P \times (TOP+1)).
  • Phase-Correct PWM
    Counter counts up to TOP then back down to 0. Output toggles on compare match in both directions. Produces a symmetric PWM waveform with lower harmonic distortion; preferred for motor control.

Counter Mode

In counter mode the register increments on each rising (or falling) edge of an external signal rather than the system clock. Events are counted directly in hardware with no CPU involvement.

Applications:

  • Frequency measurement
    Count pulses over a fixed gate period TgateT_{gate}. Frequency f=N/Tgatef = N / T_{gate}.
  • Event counting
    Tally encoder pulses, flow-meter ticks, or product counts on a conveyor.
  • Rotational speed
    Count encoder edges per timer overflow to derive RPM.

Capture/Compare Module

A Capture/Compare (CC) module shares a timer with 1 or more channels. Each channel can be independently configured in capture or compare mode. On PIC MCUs the module is called CCP (Capture/Compare/PWM) and adds hardware PWM as a third mode.

Capture Mode

When a selected edge arrives on the capture input pin, the hardware instantly copies the current timer count into the capture register and sets a flag (optionally firing an interrupt). The CPU reads the latched timestamp at any point after.

Edge selection options:

  • Rising edge only
  • Falling edge only
  • Every edge (alternating)
    Captures both transitions of a pulse.
  • Every 4th rising edge
    PIC built-in 1:4 prescaler. Reduces capture rate for slower periodic signals.
  • Every 16th rising edge
    PIC built-in 1:16 prescaler.

Measurements derived from 2 successive captures t1t_1 and t2t_2:

Tpulse=(t2t1)×PfclkT_{pulse} = (t_2 - t_1) \times \frac{P}{f_{clk}}
  • PP: prescaler

If the timer overflows between captures, the overflow count must be added:

Tpulse=((t2t1)+Nov×(TOP+1))×PfclkT_{pulse} = \bigl((t_2 - t_1) + N_{ov} \times (TOP + 1)\bigr) \times \frac{P}{f_{clk}}

The timestamp is latched in hardware. No polling latency. The CPU can read the value any time before the next capture overwrites it.

Applications:

  • Pulse width
    Capture rising then falling edge. Subtract timestamps.
  • Period
    Capture 2 consecutive rising edges.
  • Frequency
    f=1/Tperiodf = 1 / T_{period}.
  • Duty cycle
    D=Tpulse/TperiodD = T_{pulse} / T_{period}. Requires 2 channels or both edges on 1 channel.
  • Distance measurement
    Capture pulse width from an ultrasonic sensor (HC-SR04). Convert count to distance via speed of sound.
  • Rotational speed
    Capture timestamp on each Hall-effect sensor pulse. Time between successive pulses gives RPM.
  • Event timestamp
    Log exact arrival time of RF or IR pulses with microsecond precision regardless of CPU activity.

Compare Mode

The timer continuously runs. When the counter value matches the compare register, the hardware performs a configurable output action immediately, with no software latency:

ActionEffect
SetOutput pin driven HIGH
ClearOutput pin driven LOW
ToggleOutput pin inverted
No outputInterrupt or DMA trigger only

After a compare match, software loads the next target value into the compare register to schedule the following event. Compare matches chain to produce arbitrary waveforms or precise periodic interrupts without blocking the CPU.

PIC compare modules include a Special Event Trigger output. On match, TMR1 resets and ADCON0.GO is set automatically, starting an ADC conversion at the exact clock cycle with no CPU code.

Applications:

  • Precise output pulse
    Load target count → pin asserts on match → reload with new target → pin deasserts. No jitter from software overhead.
  • Periodic ADC sampling
    Use Special Event Trigger. Every match resets TMR1 and starts an ADC conversion at a fixed interval.
  • Periodic interrupt
    Reload compare register inside the ISR. Creates a time base independent of main-loop timing.
  • Motor commutation
    Assert stator coil transitions at exact counter values. Software timing jitter causes torque ripple.

PWM is a special case. The timer resets at a period compare match. A second compare match controls the duty cycle transition. See Pulse Width Modulation.

CCP Mode (PIC)

PIC CCP modules combine capture, compare, and PWM in a single peripheral sharing Timer1 (16-bit) for capture/compare and Timer2 (8-bit) for PWM. Only 1 mode is active at a time, selected by the CCPxCON register.

In PWM mode the 10-bit duty cycle is split. Upper 8 bits go into CCPRxL. Lower 2 bits go into CCPxCON. Period is set by the Timer2 PR2 register:

fPWM=fclk4×P×(PR2+1)f_{PWM} = \frac{f_{clk}}{4 \times P \times (PR2 + 1)} Duty Cycle=(CCPRxL:CCPxCON5:4)4×(PR2+1)\text{Duty Cycle} = \frac{(CCPRxL : CCPxCON\langle5:4\rangle)}{4 \times (PR2 + 1)}

Prescaler

Sits between the clock source and the counter input. Divides the clock by a fixed ratio PP before the counter sees it:

ftick=fclkPf_{tick} = \frac{f_{clk}}{P}

Effect: slower count rate → longer maximum measurable period, lower time resolution per tick.

A 16-bit counter at 16 MHz with no prescaler overflows every 4 ms and has a 62.5 ns tick resolution. With P=64P = 64 it overflows every 256 ms at the cost of a 4 µs tick.

Prescaler values are usually powers of 2 (1, 2, 4, 8, …, 256) or specific ratios depending on the MCU family.

On PIC Timer0, the PSA (Prescaler Assignment) bit bypasses the prescaler entirely, routing the clock directly to the counter.

Postscaler

Sits after the timer’s period/compare event, before the interrupt or output signal is asserted. Divides the event output by a ratio QQ. The interrupt fires only every QQ-th overflow or compare match.

fevent=foverflowQ=fclkP×(TOP+1)×Qf_{event} = \frac{f_{overflow}}{Q} = \frac{f_{clk}}{P \times (TOP + 1) \times Q}

Effect: reduces interrupt rate without changing the counter’s tick resolution or period register value.

Useful when the required interrupt period is longer than the timer can reach with the prescaler alone, or when the timer period must remain fixed for PWM frequency while the interrupt rate is adjusted independently.

Not all MCU families include a postscaler. PIC microcontrollers expose a 4-bit postscaler on Timer0/Timer2 (1:1 to 1:16). AVR and most ARM Cortex-M timers omit it. The same effect is achieved in software by counting overflows in the ISR.

Prescaler vs Postscaler

Acts onEffect
PrescalerInput clock signalSlows how fast the counter increments
PostscalerCounter overflow outputReduces how often the overflow event fires

Both are frequency dividers. Combined, they configure the timer’s effective period across a wide range without changing the counter’s bit width.

Common Uses

  • Periodic interrupt generation (task scheduling, timeouts)
  • PWM output for motor speed, LED brightness, servo control
  • Pulse width and frequency measurement via input capture
  • Event counting in external clock mode
Was this helpful?