</>EmbeddedInterview

What is input capture and how do you measure a frequency with it?

MediumMicrocontrollers & ARM Cortex-M

Short answer: In input capture mode, a timer copies (latches) its counter value into a capture register when a selected edge occurs on an input pin, and can raise an interrupt or DMA request. Capturing two consecutive rising edges gives the period in timer ticks: period = c2 − c1 (computed with unsigned arithmetic so one counter wrap is handled automatically). Frequency = timer clock ÷ period.

static volatile uint16_t last;
static volatile uint32_t period_ticks;

void TIM3_IRQHandler(void)
{
    if (TIM3->SR & TIM_SR_CC1IF) {
        uint16_t now = (uint16_t)TIM3->CCR1;        /* reading CCR1 clears CC1IF */
        period_ticks = (uint16_t)(now - last);      /* 16-bit wrap-safe difference */
        last = now;
    }
}

/* f = timer_clk / period_ticks, e.g. 1 MHz / 2500 = 400 Hz */

Handling long periods: if the period can exceed one counter cycle (65,536 ticks for a 16-bit timer), count overflows in the update interrupt and add overflows × 65536, being careful when an overflow and a capture happen close together. Or use a 32-bit timer, or a larger prescaler (less resolution).

Measuring duty cycle (PWM input mode): map one input to two capture channels, one capturing on rising and one on falling edges, with the timer reset on each rising edge (slave reset mode). Then CCR1 = period and CCR2 = high time.

Choosing a method by frequency

Signal Best method Why
Low frequency (Hz–kHz) input capture (period measurement) high resolution from many timer ticks per period
High frequency (100 kHz–MHz) counting edges in a fixed gate time (timer in external clock mode) many edges per gate → good accuracy
Very short pulses capture with input filter disabled and a fast timer clock resolution = 1 timer tick

Accuracy: ±1 tick quantisation error per measurement; average several periods for better precision. Input filters (digital filters on the capture input) reject glitches.

Uses: reading encoder or hall-sensor speed, ultrasonic distance sensors (echo pulse width), RC receiver pulse widths, IR remote decoding, measuring a crystal's frequency against a reference.