Timers and Counters in MCUs
1. Definition and Core Concepts
Timers and Counters in MCUs: Definition and Core Concepts
Fundamental Definitions
Timers and counters are hardware peripherals in microcontrollers (MCUs) designed to measure time intervals, count external events, or generate precise timing signals. While often used interchangeably, they serve distinct purposes:
- Timer: A register that increments at a fixed frequency derived from the MCU's clock source, used for time-based operations.
- Counter: A register that increments in response to external pulses or edges, used for event counting or frequency measurement.
Mathematical Basis of Timer Operation
The timer's resolution and maximum interval are determined by its bit-width and clock frequency. For an n-bit timer with a clock frequency fclk, the time per count (tcount) and maximum time (tmax) are:
For example, a 16-bit timer running at 16 MHz has:
Prescalers and Frequency Division
To extend the measurable time range, timers incorporate prescalers that divide the input clock frequency by a configurable integer N:
Common prescaler values are powers of 2 (e.g., 8, 64, 256) for hardware efficiency.
Counter Modes and Applications
Counters operate in several fundamental modes:
- Up-Counting: Increments until overflow, useful for periodic interrupt generation.
- Down-Counting: Decrements from a loaded value, used in PWM generation.
- Capture Mode: Records the timer value when an external trigger occurs, enabling pulse-width measurement.
Advanced Features in Modern MCUs
Contemporary timer peripherals incorporate:
- Auto-reload: Automatic reset of the timer register after overflow.
- DMA Triggers: Direct memory access initiation upon timer events.
- Encoder Interface: Dedicated hardware for quadrature encoder decoding.
Practical Implementation Considerations
When configuring timers:
- Clock jitter affects timing precision in high-frequency applications.
- Timer register read/write operations require synchronization to avoid metastability.
- Power consumption scales with timer frequency and bit-width.
Real-World Applications
Typical use cases include:
- Pulse-width modulation (PWM) for motor control
- Real-time clock (RTC) implementations
- Digital signal sampling timebases
- Timeout generation in communication protocols

1.2 Key Differences Between Timers and Counters
Fundamental Operational Principles
Timers and counters in MCUs both utilize register-based counting mechanisms, but their input sources and applications differ fundamentally. A timer increments its value at a fixed rate derived from the MCU's clock signal, making it ideal for time-based operations. The count rate for a timer is given by:
where fclock is the system clock frequency and the prescaler divides this frequency by an integer value. In contrast, a counter increments only when it detects an external edge trigger on its dedicated input pin, with the count rate being:
Hardware Configuration Differences
The hardware implementation reveals critical distinctions:
- Input Source: Timers use internal clock signals, while counters require external pin connections
- Interrupt Generation: Timers typically offer more sophisticated interrupt capabilities tied to overflow/compare matches
- Prescaler Options: Timers feature configurable prescalers (1:1 to 1:256 common), while counters usually operate at the external signal frequency
- Capture/Compare Units: Timer peripherals often include multiple capture/compare channels absent in basic counters
Applications in Embedded Systems
These functional differences lead to distinct use cases:
- Timer Applications:
- PWM generation for motor control
- Precise delay generation
- Real-time clock implementations
- Counter Applications:
- RPM measurement of rotating machinery
- Digital pulse accumulation
- Event counting in industrial automation
Register-Level Configuration
The control registers highlight architectural differences. A timer configuration typically requires setting:
where WGM bits set waveform generation mode and CS bits configure clock selection. Counter configurations instead focus on edge detection:
with ICES selecting edge polarity and ICNC enabling noise cancellation.
Performance Characteristics
The maximum operational frequencies differ substantially:
- Timers: Limited by clock tree distribution (often 50-100MHz in modern MCUs)
- Counters: Limited by input pin characteristics (typically 10-25MHz maximum)
Power consumption also varies significantly, with timers drawing more current due to continuous clock tree activation, while counters only consume substantial power during external events.

1.3 Common Applications in Embedded Systems
Real-Time Event Scheduling
Timers in microcontrollers enable precise real-time scheduling through interrupt-driven architectures. When a timer reaches a predefined value (compare match), it triggers an interrupt service routine (ISR), allowing deterministic execution of time-critical tasks. The period T for such scheduling is given by:
where N is the timer's maximum count value, PR the prescaler register, and FCPU the clock frequency. Advanced MCUs like ARM Cortex-M series implement multiple independent timers (e.g., SysTick, general-purpose TIM) with 16/32-bit resolution.
Pulse-Width Modulation Generation
Hardware timers generate PWM signals by combining counter registers with output compare modules. The duty cycle D is controlled through the capture/compare register (CCR):
where ARR is the auto-reload register value. Modern MCUs like STM32 provide complementary PWM outputs with dead-time insertion for motor control applications, achieving sub-nanosecond resolution through advanced timer peripherals (TIM1/8 in STM32F4).
Frequency Measurement Techniques
Input capture units coupled with counters enable precise frequency measurement. The input signal gates the counter, with the captured value C relating to frequency f as:
where FTIM is the timer clock frequency. High-speed counters (e.g., 80 MHz in ESP32) combined with quadrature encoder interfaces allow rotational speed measurements up to 200,000 RPM with 0.1% accuracy.
Watchdog Timers for System Reliability
Independent watchdog (IWDG) and window watchdog (WWDG) timers provide fail-safe mechanisms. The IWDG timeout period follows:
where WDGTB is the prescaler, T[5:0] the reload value, and FLSI the low-speed internal clock (~32 kHz). Automotive MCUs like Infineon Aurix implement multi-core watchdogs with error-correction codes for ASIL-D compliance.
Time-Stamping and Data Logging
Real-time clock (RTC) peripherals with battery backup maintain absolute time references. The timestamp resolution Δt depends on the sub-second counter configuration:
where SSC is the synchronous prescaler stage (typically 15-17 bits). Industrial-grade MCUs like NXP LPC55Sxx achieve ±2 ppm accuracy with temperature-compensated RTCs.

2. Basic Timer Operation Modes
2.1 Basic Timer Operation Modes
Timer Fundamentals
Timers in microcontrollers (MCUs) are hardware peripherals designed to measure or generate precise time intervals. They operate independently of the CPU, relying on clock signals derived from either the system clock or an external oscillator. The core principle involves counting clock pulses and triggering events upon reaching predefined values stored in registers.
Timer Modes
Most MCU timers support multiple operation modes, each serving distinct purposes in embedded systems. The primary modes include:
- Periodic Interval Mode (PWM Generation): Generates square waves with configurable duty cycles by toggling output pins when the counter matches compare registers.
- Input Capture Mode: Records timestamps of external events (e.g., rising/falling edges) by latching the counter value into a register upon trigger.
- Output Compare Mode: Triggers interrupts or pin state changes when the counter matches a predefined value.
- One-Shot Mode: Counts a single interval before stopping, useful for non-repetitive delays.
Mathematical Foundation
The timer's resolution and maximum interval depend on the counter size (N bits) and input clock frequency (fclk). The time per count (Δt) and maximum time (Tmax) are given by:
For example, a 16-bit timer (N=16) clocked at 1 MHz yields Δt = 1 µs and Tmax ≈ 65.535 ms. Prescalers extend this range by dividing fclk before counting.
Practical Implementation
Consider configuring a timer for PWM generation on an ARM Cortex-M MCU. The duty cycle (D) and period (T) are controlled via compare registers (CCR) and auto-reload register (ARR):
Modern MCUs like STM32 or AVR use hardware abstraction layers (HAL) to simplify timer configuration. For instance, STM32CubeMX autogenerates initialization code for PWM modes, abstracting low-level register manipulation.
Advanced Features
High-end timers incorporate:
- Encoder Interface Mode: Decodes quadrature signals from rotary encoders by tracking counter increments/decrements.
- Dead-Time Insertion: Adds programmable delays between complementary PWM signals to prevent shoot-through in H-bridge circuits.
- DMA Triggers: Offloads data transfers (e.g., ADC results) upon timer events without CPU intervention.
These features enable complex applications like motor control (FOC algorithms), digital power conversion, and real-time signal processing. For example, Texas Instruments' C2000 MCUs use enhanced PWM modules with nanosecond-resolution dead-time control for industrial inverters.

2.2 Prescalers and Clock Sources
Prescalers are essential components in microcontroller timer modules, enabling the division of the input clock frequency to achieve longer timing intervals without requiring excessively large counter registers. The prescaler operates by dividing the system clock (fCLK) by a configurable integer factor (N), producing a reduced clock signal (ftimer = fCLK / N) for the timer or counter.
Mathematical Derivation of Timer Resolution
The timer resolution (Δt) is the smallest time increment measurable by the timer and is determined by the prescaled clock period:
For example, a 16 MHz system clock with a prescaler value of 8 yields a timer resolution of:
Clock Source Selection
Modern MCUs offer multiple clock sources for timers, including:
- Internal oscillator – Typically ranges from 1 MHz to 48 MHz, offering low power consumption but moderate accuracy (±1–2%).
- External crystal oscillator – Provides high precision (±10–50 ppm) and stability, often used in real-time applications.
- Phase-locked loop (PLL) – Multiplies the base clock frequency for high-speed timing requirements.
- Secondary low-frequency oscillator (LFO) – Used for power-saving modes (e.g., 32 kHz in RTC applications).
Practical Considerations
When selecting a prescaler value and clock source, engineers must consider:
- Trade-off between resolution and range – Higher prescaler values increase the maximum measurable interval but reduce resolution.
- Power consumption – High-frequency clocks and PLLs increase dynamic power dissipation.
- Jitter and stability – External oscillators minimize timing errors in precision-critical applications.
Example: Timer Configuration in an AVR MCU
The following register settings configure Timer1 on an ATmega328P for a 1 ms interrupt interval using a 16 MHz clock:
// Set prescaler to 64 (N=64)
TCCR1B |= (1 << CS11) | (1 << CS10);
// Set compare match value for 1 ms
OCR1A = 250 - 1; // (16e6 / 64) * 1e-3 = 250
// Enable compare interrupt
TIMSK1 |= (1 << OCIE1A);
Here, the prescaler value of 64 reduces the effective timer frequency to 250 kHz, allowing the 8-bit counter to achieve a 1 ms period with an OCR1A value of 249.
Advanced Techniques: Dynamic Prescaler Adjustment
Some MCUs support runtime prescaler switching to optimize power and resolution. For instance, a sensor sampling system might use a high prescaler (low power) during idle periods and switch to a lower prescaler (high resolution) during active measurements.

2.3 Timer Interrupts and Event Generation
Interrupt-Driven Timer Operation
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), forcing the CPU to pause its current execution and jump to an Interrupt Service Routine (ISR). The ISR performs the required action (e.g., toggling a GPIO, updating a variable) before returning to the main program.
The interrupt latency, defined as the delay between the interrupt trigger and ISR execution, is critical for real-time systems. It depends on:
- Current instruction completion time
- Interrupt nesting configuration
- Priority of the timer interrupt relative to other IRQs
Mathematical Model of Timer Interrupt Timing
The period T between timer interrupts is determined by the timer's clock source and count value:
Where:
- N = Timer counter value (e.g., OCR1A for compare match)
- PR = Prescaler divider (1, 8, 64, etc.)
- fclk = System clock frequency
For example, an ATmega328P running at 16MHz with a prescaler of 64 and OCR1A=24999 yields:
Hardware Event Generation
Timers can directly trigger peripheral actions without CPU intervention through specialized output compare units. Common event types include:
- PWM Generation: Timer compare matches toggle OCx pins to produce pulse-width modulated signals
- ADC Synchronization: Timer overflow triggers analog-to-digital conversions
- DMA Requests: Timer events initiate direct memory access transfers
Modern MCUs like ARM Cortex-M devices implement timer event routers that can map timer triggers to any peripheral through configurable crossbar switches.
Advanced Configuration: Capture/Compare Units
Sophisticated timer modules feature multiple capture/compare channels that operate in parallel. Each channel can be independently configured for:
- Input capture (timestamping external events)
- Output compare (generating precise timing edges)
- PWM generation with dead-time insertion
The STM32's advanced timer (TIM1/TIM8) adds complementary outputs with programmable dead-time for motor control applications. The dead-time td between complementary PWM signals is calculated as:
Where DTG[7:0] is the dead-time generator value and Ttclk is the timer clock period.
Practical Implementation Considerations
When implementing timer interrupts:
- Minimize ISR processing time to reduce jitter
- Use double buffering for timer compare registers when modifying periods during operation
- Employ hardware synchronization features when chaining timers
- Consider power consumption implications of continuous timer operation in battery-powered systems
For example, the following code configures a 1kHz interrupt on an STM32 using HAL libraries:
// STM32 Timer 2 initialization for 1kHz interrupt
htim2.Instance = TIM2;
htim2.Init.Prescaler = 16000-1; // 16MHz/16000 = 1kHz
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 1000-1; // 1ms period
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_Base_Init(&htim2);
// Enable interrupt and start timer
HAL_TIM_Base_Start_IT(&htim2);

2.4 PWM Generation Using Timers
Fundamentals of Pulse Width Modulation
Pulse Width Modulation (PWM) is a technique for generating analog-like signals from digital outputs by rapidly switching a pin between high and low states. The average voltage is controlled by varying the duty cycle, defined as the ratio of the pulse width (ton) to the total period (T):
In MCUs, timers generate PWM signals by comparing a counter value with a programmable threshold stored in a capture/compare register (CCR). When the counter matches the CCR, the output pin toggles, creating precise edges.
Timer Modes for PWM Generation
Modern MCUs support several timer configurations for PWM:
- Edge-aligned PWM: The counter counts up to the auto-reload value (ARR) and resets. The output transitions occur when the counter matches the CCR.
- Center-aligned PWM: The counter counts up and down, creating symmetrical pulses around the center of the period. This reduces harmonic noise in motor control applications.
- Asymmetric PWM: Multiple CCRs control independent edges, enabling complex waveforms.
Mathematical Derivation of PWM Frequency
The PWM frequency (fPWM) is determined by the timer clock frequency (fCLK), prescaler (PSC), and auto-reload value (ARR):
For example, with a 72 MHz clock, a PSC of 71, and an ARR of 999:
Advanced PWM Features
High-end timers offer:
- Dead-time insertion: Delays between complementary PWM signals to prevent shoot-through in H-bridge circuits.
- Burst mode: PWM output in controlled bursts for power savings.
- DMA support: Direct memory access for waveform updates without CPU intervention.
Practical Implementation Example
Configuring a timer for PWM on an STM32 involves:
// STM32 HAL example for PWM generation
TIM_HandleTypeDef htim1;
TIM_OC_InitTypeDef sConfigOC;
htim1.Instance = TIM1;
htim1.Init.Prescaler = 71;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 999;
HAL_TIM_PWM_Init(&htim1);
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 500; // 50% duty cycle
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
Applications and Optimization
PWM is critical in:
- Motor control: Varying duty cycle adjusts speed while maintaining torque.
- Power converters: Buck/boost regulators use PWM for voltage regulation.
- Audio generation: Class D amplifiers modulate PWM signals to reproduce sound.
Optimization techniques include:
- Using timer DMA to update CCR values for smooth waveform transitions.
- Leveraging hardware dead-time generators for safe power switching.
- Employing timer synchronization for multi-phase systems.

3. Edge Counting and Frequency Measurement
3.1 Edge Counting and Frequency Measurement
Fundamentals of Edge Counting
Edge counting is a fundamental operation in microcontroller-based signal processing, where transitions (rising or falling edges) of a digital input signal are tallied by a hardware counter. The counter increments on each detected edge, with the edge polarity (rising or falling) often configurable via control registers. For a periodic signal with frequency f, the edge count N over a gate time Tgate is given by:
The factor of 2 arises when counting both rising and falling edges. In most MCUs, the timer/counter peripheral can be configured to increment on only one edge type, allowing N = fTgate for single-edge counting.
Frequency Measurement Techniques
Frequency measurement leverages edge counting with a known timebase. Two primary methods exist:
- Direct Counting: The input signal's edges are counted over a fixed gate time (e.g., 1 second). The count value directly represents the frequency in Hertz.
- Reciprocal Counting: Measures the period of the input signal by counting clock cycles between consecutive edges, then inverts the period to obtain frequency. This method excels at low frequencies.
The resolution Δf of direct counting is determined by the gate time:
For reciprocal counting, the resolution depends on the reference clock frequency fclk:
Hardware Implementation
Modern MCUs integrate dedicated timer/counter peripherals for edge counting and frequency measurement. Key components include:
- Prescaler: Divides the input signal frequency to extend the measurable range.
- Capture/Compare Registers: Store timestamps of edge events for period measurement.
- Input Capture Unit: Triggers an interrupt or DMA transfer on edge detection.
For high-frequency signals (>10 MHz), synchronous counting circuits (e.g., Gray code counters) mitigate metastability risks. Advanced MCUs may include hardware averaging or digital filtering to reduce jitter.
Error Sources and Mitigation
Edge counting accuracy is affected by:
- Quantization Error: Inherent in discrete counting; reduced by longer gate times or higher clock rates.
- Trigger Jitter: Caused by noise or signal slew rate limitations. Schmitt trigger inputs are commonly employed.
- Clock Drift: The reference clock's stability (e.g., ±50 ppm for typical crystals) limits long-term accuracy.
For sub-Hz resolution applications, temperature-compensated oscillators (TCXOs) or GPS-disciplined clocks are used as references.
Practical Applications
Edge counting and frequency measurement are ubiquitous in:
- Tachometry: Measuring rotational speed via optical or magnetic encoders.
- Ultrasonic Ranging: Determining distance using time-of-flight of reflected pulses.
- Spectrum Analysis: Building low-cost frequency analyzers for RF or audio signals.
In industrial environments, opto-isolated inputs and differential signaling (e.g., RS-422) enhance noise immunity for reliable edge detection.

Quadrature Decoding for Encoders
Fundamentals of Quadrature Encoding
Quadrature encoders generate two square-wave signals (A and B) phase-shifted by 90° to indicate rotational direction and displacement. The phase relationship determines the direction:
- Clockwise (CW): Signal A leads B by 90°.
- Counterclockwise (CCW): Signal B leads A by 90°.
Each rising or falling edge of either signal corresponds to a countable event, enabling resolution enhancement via X1, X2, or X4 decoding modes.
Where N is pulses per revolution and K is the decoding multiplier (1, 2, or 4).
Hardware Implementation in MCUs
Modern MCUs integrate quadrature decoder peripherals (e.g., STM32’s TIMx, NXP’s eFlexPWM) that automatically track encoder state transitions. Key registers include:
- Count Register: Stores accumulated pulses (up/down counts).
- Direction Flag: Indicates CW/CCW rotation.
- Filtering Registers: Debounce noisy encoder signals via programmable digital filters.
State Transition Logic
The decoder evaluates the current and previous states of A and B (Gray code encoding) to determine motion. The state transition table for X4 decoding is:
| Previous AB | Current AB | Count Direction |
|---|---|---|
| 00 | 01 | +1 (CW) |
| 01 | 11 | +1 |
| 11 | 10 | +1 |
| 10 | 00 | +1 |
| 00 | 10 | -1 (CCW) |
Velocity Estimation
Velocity is derived from the pulse rate using timer capture/compare units. For a timer clocked at fCLK:
Where ΔC is the count change over n clock cycles.
Error Handling
Common issues include:
- Missed counts: Mitigated by increasing MCU clock speed or reducing encoder RPM.
- Signal glitches: Addressed via hardware Schmitt triggers or software debouncing.
- Count overflow: Managed by using 32-bit counters or periodic read-and-reset routines.
Practical Applications
Quadrature decoding is critical in:
- Precision robotics (e.g., arm joint positioning).
- CNC machines for feedback control.
- Optical encoders in scientific instruments (e.g., telescope mounts).
// STM32 HAL example for quadrature encoder
TIM_Encoder_InitTypeDef encoder;
encoder.EncoderMode = TIM_ENCODERMODE_TI12; // X4 mode
encoder.IC1Polarity = TIM_ICPOLARITY_RISING;
encoder.IC2Polarity = TIM_ICPOLARITY_RISING;
HAL_TIM_Encoder_Init(&htim3, &encoder);
HAL_TIM_Encoder_Start(&htim3, TIM_CHANNEL_ALL);

3.3 Pulse Width Measurement Techniques
Fundamentals of Pulse Width Measurement
Pulse width measurement is a critical function in microcontroller-based systems, enabling precise timing analysis of digital signals. The pulse width (PW) is defined as the duration between the rising and falling edges (or vice versa) of a pulse. In MCUs, this is typically achieved using timer/counter peripherals configured in input capture or PWM input modes. The resolution of the measurement depends on the timer clock frequency and the counter's bit depth.
where N is the captured counter value, Tclk is the clock period, and fclk is the timer clock frequency.
Input Capture Mode
In input capture mode, the timer records the counter value when a transition (rising or falling edge) is detected on a designated input pin. For pulse width measurement:
- The timer is configured to trigger on both edges (rising and falling).
- The difference between two consecutive captures gives the pulse width.
- High-frequency noise can distort measurements, so digital filtering (e.g., Schmitt trigger inputs) is often applied.
PWM Input Mode
Some MCUs (e.g., STM32, ARM Cortex-M) offer a dedicated PWM input mode, where two capture registers are used to measure both the pulse width (PW) and the signal period (T). This mode simplifies measurement by automatically latching values on both edges and calculating the difference internally.
Advanced Techniques
High-Resolution Measurement
For sub-clock-cycle resolution, techniques like time-stretching or interpolating timers are employed. These methods use analog delay lines or phase-locked loops (PLLs) to achieve picosecond-level precision, often required in LiDAR or radar applications.
Statistical Averaging
In noisy environments, multiple measurements are averaged to improve accuracy. The standard deviation (σ) of the measurements provides a confidence metric:
Practical Considerations
- Timer Overflow: For long pulses, timer overflow must be accounted for by extending the counter with an overflow register.
- Clock Jitter: High-frequency clock jitter introduces uncertainty, necessitating stable oscillator sources (e.g., TCXO or OCXO).
- Interrupt Latency: In software-based capture methods, interrupt response time can skew measurements, favoring DMA-based approaches.
Applications
Pulse width measurement is essential in:
- Motor Control: Measuring encoder signals for speed and position feedback.
- Ultrasonic Ranging: Determining time-of-flight for distance calculation.
- Digital Communication: Decoding PWM-encoded data (e.g., infrared remote signals).

4. Input Capture and Output Compare
4.1 Input Capture and Output Compare
Fundamental Concepts
Input Capture (IC) and Output Compare (OC) are two critical timer/counter functionalities in modern microcontrollers. IC measures the timing of external events by recording the counter value when a trigger edge is detected on an input pin. OC generates precise timing signals by comparing the counter value with a preloaded register, triggering an action (e.g., toggle, set, or clear) upon match.
Input Capture Mechanics
When an edge (rising, falling, or both) is detected on the IC pin, the current timer value is latched into a capture register, and an interrupt may be generated. The time difference between two edges can be calculated as:
where tclk is the timer clock period. Noise filtering is typically implemented via digital glitch filters or programmable sampling.
Output Compare Operation
The OC unit continuously compares the timer counter with a preset compare register. On match, it can:
- Toggle the output pin
- Generate an interrupt
- Force the output high/low
For PWM generation, the OC register is dynamically updated to modulate duty cycle:
Advanced Features
Input Capture Modes
Advanced MCUs support:
- Buffer chaining: Multiple capture registers for high-frequency events
- Prescaler synchronization: Avoids metastability in edge detection
- Event linking: Direct hardware triggering of other peripherals
Output Compare Enhancements
Modern implementations include:
- Dead-time insertion for motor control
- Complementary waveform generation
- Fault protection auto-shutdown
Practical Applications
In a brushless DC motor controller:
- IC measures Hall sensor transitions for commutation timing
- OC generates precisely timed PWM for each phase
- Hardware-linked overcurrent detection immediately disables outputs
For frequency measurement, IC captures signal periods while a second timer counts elapsed time between captures, enabling reciprocal frequency calculation:
Implementation Considerations
Critical design factors include:
- Timer resolution vs. maximum measurable period
- Interrupt latency for time-critical applications
- Clock synchronization in multi-core systems
- Jitter analysis for high-precision timing

4.2 Timer Synchronization and Cascading
Fundamentals of Timer Synchronization
In multi-timer systems, synchronization ensures that timers operate in a deterministic and phase-aligned manner. When multiple timers are used in an MCU, clock drift or phase misalignment can lead to timing inaccuracies. Synchronization mitigates this by forcing timers to reset or start simultaneously under a common trigger signal. The synchronization mechanism typically involves a master timer controlling one or more slave timers via hardware triggers.
where Δtsync is the maximum synchronization error, ftimer is the timer clock frequency, and tprop accounts for signal propagation delays.
Hardware Trigger Synchronization
Modern MCUs like ARM Cortex-M or AVR XMEGA provide hardware trigger inputs (e.g., TRGO in STM32) to synchronize timers. When the master timer generates an update event (UEV), it sends a trigger pulse to slave timers, forcing them to reset their counters. This ensures all timers share the same timebase reference. The trigger can be configured to occur on specific events:
- Counter overflow/underflow
- Compare match
- External signal edge
Timer Cascading for Extended Resolution
Cascading connects timers in series to achieve longer counting ranges. A primary timer's overflow triggers the secondary timer, effectively creating a higher-bit counter. For example, cascading two 16-bit timers yields a 32-bit counter. The combined period Tcascaded is:
where n and m are the bit-widths of the primary and secondary timers, respectively.
Practical Implementation
In STM32, cascading is achieved by configuring Timer A as the master (TIMx_CR2.MMS=010 for overflow trigger) and Timer B as the slave (TIMx_SMCR.TS=000 for ITR0 input). The slave timer's clock must be disabled (TIMx_CR1.CEN=0) until the first trigger arrives.
Phase-Correct PWM Synchronization
For multi-channel PWM systems (e.g., motor control), phase alignment prevents shoot-through currents. Synchronized timers ensure all PWM edges are aligned to a common timebase. The alignment error ε is bounded by:
where tjitter is the clock jitter and TPWM is the PWM period.
Case Study: Synchronized ADC Sampling
In high-precision data acquisition systems, timers synchronize ADC conversions across multiple channels. A master timer triggers both the ADC start-of-conversion (SOC) and a slave timer controlling sampling intervals. This eliminates skew between channels, critical for applications like 3-phase power monitoring.

4.3 Low-Power Timer Operation
Low-power timers are critical in battery-operated and energy-constrained embedded systems, where minimizing current consumption while maintaining precise timing is essential. These timers leverage specialized hardware and software techniques to reduce power without sacrificing functionality.
Power Consumption in Timer Circuits
The total power dissipation of a timer circuit consists of dynamic and static components. Dynamic power arises from switching activity and clock distribution, while static power is due to leakage currents. The dynamic power of a timer operating at frequency f with supply voltage VDD is given by:
where α is the activity factor and C is the effective switched capacitance. Reducing VDD or f quadratically or linearly decreases dynamic power, respectively.
Low-Power Timer Design Techniques
Modern MCUs employ several architectural strategies to minimize timer power:
- Clock gating: Disables the clock to unused timer peripherals, eliminating dynamic power in idle states.
- Sub-threshold operation: Runs timers at supply voltages below the transistor threshold voltage, drastically reducing both dynamic and static power.
- Asynchronous design: Removes the global clock dependency, allowing timers to operate only when needed.
- Dynamic frequency scaling: Adjusts the timer clock rate based on required resolution and latency constraints.
Wake-Up Timers and Sleep Modes
Low-power timers often serve as wake-up sources from deep sleep modes. The wake-up time twake must account for oscillator stabilization and peripheral re-initialization:
where tosc is the oscillator start-up time, tperiph is the timer reconfiguration time, and tapp is the application-specific overhead. Ultra-low-power MCUs optimize each term through fast-start oscillators and register retention.
Case Study: STM32 LPTIM
The STM32 low-power timer (LPTIM) operates down to 1.8V and consumes just 0.5µA in stop mode while maintaining 16-bit resolution. Key features include:
- Clock source flexibility (internal LSI, LSE, or external clock)
- Hardware auto-wakeup from shutdown mode
- PWM generation with configurable duty cycles
- Asynchronous operation independent of CPU state
In one power-optimized configuration, the LPTIM achieves 1Hz timekeeping with a total system current below 2µA by leveraging the 37kHz LSI clock and aggressive clock gating.
Tradeoffs in Low-Power Timer Design
Designers must balance several competing factors when implementing low-power timers:
| Parameter | Power Impact | Performance Impact |
|---|---|---|
| Clock frequency | Linear reduction | Lower resolution/response |
| Supply voltage | Quadratic reduction | Increased timing jitter |
| Bit width | Exponential (leakage) | Higher resolution |
The optimal configuration depends on the application's accuracy requirements versus energy budget. For example, a weather station might prioritize ultra-low power with ±1% timing accuracy, while a motor controller would need higher precision despite greater power consumption.

5. Configuring Timers in Popular MCU Families
5.1 Configuring Timers in Popular MCU Families
Timer Fundamentals in MCUs
Timers in microcontrollers (MCUs) are hardware peripherals designed to measure time intervals, generate precise delays, or trigger events at specific intervals. They operate by counting clock cycles, either from the system clock or an external source. The fundamental equation governing timer operation is:
where Tevent is the time between events, N is the timer's counter value, and fclk is the clock frequency. Advanced MCUs allow prescaling the clock, introducing a divider P:
ARM Cortex-M Timers (STM32, NXP Kinetis)
The ARM Cortex-M series features sophisticated timer peripherals, including:
- SysTick Timer: A 24-bit down-counter primarily used for RTOS task scheduling.
- General-Purpose Timers (TIMx): 16/32-bit timers with input capture, output compare, and PWM generation.
- Advanced-Control Timers: Used for motor control with complementary PWM outputs and dead-time insertion.
Configuring a basic timer in STM32 using HAL involves:
TIM_HandleTypeDef htim2;
htim2.Instance = TIM2;
htim2.Init.Prescaler = 79; // 80 MHz / (79+1) = 1 MHz
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 999; // 1 kHz interrupt
HAL_TIM_Base_Init(&htim2);
HAL_TIM_Base_Start_IT(&htim2);
AVR Timers (ATmega, ATtiny)
AVR microcontrollers typically feature 8-bit and 16-bit timers with simpler architectures:
- Timer0: 8-bit timer often used for delay functions.
- Timer1: 16-bit timer with input capture for precise measurements.
- Timer2: 8-bit timer with asynchronous operation from 32 kHz crystals.
The timer mode register (TCCRx) controls prescaling and operation mode. For a 16-bit timer generating a 1 Hz interrupt on a 16 MHz clock:
TCCR1B |= (1 << CS12) | (1 << CS10); // Prescaler 1024
OCR1A = 15624; // Compare value
TIMSK1 |= (1 << OCIE1A); // Enable interrupt
ESP32 Timer Subsystems
The ESP32 features:
- Hardware Timers: Four 64-bit general-purpose timers with 16-bit prescalers.
- LED PWM Controller: High-resolution PWM generation independent of CPU.
- RMT Peripheral: Originally for infrared remote control, repurposed for precise timing.
ESP-IDF configuration for a periodic interrupt:
timer_config_t config = {
.divider = 80, // APB clock (80 MHz) / 80 = 1 MHz
.counter_dir = TIMER_COUNT_UP,
.counter_en = TIMER_PAUSE,
.alarm_en = TIMER_ALARM_EN,
.auto_reload = true
};
timer_init(TIMER_GROUP_0, TIMER_0, &config);
timer_set_counter_value(TIMER_GROUP_0, TIMER_0, 0);
timer_set_alarm_value(TIMER_GROUP_0, TIMER_0, 1000000); // 1 second
timer_enable_intr(TIMER_GROUP_0, TIMER_0);
timer_start(TIMER_GROUP_0, TIMER_0);
PIC Microcontroller Timers
PIC MCUs use a unified timer structure across families:
- Timer0: 8/16-bit timer with optional prescaler.
- Timer1: 16-bit timer often paired with CCP module.
- Timer2: 8-bit timer with PR2 period register.
For a PIC18 generating a 10 kHz PWM:
PR2 = 249; // For 10 kHz at 40 MHz with P=1
T2CON = 0b00000100; // Prescaler 1:1, timer on
CCP1CON = 0b00001100; // PWM mode
CCPR1L = 125; // 50% duty cycle
Timer Performance Optimization
Advanced configurations consider:
- Clock Gating: Disabling unused timer peripherals to reduce power.
- DMA Integration: Offloading timer-triggered data transfers.
- Input Capture Noise Cancellation: Digital filtering for reliable edge detection.
The jitter J in timer interrupts due to clock synchronization can be estimated as:

5.2 Debugging Common Timer/Counter Issues
Timer Overflow and Underflow Conditions
Timer overflow occurs when the counter exceeds its maximum value (e.g., 0xFFFF for a 16-bit timer), while underflow happens when decrementing below zero. These conditions often lead to missed interrupts or incorrect timing calculations. The overflow flag (TOV) in the timer control register (TCR) should be monitored. For example, in an 8-bit timer:
where n is the timer resolution (bits) and fclk is the input clock frequency. If the required delay exceeds tmax, prescalers or software counters must be employed.
Clock Source and Prescaler Misconfiguration
Incorrect clock source selection (internal vs. external) or prescaler settings are frequent culprits. For instance, an external clock signal must meet the MCU's minimum pulse width requirement, typically specified as:
where fsys is the system clock frequency. Prescaler errors manifest as timing deviations by integer factors (e.g., 8x slower than expected if a ÷8 prescaler is inadvertently enabled).
Race Conditions in Timer Registers
Asynchronous updates to timer control registers (e.g., TCNT, OCR) during operation can cause glitches. For atomic updates, disable interrupts during critical sections:
void safe_timer_update() {
cli(); // Disable interrupts
TCNT1 = 0x7FFF; // Update timer value
sei(); // Re-enable interrupts
}
Electromagnetic Interference (EMI) in External Counting
When using timers as counters for external signals, EMI can induce false edges. Implement hardware filtering with an RC network (time constant τ = RC > 2tnoise) or software debouncing:
where Vth is the logic threshold voltage. For optical encoders, Schmitt trigger inputs are recommended.
Phase Errors in PWM Generation
PWM phase shifts occur when timer compare registers (OCR) are updated mid-cycle. Double buffering (if available) ensures synchronous updates:
// AVR example with double buffering
OCR1A = duty_cycle; // Value latched at next TOP
For center-aligned PWM, ensure the timer is configured for up-down counting mode (e.g., WGM1[2:0] = 1 in ATmega).
Interrupt Latency and Jitter
Timer interrupt latency varies with interrupt service routine (ISR) execution time and nested interrupt priority. Worst-case latency (tlatency,max) must be less than the timer period for reliable operation:
where tcontext is the context switch time (typically 10-50 cycles). Use hardware timestamps (e.g., Input Capture units) to measure actual jitter.

5.3 Real-World Case Studies
Precision Timekeeping in Atomic Clocks
Atomic clocks rely on the hyperfine transition frequency of cesium-133 atoms, precisely measured at 9,192,631,770 Hz. Microcontroller timers, synchronized via phase-locked loops (PLLs), divide this reference to generate 1 Hz for real-time clocks. The Allan deviation σy(τ) quantifies stability:
where yi represents fractional frequency error over averaging interval τ. Advanced MCUs like the STM32H7 achieve sub-ppm drift using hardware compensation registers that adjust timer reload values dynamically.
Brushless Motor Control
Six-step commutation in BLDC motors requires precise 60° timing intervals. Timer peripherals generate complementary PWM signals with dead-time insertion. The Hall sensor input capture units trigger commutation events, with the timer period T derived from:
where P is the pole count. The Texas Instruments C2000 series implements this via its ePWM module, achieving jitter below 50 ns through clock synchronization across multiple timers.
Digital Power Supply Regulation
Switch-mode power supplies use timer interrupts for voltage-mode control. The duty cycle D updates every switching period Tsw based on PID output:
Microchip dsPIC33 devices achieve 1 ns resolution via their high-resolution PWM peripherals, enabling >90% efficiency at 2 MHz switching frequencies. Current-mode control adds ADC-triggered timer captures for peak current detection.
Wireless Sensor Network Synchronization
IEEE 802.15.4 networks use timer capture/compare for TDMA scheduling. The synchronization error ε between nodes follows:
where Δf is frequency offset and D is drift rate. Nordic nRF52 series counters compensate this using radio timestamping at the 16 MHz timer tick level, achieving <100 ns synchronization accuracy.
Automotive Engine Control Units
Crank angle measurement requires capturing timer values at tooth edges of the reluctor wheel. The angular velocity ω is computed from consecutive edges:
NXP S32K144 MCUs implement this via FlexTimer modules with 41.6 ps resolution, enabling misfire detection even at 10,000 RPM. Missing tooth patterns are identified using timer overflow interrupts.

6. Recommended Datasheets and Manuals
6.1 Recommended Datasheets and Manuals
- Download Owners Manuals for Digital Panel Meters, Counters, Timers ... — Click on the links below to download technical manuals for digital panel meters, counters, timers and remote displays by Laurel Electronics. Call (714) 434 6131 for Product Assistance. Panel Meters - Counters - Timers - Transmitters, 4-20 mA & Modbus - Ethernet - USB - RS485 - RS232 ... Large-Digit Counters; Electronic Timers. Stopwatch, Single ...
- PDF EAGLE SIGNAL CX400 Dual Setpoint Timer/Counter — Electronic Timers T I M E R S E L E C T R O N I C T I M E R S 5 5.36 DANAHER SENSORS & CONTROLS The CX400 is a microprocessor based, dual setpoint timer/counter housed in a standard 15 terminal CYCL-FLEX® plug-in case which allows easy removal for programming changes and replacement. Time or count operation, time range, and the type of start ...
- PDF AN4013 Application note - STMicroelectronics — February 2025 AN4013 Rev 13 1/47 1 AN4013 Application note Introduction to timers for STM32 MCUs Introduction The purpose of this document is to: • Present an overview of the timer periphera ls for the STM32 product series listed in Table 1. • Describe the various modes and specific timer features, such as clock sources.
- Data Sheets | Eagle Signal Timers & Counters — Electro-Mechanical Timers; Electronic Timers; Percentage Timers; Other Timers; Accessories; Applications. Commercial Printing; ... Download CT4 Series Percentage Timer Datasheet: pdf CX100 Series Repeat Cycle Timer ... Download CX200 Series Microprocessor Preset Timer-Counter: pdf CX300 Microprocessor Preset Timer-Counter pdf 136 KB
- PDF Low-power timer (LPTIM) applicative use cases on STM32 MCUs and MPUs ... — This application note describes the various modes and specific features of the low-power timer (LPTIM) embedded in the STM32 microcontrollers (MCUs) and microprocessors (MPUs) listed in the table below. This document contains some applicative examples provided with: • the X-CUBE-LPTIMER Expansion Package which includes:
- Manuals | Eagle Signal Timers & Counters - Specialty Product Technologies — Click here for user manuals for Eagle Signal Controls industrial timers including specifications, installation, maintenance instructions.
- Timer Peripherals for 8-bit MCUs | Microchip Technology — For the best experience, please visit the site using Chrome, Firefox, Safari, or Edge. X. ... Timers on AVR MCUs are designed a little differently than the timers on PIC MCUs. The biggest difference is that the timers on AVR MCUs are integrated with waveform output modules like the Pulse-Width Modulation (PWM) and Complimentary Waveform ...
- PDF UNIT - 4: TIMER and INTERUPT PROGRAMMING 4.1 TIMERS AND COUNTERS Timer ... — 3. Mode 2 - 8-bit auto-reload timer/counter 4. Mode 3 - Split timer. C/T (clock/timer): This bit is used to select timer hardware as a timer or counter. If this bit is set to 0, timer hardware act as a timer to generate time delay by counting internal clock pulse generated by the crystal oscillator. If the bit is set
- PDF 8-bit MCUs with A/D converter, two timers ... - STMicroelectronics — 2 Timers - Configurable watchdog timer - 8-bit timer/counter with a 7-bit prescaler Analog Peripheral - 8-bit ADC with 4 input channels (except on ST6203C) Instruction Set - 8-bit data manipulation - 40 basic instructions - 9 addressing modes - Bit manipulation Development Tools - Full hardware/software development package
- ST62P25BM6/CCC datasheet - 8-bit MCUs WITH A/D Converter, TWO Timers ... — Features, Applications: 8-BIT MCUs WITH A/D CONVERTER, TWO TIMERS, OSCILLATOR SAFEGUARD & SAFE RESET. Memories or 4K bytes Program memory (OTP, EPROM, FASTROM or ROM) with read-out protection 64 bytes RAM Clock, Reset and Supply Management Enhanced reset system Low Voltage Detector (LVD) for Safe Reset Clock sources: crystal/ceramic resonator or RC network, external clock, backup ...
6.2 Advanced Topics and Research Papers
- PDF STM32 cross-series timer overview - STMicroelectronics — signals with a time base independent from the advanced timers. • Basic timers have no input/outputs and are used either as timebase timers or for triggering the DAC peripheral. • Low-power timers are simpler than general purpose timers and their advantage is the ability to continue working in low-power modes and generate a wake-up event.
- Using Timers and Counters to Create Efficient MCU-based Designs — Timer and counter modes: from simple to advanced. Timers and counters started out with some very simple modes of operation to replace common-program loops for counting external events, for timing internal and external operations and for collecting various statistics on key MCU operations.
- STM32 General-purpose timer cookbook - STMicroelectronics — This is my first time to use timers for PWM. I copied and adapted the code of chapter 3.2 and it is working as described: The timer TIM1 is counting up until reaching the value of CCR1 and changes the GPIO output level from LOW to HIGH until it reaches the value of ARR. The counter starts again. The most interesting code lines are:
- PDF 6 Using the MCU Timers - Springer — in the principles of operation and the structure of the timer subsystem. Figure 6.1 shows a general block diagram of the timer system, illustrating the principles of implementation of most MCU timers. The central element of the timer subsystem is a counter, TCNT (8 or 16-bits in length), which may be read or (sometimes) written by software.
- PDF Low-power timer (LPTIM) applicative use cases on STM32 MCUs and MPUs ... — This application note describes the various modes and specific features of the low-power timer (LPTIM) embedded in the STM32 microcontrollers (MCUs) and microprocessors (MPUs) listed in the table below. This document contains some applicative examples provided with: • the X-CUBE-LPTIMER Expansion Package which includes:
- PDF AN4013 Application note - STMicroelectronics — feature allows a general purpose timer to be used where an additional advanced timer would be necessary. • Basic timers are used either as timebase timers or for triggering the DAC peripheral. These timers do not have any input or output capabilities. • Low-power timers are simple general purpose timers and are able to operate in low-power ...
- PDF Examples of using eTimer on Power Architecture devices — Enhanced Motor Control Timer (eTimer) module and what is necessary to set in the device for using the eTimer. The base features of the eTimer are shown in four examples which were developed in a GreenHills project for RAM memory; generating periodical signal, generating periodical pulse, generating one-shot signal and measure signal parameters ...
- Chapter 6: Using the MCU Timers - GlobalSpec — Figure 6.1 shows a general block diagram of the timer system, illustrating the principles of implementation of most MCU timers. Figure 6.1: General block diagram of the timer subsystem The central element of the timer subsystem is a counter, TCNT (8 or 16-bits in length), which may be read or (sometimes) written by software.
- Latches, Flip-Flops, Counters, Registers, Timer, Multiplexer ... - Springer — A two-digit BCD counter is presented in Fig. 8.31 (a two-digit BCD counter). It consists of two modulo-10 counters, one for each BCD digit, which we implemented using the parallel-load four-bit counter. Note that in a modulo-10 counter it is necessary to reset the four flip-flops after the count of 9 has been obtained.
- Introduction to Microcontroller Timers: Periodic Timers — The counter is 24 bits wide and counts down from a modulus value which is reloaded when the counter reaches 0. The count sequence is the same one shown earlier. The value of the counter can be read "on the fly" from a "current value" register. When the counter reaches 0, the timer can request an interrupt.
6.3 Online Resources and Communities
- Timers and Counters - Automation Community — Timers and counters are internal instructions that provide the same functions as timing relays and counters. They are used to activate or de-activate a device after a preset interval of time. Timers and Counters. The timer is assigned an address as well as being identified as a timer. Also included, as part of the timer instruction is the time ...
- Timer and Counter in Embedded Systems - Online Tutorials Library — The 8051 has two timers, Timer 0 and Timer 1. They can be used as timers or as event counters. Both Timer 0 and Timer 1 are 16-bit wide. Since the 8051 follows an 8-bit architecture, each 16 bit is accessed as two separate registers of low-byte and high-byte. Timer 0 Register. The 16-bit register of Timer 0 is accessed as low- and high-byte.
- Beginning Microcontrollers Part 11: Timers, Counters, and the ... — The latter program is shown here since it has the most features used with the 16-bit timer. Without being repetitive from previous posts, the program initializes the ports for the LEDs and sets the timer/counter #1 (the 16-bit timer). The TCCR1B control register is used to set the prescaling factor of 64 with the CS10 and CS11 switches.
- 1.6 Getting Started with Timers - Microchip Technology — This technical brief provides information about the Timers/Counters present on the PIC18 families of microcontrollers. The document describes the application area, the modes of operation and the hardware and software requirements of the Timers/Counters and configurable output or input for internal or external use with the help of the Peripheral Pin Select (PPS).
- Essentials of Microcontroller Use Learning about Peripherals: Timers — The peripheral timers most frequently used by MCUs are those that count out a specific time period, and those that issue periodic interrupts. The RX63N includes numerous other timers as well, including one that generates a PWM (pulse-width modulation) signal used for servo motor control, another that measures the time between input signals, and ...
- 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.
- Using Timers and Counters to Create Efficient MCU-based Designs — The basic operation of a motor-control PWM counter/timer are common between most manufacturer implementations and those found in the NXP LPC 17xx PWM timer, which is optimized for three-phase AC and DC motor-control applications, provides a good example. As shown in Figure 2, the functions of a motor-control PWM block can appear rather complex ...
- PDF 6 Using the MCU Timers - Springer — with the timer is higher than the average number of registers of a peripheral interface. For clarity of the presentation, the registers of the timer system are described in connection with the basic operating modes of the timer. 6.3.1.1 The Timer Overflow Operating Mode The prescaler is controlled by the bits PR1:PR0 in register TMSK2 (Timer ...
- PDF AN4776 Application note - STMicroelectronics — General-purpose timer cookbook for STM32 microcontrollers Introduction The timer peripheral is part of the essential set of peripherals embedded in all the STM32 microcontrollers. The number of timer peripherals and their respective features differ from one STM32 microcontroller family to another, but they all share some common features and
- Introduction to Microcontroller Timers: Periodic Timers — The counter is 24 bits wide and counts down from a modulus value which is reloaded when the counter reaches 0. The count sequence is the same one shown earlier. The value of the counter can be read "on the fly" from a "current value" register. When the counter reaches 0, the timer can request an interrupt.








