Microcontroller Timers and Counters

1. Definition and Core Concepts

Microcontroller Timers and Counters: Definition and Core Concepts

Fundamental Operation

Timers and counters in microcontrollers are hardware peripherals designed to measure or generate precise time intervals. A timer increments its value at a fixed frequency derived from the system clock or an external oscillator, while a counter increments upon detecting edges on an external signal. Both operate on the principle of a n-bit register that overflows after reaching its maximum value (2n - 1).

Mathematical Basis

The time resolution of a timer is determined by its input clock frequency (fclk) and prescaler (P):

$$ \Delta t = \frac{P}{f_{clk}} $$

For a 16-bit timer with fclk = 16 MHz and P = 8, the maximum measurable interval before overflow is:

$$ t_{max} = \frac{(2^{16} - 1) \times P}{f_{clk}} = \frac{65535 \times 8}{16 \times 10^6} \approx 32.77 \text{ ms} $$

Modes of Operation

Hardware Implementation

Modern microcontrollers integrate multiple timer units with:

Practical Applications

In motor control systems, timers generate precisely timed PWM signals with dead-band insertion. Counters in industrial automation precisely measure encoder pulses for position tracking, with typical resolutions down to 50 ns in 32-bit implementations.

Advanced Features

High-end timer peripherals support:

Timer Operation Timeline Timing diagram showing the relationship between clock frequency, prescaler, and timer overflow in a microcontroller. Time System Clock (f_clk) Prescaler (P) Δt = P/f_clk Timer Register Overflow Flag Overflow at 2ⁿ-1
Diagram Description: The diagram would show the relationship between clock frequency, prescaler, and timer overflow in a visual timeline format, clarifying how the mathematical values translate to physical behavior.

1.2 Differences Between Timers and Counters

Fundamental Operational Modes

Timers and counters in microcontrollers both rely on incrementing a register, but their triggering mechanisms differ fundamentally. A timer increments its value at a fixed frequency derived from the microcontroller's clock signal, making it a function of time. For example, a 16-bit timer with a 1 MHz clock increments every 1 µs, overflowing after 65.536 ms. The relationship between clock frequency (fclk) and timer resolution (Δt) is:

$$ \Delta t = \frac{1}{f_{clk}} $$

In contrast, a counter increments only upon receiving an external pulse at a dedicated input pin, independent of the system clock. This makes it suitable for event-driven applications like measuring RPM or counting objects on a conveyor belt.

Clock Source and Signal Dependency

Timers are synchronized with the internal clock, which may be prescaled to adjust resolution. For instance, an 8 MHz clock with a prescaler of 8 yields an effective timer clock of 1 MHz. The prescaler value (N) modifies the timer increment rate:

$$ f_{timer} = \frac{f_{clk}}{N} $$

Counters, however, operate asynchronously, responding to edges (rising or falling) of an external signal. This introduces considerations for signal debouncing and noise immunity, often requiring hardware or software filtering.

Applications and Practical Use Cases

Hardware Implementation

Timer peripherals often include auxiliary features like:

Counters typically lack these features but may support gate control, where an enable signal validates external pulses.

Mathematical Modeling

The maximum countable time (Tmax) for an n-bit timer is:

$$ T_{max} = \frac{2^n}{f_{timer}} $$

For a counter, the maximum count (Cmax) is simply:

$$ C_{max} = 2^n - 1 $$

Overflow handling differs: timers often trigger interrupts, while counters may latch values or generate hardware events.

Edge Cases and Error Sources

Timers suffer from jitter due to clock drift or interrupt latency, while counters face missed pulses from signal glitches. Advanced microcontrollers mitigate these with:

Timer vs Counter Signal Flow A block diagram comparing the clock signal flow for timers versus external pulse triggering for counters in a microcontroller. Timer vs Counter Signal Flow Timer Microcontroller Clock (f_clk) Prescaler Timer Register Counter Microcontroller External Input Pin Counter Register External Pulse Legend Timer Clock Flow Counter Pulse Flow
Diagram Description: The diagram would show the clock signal flow for timers versus external pulse triggering for counters, highlighting their operational differences.

1.3 Common Applications in Embedded Systems

Precision Timing and Event Scheduling

Microcontroller timers are fundamental in generating precise time delays and scheduling real-time tasks. A timer configured in interval mode generates periodic interrupts, enabling deterministic execution of time-critical functions. The interrupt period T is derived from the timer clock frequency ftimer and the prescaler N:

$$ T = \frac{N \cdot (1 + \text{TOP})}{f_{\text{timer}}} $$

where TOP is the timer's maximum count value (e.g., 0xFFFF for a 16-bit timer). Applications include:

Pulse-Width Modulation (PWM) Generation

Timers with PWM output modes drive motors, LEDs, and power converters by varying duty cycle D:

$$ D = \frac{\text{CCR}}{\text{ARR}} \times 100\% $$

where CCR is the capture/compare register value and ARR is the auto-reload register. Key implementations:

Frequency Measurement and Encoder Interfaces

Timer input capture modes measure external signal frequency fext by recording timestamps of edges:

$$ f_{\text{ext}} = \frac{f_{\text{timer}}}{(\text{CCR}_2 - \text{CCR}_1)} $$

Quadrature encoder interfaces use dual-edge detection to track position/speed in robotic systems. Advanced features include:

Waveform Generation and Signal Processing

Timers synchronize with DACs to produce arbitrary waveforms through direct memory access (DMA)-based buffer updates. The output frequency resolution is:

$$ \Delta f = \frac{f_{\text{timer}}}{2^n} $$

where n is the timer resolution. Applications include:

Time-Stamping and Data Logging

High-resolution timers (e.g., 32-bit @ 100MHz) provide µs-level timestamping for:

CCR1 CCR2 Timer Compare Output Waveform
Timer Modes and Waveforms Waveform diagrams illustrating PWM, input capture, interval mode, and DAC synchronization with annotated timing parameters. Time Amplitude PWM Generation 0 CCR CCR ARR D = CCR/ARR Input Capture T1 T2 Δf = 1/(T2-T1) Edges Interval Mode 0 TOP TOP ARR f_timer = 1/TOP DAC Synchronization T1 T2 T3 T4 Timer Triggers
Diagram Description: The section includes multiple mathematical relationships and time-domain behaviors (PWM generation, frequency measurement, waveform generation) that benefit from visual representation of waveforms and timing diagrams.

2. Timer Modes: Input Capture, Output Compare, PWM

Timer Modes: Input Capture, Output Compare, PWM

Input Capture Mode

Input capture mode records the exact time at which an external event occurs, typically using a dedicated timer input pin. When a signal edge (rising or falling) is detected, the current timer value is latched into a capture register, allowing precise timestamping. The time difference between two events can be computed as:

$$ \Delta t = (T_{capture2} - T_{capture1}) \times T_{clock} $$

where Tcapture is the captured timer value and Tclock is the timer clock period. This mode is essential for frequency measurement, pulse-width analysis, and rotary encoder decoding.

Output Compare Mode

Output compare mode triggers actions (e.g., pin toggling, interrupt generation) when the timer counter matches a predefined value stored in a compare register. The compare register OCR determines the timing:

$$ t_{action} = OCR \times T_{clock} $$

Applications include waveform generation, time-delay creation, and synchronized signal control. Advanced microcontrollers allow concatenated timers for extended resolution.

Pulse-Width Modulation (PWM) Mode

PWM generates variable-duty-cycle signals by periodically resetting the timer counter at a top value (TOP) and toggling outputs at compare matches. The duty cycle D is:

$$ D = \frac{OCR}{TOP} \times 100\% $$

Key parameters include PWM frequency (fPWM = fclock/(TOP + 1)) and resolution (bits = log2(TOP + 1)). High-resolution PWM is critical for motor control, LED dimming, and power converters.

PWM Generation Techniques

Hardware Considerations

Timer peripherals often feature:

OCR TOP
Timer Modes Waveform Comparison Time-domain waveform diagram comparing input capture, output compare, and PWM modes with synchronized axes. Time Time Time Input Counter PWM Rising edge Falling edge Rising edge Falling edge T_capture1 T_capture2 TOP OCR Duty cycle % Input Capture Timer Counter PWM Output
Diagram Description: The section describes time-domain behaviors (input capture, output compare, PWM) and waveform relationships that are inherently visual.

2.2 Clock Sources and Prescalers

Clock Sources in Microcontroller Timers

Microcontroller timers rely on clock signals to increment their counters. The clock source determines the timer's resolution and accuracy. Common clock sources include:

Prescalers and Frequency Division

A prescaler divides the input clock frequency before it reaches the timer counter, enabling longer timing intervals. The division factor (N) is typically a power of two (e.g., 1, 2, 4, ..., 256). The effective timer clock frequency (ftimer) is given by:

$$ f_{timer} = \frac{f_{clock}}{N} $$

For example, a 16 MHz clock with a prescaler of 64 yields a timer frequency of 250 kHz. The timer resolution (Δt) then becomes:

$$ \Delta t = \frac{1}{f_{timer}} = \frac{N}{f_{clock}} $$

Trade-offs in Prescaler Selection

Choosing an appropriate prescaler involves balancing resolution and maximum interval:

For a 16-bit timer with a 16 MHz clock and prescaler of 8, the maximum interval before overflow is:

$$ T_{max} = \frac{2^{16} \times 8}{16 \times 10^6} = 32.768 \text{ ms} $$

Dynamic Prescaler Adjustment

Some microcontrollers allow runtime prescaler modification, enabling adaptive timing resolution. However, this may introduce glitches if not synchronized properly. Techniques like double buffering ensure smooth transitions.

Clock Synchronization and Jitter

Asynchronous clock sources (e.g., external signals) require synchronization to the microcontroller's internal clock domain, introducing latency (±1–2 clock cycles). High-frequency jitter can degrade timing accuracy, particularly in precision applications like PWM generation.

Practical Considerations

Timer Clock Path and Prescaler Operation Block diagram showing clock signal flow from sources through prescaler to timer, with frequency division and synchronization paths. Internal Clock f_clock External Clock PLL Multiplier: M MUX Prescaler Division: N f_clock Sync Logic latency: 2 cycles Timer f_timer = f_clock/N
Diagram Description: A diagram would visually show the clock signal flow from sources to the prescaler and timer, illustrating frequency division and synchronization paths.

2.3 Timer Interrupts and Event Generation

Timer interrupts enable microcontrollers to execute time-critical tasks without continuous polling. When a timer reaches a predefined value (e.g., overflow or compare match), it triggers an interrupt request (IRQ), diverting the CPU to an interrupt service routine (ISR). The latency between interrupt assertion and ISR execution depends on the microcontroller's interrupt controller architecture and current instruction pipeline state.

Interrupt Latency and Jitter

Interrupt latency (tlatency) comprises three components:

$$ t_{latency} = t_{sync} + t_{exec} + t_{isr\_prologue} $$

Jitter (Δt) arises from variations in texec and is minimized by:

Event Generation Without CPU Intervention

Advanced timer peripherals (e.g., STM32's TIM, AVR's TC1) support hardware-triggered events via:

Timer Counter (TCNT) Compare Match (CCR) Output Toggle GPIO/ADC Trigger

Practical Implementation: PWM Generation

For a 16-bit timer (e.g., TCA0 in ATmega4809), PWM frequency (fPWM) and duty cycle (D) are set via:

$$ f_{PWM} = \frac{f_{CLK}}{N \cdot (TOP + 1)} $$ $$ D = \frac{CCR}{TOP + 1} \times 100\% $$

where N is the prescaler (1, 2, 4, ..., 1024), and TOP is the counter's maximum value (e.g., 0xFFFF). An interrupt can be generated at the TOP or BOTTOM for synchronization.


// Configure PWM on ATmega4809 with 20% duty cycle
TCA0.SINGLE.CTRLA = TCA_SINGLE_CLKSEL_DIV16_gc | TCA_SINGLE_ENABLE_bm;
TCA0.SINGLE.PER = 9999;  // TOP value for 1kHz @ 16MHz/16
TCA0.SINGLE.CMP0 = 2000; // 20% duty cycle
TCA0.SINGLE.INTCTRL = TCA_SINGLE_OVF_bm; // Enable overflow interrupt
   

Real-World Considerations

Timer Interrupt Latency Components and Event Generation Timing diagram showing interrupt signal propagation through synchronization flip-flops, CPU pipeline, ISR prologue, and hardware events like output compare and GPIO trigger. Timer Interrupt Latency Components Hardware Event Generation Interrupt Signal Sync FF t_sync CPU t_exec ISR t_isr_prologue Output Compare GPIO Toggle ADC Trigger TCNT CCR Legend Synchronization CPU Pipeline ISR Prologue
Diagram Description: The section describes timer interrupt latency components and hardware-triggered events, which involve sequential timing relationships and signal flows that are best visualized.

3. Event Counting and Frequency Measurement

3.1 Event Counting and Frequency Measurement

Microcontroller timers configured as counters operate by incrementing their register values in response to external signal edges. The counting mechanism relies on transitions detected on a designated input pin, typically synchronized with the microcontroller's clock domain to avoid metastability. Edge sensitivity—whether rising, falling, or both—is programmable in most modern architectures, allowing precise control over what constitutes a countable event.

Event Counting Modes

In edge-counting mode, the timer increments its count register (TCNTn) on each qualifying edge of an external signal. The maximum countable frequency is constrained by the synchronization logic and is generally half the timer's input clock frequency (Nyquist criterion). For a 16 MHz timer clock, this limits event counting to approximately 8 MHz without prescaling. The relationship between the input signal frequency (fin) and the timer resolution is given by:

$$ f_{max} = \frac{f_{timer}}{2} $$

Higher frequencies require prescaling the input signal or using hardware capture units with dedicated signal conditioning circuits.

Frequency Measurement Techniques

Two primary methods exist for frequency measurement:

$$ f_{in} = \frac{f_{timer}}{N} $$
$$ f_{in} = \frac{N_{ref} \cdot f_{ref}}{N_{unknown}} $$

Reciprocal counting offers superior accuracy for low-frequency signals, while direct period measurement excels at higher frequencies.

Error Sources and Mitigation

Quantization error arises from the discrete nature of timer clocks, introducing a ±1 count uncertainty. For a timer running at frequency ftimer, the worst-case relative error in period measurement is:

$$ \epsilon = \pm \frac{1}{N} = \pm \frac{f_{in}}{f_{timer}} $$

Synchronization delays between asynchronous input signals and the timer clock domain introduce additional phase uncertainty. Advanced microcontrollers mitigate this through:

Practical Implementation

Modern microcontrollers like ARM Cortex-M devices implement combined timer/counter peripherals with hardware capture/compare units. For example, the STM32 series allows simultaneous capture of timer values on both rising and falling edges, enabling pulse-width measurement without software intervention. The capture process triggers DMA transfers in high-performance applications, achieving measurement rates exceeding 10 MHz with sub-nanosecond resolution.

Timer Count: 1 2 3 4 5

High-precision applications often employ time-to-digital converters (TDCs) integrated into modern microcontrollers, which use delay-line interpolation to achieve picosecond-level resolution. These circuits measure the phase difference between the event signal and the nearest clock edge, effectively subdividing the timer clock period.

3.2 Pulse Width Measurement

Pulse width measurement is a fundamental operation in microcontroller-based systems, enabling precise time-domain analysis of digital signals. The technique involves determining the duration of a pulse, defined as the time interval between its rising and falling edges (or vice versa). Microcontroller timers, configured in capture or input capture mode, are typically employed for this purpose.

Timer Capture Mode

When a timer is set to capture mode, it records the current counter value upon detecting a specified edge transition (rising or falling) on an input pin. The difference between two consecutive captures yields the pulse width. For instance, if the timer captures a value T1 at a rising edge and T2 at the subsequent falling edge, the pulse width PW is:

$$ PW = (T_2 - T_1) \cdot t_{clk} $$

where tclk is the timer clock period. High-resolution measurements require a fast timer clock or prescaler optimization.

Input Capture Units

Advanced microcontrollers feature dedicated input capture units (ICUs) that automate edge detection and timestamp recording. These units often include noise filters and programmable edge polarity selection. The ICU triggers an interrupt or DMA transfer upon capture, minimizing CPU overhead in real-time systems.

Measurement Resolution and Error Sources

The quantization error in pulse width measurement is bounded by:

$$ \Delta t = \pm t_{clk} $$

Additional error sources include:

Dual-Slope Measurement Technique

For improved accuracy in noisy environments, some systems employ a dual-slope approach where the timer measures both the high and low periods of a periodic signal. The pulse width PW and period T are derived from:

$$ PW = \frac{N_{high}}{N_{high} + N_{low}} \cdot T $$

where Nhigh and Nlow are the timer counts during the high and low phases, respectively. This method averages out high-frequency jitter.

Applications

Hardware Considerations

Modern microcontrollers integrate specialized peripherals for pulse width measurement:

Pulse Width Measurement with Timer Capture Waveform diagram showing pulse width measurement using timer capture, with input signal, timer counter values, and labeled edges. T1 (Rising Edge) T2 (Falling Edge) T1 (Rising Edge) Timer = 0 Timer = N Timer = 0 PW = Pulse Width t_clk (Clock Period) Input Signal Timer Counter Value Amplitude Time
Diagram Description: The section involves time-domain behavior of pulse width measurement and edge detection, which is highly visual.

3.3 External Triggering and Gate Control

Principles of External Triggering

External triggering allows a microcontroller timer to synchronize its counting operation with an external signal rather than relying solely on its internal clock. The trigger signal, typically a rising or falling edge, initiates or resets the timer's count sequence. This mechanism is crucial in applications requiring precise event synchronization, such as pulse-width modulation (PWM) generation, frequency measurement, or time-stamping external events.

The triggering condition is often configurable through control registers. For instance, the Timer Control Register (TCR) in many ARM Cortex-M microcontrollers provides bits to select between:

$$ t_{response} = t_{prop} + \frac{1}{f_{clk}} $$

Where tresponse is the delay between trigger and timer start, tprop is the signal propagation delay through input synchronization circuits, and fclk is the timer's clock frequency.

Gate Control Operation

Gate control extends external triggering by using an additional signal to enable or disable the counting process. When the gate signal is active (typically high), the timer increments on each clock cycle; when inactive, counting pauses regardless of clock activity. This creates a windowed counting operation useful for:

The gate control logic can be modeled as:

$$ Count_{enable} = Gate \land (Trigger \lor FreeRun) $$

Where FreeRun represents the timer's normal operation mode without external triggering.

Hardware Implementation

Modern microcontrollers implement external triggering and gate control through dedicated input capture pins with configurable digital filters. The signal path typically includes:

  1. Input buffer with Schmitt trigger characteristics
  2. Programmable digital noise filter (4-16 clock cycles)
  3. Synchronization flip-flops (2-3 stages) to prevent metastability
  4. Edge detection logic feeding into the timer control unit

The synchronization process introduces a deterministic latency that must be accounted for in precision applications:

$$ t_{sync} = N_{sync} \times T_{clk} $$

Where Nsync is the number of synchronization stages (typically 2-3) and Tclk is the system clock period.

Practical Applications

In motor control systems, external triggering synchronizes PWM generation with rotor position sensors. The timer begins counting when a hall sensor triggers, ensuring precise commutation timing. Gate control prevents false triggering from electrical noise during inactive periods.

High-energy physics experiments use these features to timestamp particle detector events. A leading-edge trigger initiates the timer, while a trailing-edge gate signal defines the measurement window, rejecting afterpulses and noise.

Configuration Example

For an STM32 microcontroller, setting up external triggering with gate control involves:


// Configure Timer 2 for external trigger with gate control
TIM2->SMCR |= TIM_SMCR_TS_2 | TIM_SMCR_TS_0;  // Trigger on TI2FP2
TIM2->SMCR |= TIM_SMCR_SMS_2;                 // Gate mode
TIM2->CCMR1 |= TIM_CCMR1_CC2S_0;              // CC2 as input
TIM2->CCER |= TIM_CCER_CC2E;                  // Enable CC2
TIM2->CR1 |= TIM_CR1_CEN;                     // Enable timer
    

Timing Constraints

The maximum trigger frequency is limited by the timer's synchronization and processing logic:

$$ f_{trigger_{max}} = \frac{f_{timer}}{N_{sync} + N_{filter} + 2} $$

Where Nfilter is the configured filter length in clock cycles. For a 100 MHz timer with 3 synchronization stages and 4-cycle filtering, the maximum reliable trigger frequency is approximately 11.1 MHz.

External Trigger and Gate Control Timing Diagram Timing diagram showing the relationship between trigger signal, gate signal, timer enable, clock pulses, and count sequence with annotated transitions. Time Signal Trigger Gate Timer Enable Clock Count Rising Edge Falling Edge Gate Active Gate Active Count Enable 0 1 2 3 2 1 Propagation Delay
Diagram Description: The section describes signal timing relationships and hardware signal paths that would be clearer with visual representation.

4. Configuring Timers in Popular Microcontrollers (AVR, ARM, PIC)

Configuring Timers in Popular Microcontrollers (AVR, ARM, PIC)

AVR Timer Configuration

AVR microcontrollers, such as the ATmega328P, feature 8-bit and 16-bit timers with multiple operating modes. The Timer/Counter Control Registers (TCCRx) configure prescaler values, waveform generation modes, and interrupt enable bits. For a timer operating in CTC (Clear Timer on Compare Match) mode, the output compare register (OCRx) determines the period according to:

$$ f_{timer} = \frac{f_{clk}}{N(1 + OCRx)} $$

where fclk is the system clock frequency and N is the prescaler value (1, 8, 64, 256, or 1024). To generate a 1 kHz signal with a 16 MHz clock and prescaler of 64:


// Configure Timer1 for CTC mode
TCCR1A = 0;
TCCR1B = (1 << WGM12) | (1 << CS11) | (1 << CS10); // Prescaler 64
OCR1A = 249; // 16000000 / (64 * 1000) - 1
TIMSK1 = (1 << OCIE1A); // Enable compare match interrupt
    

ARM Cortex-M Timers

ARM Cortex-M processors utilize the SysTick timer and General-Purpose Timers (TIMx). The SysTick timer, integrated into the NVIC, is commonly used for real-time operating systems. For a 16-bit TIMx timer in PWM mode, the auto-reload register (ARR) and prescaler (PSC) set the period:

$$ PWM_{period} = \frac{(ARR + 1)(PSC + 1)}{f_{timer}} $$

To configure TIM2 for a 1 kHz PWM output with a 72 MHz clock:


// Enable TIM2 clock
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;

// Configure TIM2 for PWM mode 1
TIM2->PSC = 71; // Prescaler = 72 - 1
TIM2->ARR = 999; // Auto-reload value for 1 kHz
TIM2->CCMR1 |= TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1; // PWM mode 1
TIM2->CCER |= TIM_CCER_CC1E; // Enable output
TIM2->CR1 |= TIM_CR1_CEN; // Start timer
    

PIC Microcontroller Timers

PIC microcontrollers use the TMRx module with configurable prescalers and postscalers. The timer period is calculated as:

$$ T_{timer} = \frac{4 \times T_{osc} \times Prescaler \times (TMRx + 1)}{F_{osc}} $$

where Tosc is the oscillator period. For a PIC16F877A generating a 100 ms delay with a 4 MHz crystal and prescaler of 256:


// Configure Timer1
T1CON = 0x31; // Prescaler 1:8, Timer1 ON
TMR1H = 0x0B; // High byte for 3036 counts
TMR1L = 0xDC; // Low byte
TMR1IF = 0; // Clear interrupt flag
TMR1IE = 1; // Enable Timer1 interrupt
    

Practical Considerations

4.2 Example: Generating Precise Delays

Fundamentals of Timer-Based Delay Generation

Precise timing is critical in embedded systems for tasks such as sensor polling, PWM generation, and communication protocols. Microcontroller timers, when configured in timer mode, increment their counter register at a fixed rate derived from the system clock or an external source. The delay duration Tdelay is determined by:

$$ T_{delay} = N \cdot T_{clock} $$

where N is the number of clock cycles and Tclock is the period of the timer clock. For a 16-bit timer (e.g., Timer1 in ATmega328P), the maximum countable value is 65,535 (216 - 1). Beyond this, overflow interrupts must be used to extend the delay range.

Configuring Timer Registers for Delay Calculation

The required timer count value N for a desired delay Tdelay is calculated as:

$$ N = \frac{T_{delay}}{T_{clock}} = T_{delay} \cdot f_{clock} $$

where fclock is the timer clock frequency. In practice, the prescaler value P divides the system clock fCPU to produce fclock:

$$ f_{clock} = \frac{f_{CPU}}{P} $$

Common prescaler values are 1, 8, 64, 256, and 1024. The optimal prescaler minimizes quantization error while avoiding timer overflow.

Practical Implementation on AVR Microcontrollers

The following steps outline delay generation using an AVR timer in CTC (Clear Timer on Compare Match) mode:

  1. Select timer clock source and prescaler by configuring TCCR1B.
  2. Calculate and set the compare match value OCR1A = N - 1.
  3. Enable compare match interrupt by setting OCIE1A in TIMSK1.
  4. Start the timer by writing to TCCR1B.
  5. Implement the ISR to handle the elapsed delay.

// Generate 100ms delay on ATmega328P (16MHz clock)
#include <avr/io.h>
#include <avr/interrupt.h>

void timer1_init() {
    TCCR1A = 0;                     // Normal port operation
    TCCR1B = (1 << WGM12);          // CTC mode
    OCR1A = 15624;                  // 100ms at 16MHz/1024 prescaler
    TIMSK1 = (1 << OCIE1A);         // Enable compare match interrupt
    TCCR1B |= (1 << CS12) | (1 << CS10); // Start with 1024 prescaler
}

ISR(TIMER1_COMPA_vect) {
    // Delay complete - handle event here
}
    

Error Analysis and Optimization

The quantization error ε arises from integer truncation of N:

$$ ε = T_{delay} - \left\lfloor \frac{T_{delay} \cdot f_{CPU}}{P} \right\rfloor \cdot \frac{P}{f_{CPU}} $$

For sub-microsecond precision, consider:

Advanced Techniques: Phase-Correct PWM for Fine Resolution

When sub-clock-cycle resolution is required, phase-correct PWM can generate delays with finer granularity. By varying the duty cycle at high frequency (e.g., 1MHz PWM), the effective delay resolution improves through averaging:

$$ Δt_{res} = \frac{T_{PWM}}{256} $$

where TPWM is the PWM period and 256 represents 8-bit resolution. This technique is particularly useful in laser ranging and time-of-flight applications where picosecond resolution may be required.

Timer Delay Generation Timing Diagram A timing diagram showing the relationship between system clock, prescaler output, timer counter, compare match signal, and interrupt flag in a microcontroller timer delay generation scenario. Time Signals System Clock Prescaler (P) Timer Counter Compare Match Interrupt (OCF1A) f_CPU T_clock P N OCR1A OCF1A T_clock Compare Match
Diagram Description: The section involves time-domain behavior and clock signal relationships that are easier to visualize than describe textually.

4.3 Example: Measuring Sensor Input Frequency

Fundamental Principles

Frequency measurement using microcontroller timers relies on capturing the number of signal edges (rising or falling) within a known time interval. For a periodic sensor signal with frequency f, the timer counts N edges over a gate time Tgate, yielding:

$$ f = \frac{N}{T_{\text{gate}}} $$

Timer peripherals in microcontrollers (e.g., STM32, AVR, or PIC) typically operate in input capture mode or counter mode, synchronized with an internal or external clock source.

Hardware Configuration

For a sensor outputting a square wave (e.g., an optical encoder or Hall-effect sensor):

Mathematical Derivation

Assume a timer clock frequency fclk and prescaler value P. The timer resolution Δt is:

$$ \Delta t = \frac{P}{f_{\text{clk}}} $$

For N captured edges over M timer ticks, the input frequency becomes:

$$ f_{\text{in}} = \frac{N \cdot f_{\text{clk}}}{M \cdot P} $$

Practical Implementation

An STM32 example using HAL libraries:

// Configure Timer 2 in input capture mode
TIM_HandleTypeDef htim2;
TIM_IC_InitTypeDef sConfigIC;

htim2.Instance = TIM2;
htim2.Init.Prescaler = 15; // Prescaler P=16 (15+1)
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 0xFFFF; // Max timer period
HAL_TIM_IC_Init(&htim2);

sConfigIC.ICPolarity = TIM_ICPOLARITY_RISING;
sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
sConfigIC.ICFilter = 0;
HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1);

// Start input capture
HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1);

Error Analysis

Frequency measurement accuracy depends on:

Advanced Techniques

For high-precision measurements:

Timer Input Capture Waveform and Counting A waveform diagram showing sensor input signal, timer clock ticks, captured edges, and gate time interval. Time Sensor Input Rising Edge T_gate N = 3 edges Time Timer Clock (f_clk) Timer Counter Value Δt = T_gate × f_clk
Diagram Description: The section involves time-domain behavior of signal edges and timer interactions, which are inherently visual.

5. Timer/Counter Chaining for Extended Range

5.1 Timer/Counter Chaining for Extended Range

Microcontroller timers and counters are typically constrained by their register bit-width, limiting their maximum count value. For instance, an 8-bit timer overflows at 255, while a 16-bit timer reaches 65,535. Many applications—such as long-duration event logging, high-precision frequency measurement, or motor control with extended pulse-width modulation (PWM) periods—require counting beyond these limits. Timer/counter chaining provides a solution by cascading multiple timers to achieve a combined effective bit-width.

Hardware and Software Chaining Methods

Chaining can be implemented in two primary ways:

Mathematical Derivation of Extended Range

When two n-bit timers are chained, the combined count range becomes:

$$ N_{total} = (2^n) \times (2^n) = 2^{2n} $$

For example, two 8-bit timers yield a 16-bit range (65,536), while two 16-bit timers produce a 32-bit range (4,294,967,296). The effective resolution R in seconds, given a clock frequency fclk, is:

$$ R = \frac{1}{f_{clk}} $$

The maximum measurable time interval Tmax becomes:

$$ T_{max} = \frac{2^{2n}}{f_{clk}} $$

Practical Implementation Considerations

Chaining introduces trade-offs between resolution and latency:

Case Study: AVR Timer Chaining

On ATmega microcontrollers, Timer1 (16-bit) can be chained with Timer2 (8-bit) by configuring Timer1’s overflow to trigger Timer2’s clock. The following assembly snippet demonstrates initialization:


; Configure Timer1 for normal mode, overflow interrupt
ldi r16, (1<

This extends the effective range to 24 bits (16 + 8), allowing measurement intervals up to 1.06 seconds at 16 MHz with minimal software overhead.

Applications in High-Precision Systems

Extended-range timers enable:

  • Ultrasonic Rangefinders: Measuring echo times beyond 65 ms (unachievable with standalone 16-bit timers at common clock frequencies).
  • Energy Metering: Integrating pulse counts over hours or days without frequent CPU wake-ups.
  • Astronomical Event Logging: Timestamping celestial events with sub-millisecond precision over multi-day observations.

Modern microcontrollers like the STM32 series offer dedicated chaining logic in their advanced timer peripherals (e.g., TIM1 and TIM8 in master-slave configuration), reducing jitter to sub-nanosecond levels.

Timer/Counter Chaining Methods A block diagram showing hardware and software chaining methods between two timers (Timer1 and Timer2), including overflow signal paths and interrupt service routine (ISR) connections to the CPU. Timer1 Timer2 CPU ISR Overflow Hardware Chaining Software Chaining
Diagram Description: The diagram would show the hardware and software chaining methods with signal flow between timers and interrupt paths.

5.2 Low-Power Timer Operation

Low-power timers are critical in battery-operated and energy-constrained systems, where minimizing current consumption without sacrificing timing accuracy is paramount. These timers leverage specialized clock sources, reduced voltage operation, and selective peripheral activation to achieve microampere or even nanoampere current draw.

Clock Source Selection

The choice of clock source significantly impacts power consumption. High-frequency clocks like the main system oscillator (8–48 MHz) consume milliamperes, whereas low-power internal RC oscillators (32.768 kHz or 128 kHz) draw microamperes. The relationship between clock frequency (f) and dynamic power (Pdyn) is given by:

$$ P_{dyn} = C V^2 f $$

where C is the switching capacitance and V is the supply voltage. Reducing f by a factor of 1000 (e.g., from 16 MHz to 16 kHz) theoretically lowers dynamic power by the same factor.

Prescaler Optimization

When using a high-frequency source, prescalers divide the clock to reduce power. However, each division stage introduces additional propagation delay and leakage current. The optimal prescaler value (Nopt) balances resolution and power:

$$ N_{opt} = \sqrt{\frac{f_{source} \cdot t_{prop}}{k \cdot V_{DD}}} $$

where tprop is the gate delay, k is a process-dependent constant, and VDD is the supply voltage. Modern microcontrollers like the STM32L4 series implement dynamic prescaler switching, automatically adjusting N based on the required timer resolution.

Sleep Mode Integration

Low-power timers often operate in conjunction with sleep modes:

  • Active Mode: Timer runs at full speed (e.g., during sensor sampling)
  • Low-Power Sleep: Timer switches to a 32 kHz oscillator, waking the CPU only on overflow events
  • Stop Mode: Timer retains state in static RAM, drawing only leakage current (typically < 1 µA)

The wake-up latency (twake) must be accounted for in real-time systems:

$$ t_{wake} = t_{osc\_stable} + t_{PLL\_lock} + t_{context\_restore} $$

Peripheral Clock Gating

Advanced microcontrollers implement clock gating at the peripheral level. For example, the MSP430's LFXT1 clock can be exclusively routed to Timer_A while other peripherals remain unclocked. This reduces capacitive loading on the clock tree, decreasing power by 15–30% compared to global clock distribution.

Voltage Scaling Effects

Operating at reduced voltages (e.g., 1.8V instead of 3.3V) quadratically reduces dynamic power but increases timing uncertainty due to threshold voltage variations. The timing error (Δt) scales as:

$$ \frac{\Delta t}{t} \propto \frac{V_{th}}{V_{DD} - V_{th}} $$

where Vth is the transistor threshold voltage. Techniques like body biasing and compensated delay lines mitigate this effect in ultra-low-voltage timers (0.9–1.2V operation).

Real-World Implementation: RTC Subsystems

Dedicated real-time clock (RTC) modules exemplify optimized low-power timer design. The NXP Kinetis L series RTC consumes 450 nA at 3V while maintaining ±2 ppm accuracy through:

  • Dual oscillators (high-speed for calibration, low-speed for operation)
  • Automatic compensation of crystal drift
  • Asynchronous prescaler chain with glitch-free switching

For applications requiring both precision and low power, temperature-compensated crystal oscillators (TCXOs) paired with duty-cycled timers achieve < 1 µA average current while maintaining ±5 ppm stability from -40°C to 85°C.

Low-Power Timer Architecture and Modes Block diagram showing clock sources, prescaler, timer core, and sleep mode logic in a low-power microcontroller timer system. Clock Sources f_source Prescaler N_opt Timer Core Sleep Mode Logic Power Domains Active Sleep t_wake Stop V_DD Legend: Clock Path Control Path Power Domain
Diagram Description: The section involves multiple interacting concepts (clock sources, prescalers, sleep modes) that would benefit from a visual representation of their relationships and timing behaviors.

5.3 Debugging Common Timer/Counter Issues

Clock Source and Prescaler Misconfiguration

One of the most frequent issues in timer/counter operation stems from incorrect clock source selection or prescaler configuration. The timer's counting rate is given by:

$$ f_{timer} = \frac{f_{system}}{(prescaler + 1) \times (compare\_match + 1)} $$

where fsystem is the microcontroller's main clock frequency. A common mistake is forgetting that prescaler values are often zero-indexed, meaning a register value of 0 actually corresponds to a division factor of 1. This leads to timers running at unexpected speeds.

Overflow and Interrupt Race Conditions

When using timer overflow interrupts, a critical window exists between the overflow event and the interrupt service routine (ISR) execution. If the timer continues counting during this period, the ISR may read an incorrect value. The probability of this occurring increases with:

  • Higher clock frequencies
  • Longer ISR latency
  • Shorter timer periods

To mitigate this, always read the timer value immediately upon entering the ISR before performing any other operations.

Input Capture Glitches

Input capture modules used for frequency measurement or pulse timing are susceptible to noise-induced glitches. The false trigger probability Pglitch can be modeled as:

$$ P_{glitch} = 1 - e^{-\lambda t_{meas}} $$

where λ is the noise event rate and tmeas is the measurement duration. Hardware solutions include implementing a Schmitt trigger input or using a digital filter in the capture module if available.

PWM Output Dead-Time Issues

When generating complementary PWM signals for motor control or power electronics, improper dead-time configuration can cause shoot-through currents. The minimum dead time tdead must satisfy:

$$ t_{dead} > t_{rise} + t_{fall} + t_{prop} $$

where trise and tfall are the power device switching times, and tprop accounts for signal propagation delays. Many modern microcontrollers include programmable dead-time generators, but their resolution limitations must be considered.

Timer Peripheral Conflicts

Advanced microcontrollers often share timer resources between multiple functions. For example, a single timer might be used for:

  • PWM generation
  • Input capture
  • Output compare
  • Time-base generation

These competing uses can lead to unexpected behavior when modes are changed dynamically. Always verify that all relevant control registers are properly configured when repurposing a timer peripheral.

Counter Register Corruption

On some architectures, reading multi-byte timer/counter registers requires special handling. A common pitfall occurs when the high and low bytes are read separately while the counter is running:

$$ \Delta = (high_{new} - high_{old}) \times 256 + (low_{new} - low_{old}) $$

If an overflow occurs between reading the high and low bytes, the calculated delta will be incorrect. Many manufacturers provide atomic read operations or shadow registers to prevent this issue.

Power Management Interactions

Low-power modes often affect timer operation in non-obvious ways. When entering sleep modes:

  • Some clock sources may be disabled
  • Prescalers may be reset
  • Asynchronous timers may lose synchronization

Always consult the power management section of the microcontroller reference manual to understand these interactions. Measure timer behavior after wake-up to verify proper operation.

6. Recommended Books and Datasheets

6.1 Recommended Books and Datasheets

  • PDF Technical Reference Manual - Nuvoton — The MS51BA9AE / MS51DA9AE provides rich peripherals including 256 Bytes of SRAM, 1K Bytes of auxiliary RAM (XRAM), Up to 12 general purpose I/O, two 16-bit Timers/Counters 0/1, one 16-bit Timer2 with three-channel input capture module, one Watchdog Timer (WDT), one Self Wake-up Timer (WKT), one 16-bit auto-reload Timer3 for general purpose or ...
  • PDF 6 Using the MCU Timers - Springer — 6.2 The General Structure and Functions of the Timer System Timing is essential for the operation of microcontroller systems, either for generating signals with precisely determined duration, or for counting external events. For this reason, the timer subsystem is present in all microcontroller implementations, and covers a wide range of functions including:
  • PDF General-purpose timer cookbook - STMicroelectronics — Within the STM32 microcontrollers' documentation, a general purpose timer peripheral is always named "TIMx timer", where "x" can be any number and it does not reflect the number of timer peripherals embedded by a given microcontroller. For example, the STM32F100 microcontrollers embed a timer peripheral named TIM17, but the total number of timer peripherals embedded by these ...
  • PDF Digital and System Design - Use of Microcontroller — This explains the main reason behind calling our book "Digital System Design" and not "Embedded System Design"; the use of the microcontroller as the processor in the system. In Chapter 6, we discuss the memory system; Chapter 7 considers timer/counters, while Chapter 8 treats the main components of any Data Acquisition System.
  • PDF Microcontrollers - Dr. P's Engineering Classes — These topics include I/O port registers, analog to digital con-version, interrupts, timers/counters, clock systems, pulse-width modulation, serial communication, memory addressing, CPU regis-ters and condition codes, and a basic overview of assembly language. Some chapters have additional practice problems to aid in studying the material.
  • PDF Chapter 6: Interrupts and Timers - embedded-knowhow.co.uk — The Digital Counter It is easy in digital electronics to make electronic counters by connecting together a series of bistables or flip-flops. If the input is connected to a clock signal then the counter will count, in binary, the number of clock pulses applied to it.
  • PDF CHAPTER 6 - Working with time — The simplest application of Timer 0 is to use it as a counter, counting pulses entering the microcontroller through the external input. Looking at the electronic ping-pong circuit (Appendix 2, Figure A2.1), we see that the right paddle is connected to Pin 3 of the 16F84A.
  • PDF Introduction to timers for STM32 MCUs - Application note — Introduction to timers for STM32 MCUs The purpose of this document is to: Present an overview of the timer peripherals for the STM32 product series listed in Table 1. Describe the various modes and specific timer features, such as clock sources.
  • PDF AT07690: Using the Timer Counter for Control Applications in SAM D11 — The Timer/Counter for Control Applications (TCC) module provides a set of timing and counting related functionalities, such as the generation of periodic waveforms, the capture of a periodic waveform's frequency/duty cycle, software timekeeping for periodic operations, waveform extension control, fault detection, etc.
  • AN4776 General-Purpose Timer Cookbook for STM32 Microcontrollers — AN4776 Application note General-purpose timer cookbook for STM32 microcontrollers Introduction The timer peripheral is part of the essential set of

6.2 Online Resources and Tutorials

  • "Bare Metal" STM32 Programming (Part 5): Timer ... - Vivonomicon — The "advanced control" timer peripheral is particularly complicated and I won't try to cover it in this quick overview, but the basic and general-purpose timers are easy to get started with for simple counters and interrupts.
  • 8051 MicroController Architecture - GeeksforGeeks — What is 8051 MicroController? An 8051 microcontroller is an 8-bit Harvard architecture microcontroller and it consists of a CPU, RAM, ROM, I/O ports, timers, and serial communication ports all combined on one chip.
  • Lab 7: PIC Timers and Counters (Part 1) - Embedded Lab — Description PIC microcontrollers are equipped with one or more precision timing systems known as Timers. They can be used to perform a variety of time precision functions, such as generating events at specific times, measuring the duration of an event, keeping date and time record, counting events, etc. The main component of a timer module is a free running binary counter that increments for ...
  • 1.6 Getting Started with Timers - Microchip Technology — In this example, the microcontroller was configured with a clock system of 1 MHz and the timer was configured with a clock source frequency of 250 kHz. It is a 16-bit timer so it can count up to 65,535.
  • PDF Digital and System Design - Use of Microcontroller — This explains the main reason behind calling our book "Digital System Design" and not "Embedded System Design"; the use of the microcontroller as the processor in the system. In Chapter 6, we discuss the memory system; Chapter 7 considers timer/counters, while Chapter 8 treats the main components of any Data Acquisition System.
  • PDF General-purpose timer cookbook - STMicroelectronics — The purpose of this application note is to provide a simple and clear description of the basic features and operating modes of the STM32 general-purpose timer peripherals. This document complements the specifications of the STM32 timer peripherals available on their reference manuals.
  • PDF Introduction to timers for STM32 MCUs - Application note — Introduction to timers for STM32 MCUs The purpose of this document is to: Present an overview of the timer peripherals for the STM32 product series listed in Table 1. Describe the various modes and specific timer features, such as clock sources.
  • Getting Started with Timers/Counters on PIC18 - Microchip Technology — 3 Using and Operating TMR0 in 16-bit Mode while the Microcontroller is in Sleep
  • PIC16f877a Timer - Tutorials — The microcontroller can also generate/measure the required time delays by running loops, but the timer/counter relieves the CPU from that redundant and repetitive task, allowing it to allocate maximum processing time for other tasks. Timer is nothing but a simple binary counter that can be configured to count clock pulses (Internal/External).
  • PDF Timers: Timer0 Tutorial (Part 1) - Microchip Technology — In the next few labs we will look at three timer/counters that are available in the mid-range PIC microcontroller family. You will notice that each of these timer/counters have unique features but also have some characteristics that are common (see Figure 1-3).

6.3 Community Forums and Support

  • Timers and Counters in Embedded Systems - csbranch.com — Types of Timers and Counters. Timers and counters come in different types, and the classification depends on the functionality and complexity of the timers. Here are some of the common types: 5.1 Basic Timers. Basic timers count clock pulses and generate interrupts when they reach a preset value.
  • 1.6 Getting Started with Timers - Microchip Technology — The event can be configured to clear or not clear the timer counter value and, if the GPIO pin should be set high, set low or toggled every time the event is triggered. ... 1.6.3 Using and Operating TMR0 in 16-bit Mode while the Microcontroller is in Sleep. 1.6.3.1 MCC Generated Code; 1.6.3.2 Bare Metal Code; 1.6.4 Using TMR0 in 8-bit Mode and ...
  • Bios6 and Timers - Processors forum - TI E2E support forums — To that end, I went through and specified a timer ID for each specific timer. ti.sysbios.knl.clock.timerid = 0, an instance of ti.sysbios.hal.timer has an id of 1. then I have three instances of ti.sysbios.timers.timer64.timer: two sharing timer id 2 (one using the lower 32bit counter, the other using the upper 32 bit counter), and timer id 3 i ...
  • PDF AN0005: EFM32 Real Time Counters - Silicon Labs — Real Time Counters 1.1 General Many microcontroller applications have long time intervals in which almost no activity is required. ... timers. Two kinds of timers are supported: oneshot timers and periodic timers. ... to support RTCC Added example code (main_rtcc_calendar.c) for RTCC calendar mode Replace example main_rtc_driver.c with main ...
  • microcontroller - How to use timers in STM32 board and HAL library in ... — And the counter rate should be fast enough to provide sufficient time resolution between tach pulses for the fastest speed that you intend to measure. In input capture mode the timer will count up through the full range of the counter value. And the timer will capture the counter value and provide an interrupt when ever a tach pulse is received.
  • PDF Digital and System Design - Use of Microcontroller - River Publishers — and microcontroller, etc. We briefly introduce the reader to the main build-ing blocks of the microcontroller that will be the subject of the rest of the book; timers, counters, the watchdog timer, ADC, DAC, serial communica-tion, memory, need of programming, etc. Part 2 comprises Chapters 4 and 5 which cover the programming part of
  • 8051 Timers | 8051 Controller - ElectronicWings — Introduction to 8051 Timers. 8051 microcontrollers have two timers and counters which work on the clock frequency. Timer/counter can be used for time delay generation, counting external events, etc. 8051 Clock . Every Timer needs a clock to work, and 8051 provides it from an external crystal which is the main clock source for Timer.
  • H-bridge control with PWM from different timers an ... — (e.g. PC_1 is by default connected to Timer 1, channel 1, and PA_7 is the complimentary pin (by default)). So my question is really: How can I (in software) make one PWM signal the complimentary of another PWM signal, and they are not of the same timer and/or channel (with a dead-time in between), and the it is switching between different ...
  • How to build a proportional pulse stretcher? : r/AskElectronics - Reddit — You can then use the interupt routines to record the timing between events by using the time difference in one of the 16bit timers. At the full 16MHz This will give you a resolution of 62.5ns and a max pulse of 4ms, more than enough for your requirements It's a good project to begin the next stage of microcontroller development.
  • PDF AT07690: Using the Timer Counter for Control Applications in SAM D11 — AT07690: Using the Timer Counter for Control Applications in SAM D11 APPLICATION NOTE Introduction This application note describes the following features of the Timer/Counter for Control Applications available on the Atmel® | SMART SAM D11. 1. Circular Buffer. 2. One-shot Operation. 3. Output Matrix with DTI. 4. Swap. 5. Pattern Generation. 6 ...