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):
For a 16-bit timer with fclk = 16 MHz and P = 8, the maximum measurable interval before overflow is:
Modes of Operation
- Timer Mode: Clock-driven increments for PWM generation or delay creation
- Counter Mode: Edge-triggered increments for frequency measurement
- Capture Mode: Records timer value upon external trigger
- Compare Mode: Generates interrupts or toggles outputs at specific values
Hardware Implementation
Modern microcontrollers integrate multiple timer units with:
- Dedicated clock multiplexers for flexible source selection
- Auto-reload registers for periodic interrupt generation
- Daisy-chaining capability for extended resolution
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:
- Quadrature decoding for rotary encoders
- Hall sensor pattern detection
- Linked DMA operations for low-latency data transfer
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:
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:
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
- Timers: PWM generation, real-time task scheduling, baud rate generation.
- Counters: Quadrature encoder decoding, pulse accumulation, frequency measurement.
Hardware Implementation
Timer peripherals often include auxiliary features like:
- Compare/capture registers for triggering interrupts or PWM.
- Auto-reload modes for periodic tasks.
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:
For a counter, the maximum count (Cmax) is simply:
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 synchronization circuits (e.g., shadow registers).
- Counter noise cancellation (e.g., minimum pulse-width validation).
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:
where TOP is the timer's maximum count value (e.g., 0xFFFF for a 16-bit timer). Applications include:
- Real-time operating system (RTOS) task schedulers
- Sensor sampling at fixed intervals (e.g., ADC triggering)
- Timeout management in communication protocols
Pulse-Width Modulation (PWM) Generation
Timers with PWM output modes drive motors, LEDs, and power converters by varying duty cycle D:
where CCR is the capture/compare register value and ARR is the auto-reload register. Key implementations:
- Brushless DC motor control (6-step commutation)
- LED dimming with gamma correction
- Switch-mode power supply regulation
Frequency Measurement and Encoder Interfaces
Timer input capture modes measure external signal frequency fext by recording timestamps of edges:
Quadrature encoder interfaces use dual-edge detection to track position/speed in robotic systems. Advanced features include:
- Hall-effect sensor decoding for RPM measurement
- Optical encoder interpolation
- Resonant frequency tracking in ultrasonic systems
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:
where n is the timer resolution. Applications include:
- Digital synthesizers (DDS algorithms)
- Impedance spectroscopy excitation signals
- Spread-spectrum clock generation
Time-Stamping and Data Logging
High-resolution timers (e.g., 32-bit @ 100MHz) provide µs-level timestamping for:
- Precision event sequencing in particle detectors
- Network packet arrival time tagging (PTP protocol)
- Inertial measurement unit (IMU) data synchronization
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:
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:
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:
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
- Fast PWM: Counter resets at TOP, single compare point per period.
- Phase-Correct PWM: Counter counts up then down, reducing harmonic noise.
- Center-Aligned PWM: Symmetrical around TOP/2, used in motor drives.
Hardware Considerations
Timer peripherals often feature:
- Dead-time generators for H-bridge control
- Burst-mode PWM for reduced EMI
- DMA support for buffer updates without CPU intervention
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:
- Internal oscillator – Typically provides a low-frequency clock (e.g., 32 kHz or 8 MHz) with moderate stability (±1–5%).
- External crystal oscillator – Delivers high-frequency, high-precision timing (e.g., 16 MHz with ±10–50 ppm stability).
- Phase-locked loop (PLL) – Multiplies the input clock frequency to achieve higher speeds (e.g., 80 MHz from a 16 MHz source).
- External clock input – Allows synchronization with an external signal, useful in distributed systems.
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:
For example, a 16 MHz clock with a prescaler of 64 yields a timer frequency of 250 kHz. The timer resolution (Δt) then becomes:
Trade-offs in Prescaler Selection
Choosing an appropriate prescaler involves balancing resolution and maximum interval:
- High prescaler values – Increase maximum measurable interval but reduce resolution.
- Low prescaler values – Improve resolution but limit the maximum count before overflow.
For a 16-bit timer with a 16 MHz clock and prescaler of 8, the maximum interval before overflow is:
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
- Power consumption – Higher clock frequencies increase dynamic power dissipation (P ∝ fclock × V2).
- EMI reduction – Lowering clock frequencies via prescalers can mitigate electromagnetic interference.
- Real-time constraints – Critical tasks (e.g., motor control) may require dedicated timers with fixed prescalers to avoid runtime overhead.
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:
- tsync: Synchronization delay (1-3 clock cycles) as the interrupt signal propagates through flip-flops.
- texec: Worst-case instruction completion time (e.g., multi-cycle multiply or divide).
- tisr_prologue: Context-saving overhead (register pushes to stack).
Jitter (Δt) arises from variations in texec and is minimized by:
- Avoiding long-running atomic operations before ISRs.
- Using nested interrupts cautiously (priority-based controllers like NVIC in ARM Cortex-M).
Event Generation Without CPU Intervention
Advanced timer peripherals (e.g., STM32's TIM, AVR's TC1) support hardware-triggered events via:
- Output Compare Units: Automatically toggle/clear/set GPIO pins on compare matches.
- Input Capture: Record timestamps of external edges with nanosecond resolution.
- DMA Triggers: Transfer ADC results or buffer data without CPU overhead.
Practical Implementation: PWM Generation
For a 16-bit timer (e.g., TCA0 in ATmega4809), PWM frequency (fPWM) and duty cycle (D) are set via:
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
- Race Conditions: Reading TCNT while updating CCR may cause glitches. Use buffered registers (e.g., ARM's TIMx_CCR1 shadow registers).
- Power Consumption: Timer interrupts prevent sleep modes. Use event-driven peripherals (e.g., CCL in AVR-Dx) for low-power designs.
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:
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:
- Direct Period Measurement: The timer captures the duration between consecutive edges of the input signal using its internal clock. For a signal with period Tin, the timer value N relates to the input frequency as:
- Reciprocal Counting: The timer gates its counting period using the unknown signal as a timebase. By counting cycles of a known high-frequency reference clock during one period of the input signal, the frequency is calculated as:
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:
Synchronization delays between asynchronous input signals and the timer clock domain introduce additional phase uncertainty. Advanced microcontrollers mitigate this through:
- Clock dithering techniques
- Multiple-stage synchronization flip-flops
- Hardware averaging of multiple measurements
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.
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:
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:
Additional error sources include:
- Timer overflow: If the pulse width exceeds the timer's maximum count, overflow handling must be implemented.
- Signal jitter: High-frequency noise on the input signal causes edge detection uncertainty.
- Interrupt latency: Software-based capture methods suffer from variable response times.
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:
where Nhigh and Nlow are the timer counts during the high and low phases, respectively. This method averages out high-frequency jitter.
Applications
- Duty cycle modulation: Closed-loop control of PWM-driven systems requires precise pulse width feedback.
- Time-of-flight sensors: Ultrasonic and optical rangefinders measure echo pulse widths to calculate distances.
- Digital communication: Pulse-width-encoded protocols (e.g., RC servo control, infrared remote signals) decode information in the time domain.
Hardware Considerations
Modern microcontrollers integrate specialized peripherals for pulse width measurement:
- STM32's Input Capture Mode with 16-bit resolution and 4x oversampling
- PIC microcontrollers' Enhanced Capture/Compare/PWM (ECCP) module
- ESP32's PCNT (Pulse Counter) peripheral with glitch filtering
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:
- Rising edge trigger - Timer starts/resets on low-to-high transition
- Falling edge trigger - Timer starts/resets on high-to-low transition
- Dual-edge trigger - Timer responds to both transitions
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:
- Precise pulse width measurement
- Noise filtering by ignoring transitions during inactive gate periods
- Synchronized multi-timer operation in complex systems
The gate control logic can be modeled as:
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:
- Input buffer with Schmitt trigger characteristics
- Programmable digital noise filter (4-16 clock cycles)
- Synchronization flip-flops (2-3 stages) to prevent metastability
- Edge detection logic feeding into the timer control unit
The synchronization process introduces a deterministic latency that must be accounted for in precision applications:
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:
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.
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:
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:
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:
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
- Clock Synchronization: Asynchronous timer modes in AVR/PIC require careful handling to avoid metastability.
- Power Consumption: ARM timers can be gated using the RCC registers to minimize active power.
- Jitter Reduction: Using hardware capture/compare registers yields more precise timing than software polling.
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:
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:
where fclock is the timer clock frequency. In practice, the prescaler value P divides the system clock fCPU to produce fclock:
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:
- Select timer clock source and prescaler by configuring TCCR1B.
- Calculate and set the compare match value OCR1A = N - 1.
- Enable compare match interrupt by setting OCIE1A in TIMSK1.
- Start the timer by writing to TCCR1B.
- 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:
For sub-microsecond precision, consider:
- Using higher CPU frequencies (e.g., 48MHz instead of 16MHz)
- Selecting smaller prescaler values when possible
- Employing timer cascading for very long delays
- Using hardware capture/compare units for edge-aligned events
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:
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.
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:
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):
- Connect the sensor output to a timer’s input capture pin (e.g., TI1 on STM32).
- Configure the timer in input capture mode with edge detection (rising/falling/both).
- Set the timer clock source (e.g., internal 16 MHz oscillator) and prescaler to achieve the desired resolution.
Mathematical Derivation
Assume a timer clock frequency fclk and prescaler value P. The timer resolution Δt is:
For N captured edges over M timer ticks, the input frequency becomes:
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:
- Timer resolution: Limited by fclk and prescaler.
- Signal jitter: Noise or irregular edges introduce ±1 count uncertainty.
- Quantization error: Dominates at low frequencies, given by Δf = fclk/(P⋅M).
Advanced Techniques
For high-precision measurements:
- Interrupt-driven timestamping: Record timer values at each edge to compute instantaneous frequency.
- Hardware averaging: Use multiple capture events to reduce quantization noise.
- Reciprocal counting: Measure the period between edges and invert to derive frequency, improving low-frequency accuracy.
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:
- Hardware Chaining: The overflow signal of one timer triggers the increment of another. This method minimizes CPU overhead but requires specific microcontroller support (e.g., Timer1 overflow clocking Timer2 in AVR microcontrollers).
- Software Chaining: An interrupt service routine (ISR) increments a secondary counter upon overflow of the primary timer. This approach is more flexible but introduces latency due to ISR execution time.
Mathematical Derivation of Extended Range
When two n-bit timers are chained, the combined count range becomes:
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:
The maximum measurable time interval Tmax becomes:
Practical Implementation Considerations
Chaining introduces trade-offs between resolution and latency:
- Synchronization Errors: In software chaining, ISR latency causes a slight undercounting. The error E is bounded by the ISR response time tISR:
$$ E \leq t_{ISR} \times f_{clk} $$
- Power Consumption: Hardware chaining keeps peripherals active, while software chaining allows sleep modes between overflows.
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.
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:
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:
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:
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:
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.
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:
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:
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:
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:
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 ...