Home / Learn Chip Programming / Input Capture: Measuring Frequency and Pulse Width

Input Capture: Measuring Frequency and Pulse Width

Use a timer to timestamp edges and measure signals precisely.

In shortUse a timer to timestamp edges and measure signals precisely.

Theory in plain words

Measure periodEdge 1: capture C1Edge 2: capture C2delta = C2 - C1f = Fclk / delta
Measure period

What it is

Input capture latches the timer counter at the moment an edge arrives. The difference between two captures is the period or pulse width.

Why we use it

Software polling misses fast edges. Hardware capture is exact: RPM sensors, ultrasonic distance, remote control receivers, frequency meters.

How it works

Configure a timer to count at a known rate, select the input edge, enable capture interrupt/DMA. Period = (capture2 - capture1) / timer clock.

Where it is used

  • Frequency counter, tachometer
  • HC-SR04 ultrasonic distance
  • RC receiver PWM, IR protocols

Frequency meter

Capture two rising edgesTry it Yourself

Resolution depends on ticks per period: slow clock with fast signal gives big errors. For low frequencies a 16 bit timer may overflow: count overflows too.

Capture ISR (concept)
volatile uint32_t last, period; volatile bool ready;
void TIM2_IRQHandler(void) {
    uint32_t now = TIM2->CCR1;               // value latched by hardware at the edge
    period = (uint16_t)(now - last);         // 16 bit subtraction handles wrap
    last = now; ready = true;
}
Tip:Use unsigned subtraction: (uint16_t)(now - last) is correct even when the counter wrapped between edges.

Quick quiz

1. Period from two captures?

2. Why hardware capture?

Common questions

Period from two captures?

C2 - C1 divided by clock. Ticks between edges times tick time.

Why hardware capture?

Exact timestamps without CPU polling. Hardware latches at the edge.