UNIT 08 · LESSON 5 OF 6

Measuring Pulses with Input Capture

How can the timer itself tell you exactly when each edge happened?

INTERACTIVEMeasuring a period with input capture
An input signal with two capture events and the resulting period measurementinputcapture 1capture 2N = f_tick / f = 1 MHz / 1 kHz ≈ 1 000 ticks per periodmeasured f = 1 MHz / 1 000 = 1 kHz, uncertain by about 1/N = 0.1 %Fine resolution: one period is enough.
An input signal with two capture events and the resulting period measurementinputcapture 1capture 2N = f_tick / f = 1 MHz / 1 kHz ≈ 1 000 ticks perperiodmeasured f = 1 MHz / 1 000 = 1 kHz, uncertain byabout 1/N = 0.1 %Fine resolution: one period is enough.

Try this

Input frequency
Timer tick
N = 1 000 ticks; f = 1 kHz ± 0.1 %.

On each rising edge of the input, the timer copies its counter into a capture register. The difference between two captures is the period in ticks, N; the frequency is f_tick/N. Each capture is exact to one tick, so N can be off by one: the relative error is about 1/N, which is small for slow signals and large for fast ones.

What you will be able to do
  • Compute a period, frequency and pulse width from captured counter values, including across a counter wrap.
  • Estimate the resolution of a capture measurement and improve it with a faster tick or a capture prescaler.
  • Choose between reciprocal (period) measurement and gate (edge-count) measurement for a given frequency.
  • Explain what an input filter and edge selection do and when to use them.
  • Measure pulse width and duty cycle with captures on both edges.
Before you start
  • Timer ticks and periods (lesson 2) and wrap-safe subtraction (lesson 3).
  • Logic analyser sampling limits (unit 6, lesson 5).
Steps in this lesson
  1. Capture: the timer timestamps the edge
  2. Resolution is one tick
  3. Timing periods versus counting edges
  4. Clean inputs, right edges
  5. Worked example: an RC receiver pulse
  6. Common misconceptions

The puzzle

A flow sensor outputs pulses whose frequency is proportional to flow, somewhere between 5 Hz and 20 kHz. An RC receiver sends a 1–2 ms pulse every 20 ms whose width is the stick position. Polling the pin in a loop gives numbers that jitter with every other task. How can the timer itself tell you exactly when each edge happened?

STEP 1

Capture: the timer timestamps the edge

An input-capture channel watches a pin. On the selected edge, the timer copies its counter value into the channel’s capture register at that instant and raises a flag or interrupt. Software reads the timestamp later, whenever it gets round to it; the latency no longer matters because the time was recorded in hardware.

Two captures on rising edges give the period in ticks, and so the frequency:

N=capture2−capture1(mod2n),N = \text{capture}_2 - \text{capture}_1 \pmod{2^{n}}, f=ftickNf = \frac{f_{\text{tick}}}{N}

The subtraction is the wrap-safe unsigned difference of lesson 3, correct as long as the counter free-runs over its full 2ⁿ range (on an STM32, ARR at its maximum; otherwise the difference is taken modulo ARR + 1) and the period is shorter than one wrap. In C, cast the result back to the counter width: (uint16_t)(c2 - c1), because the subtraction itself is done in int. Capturing on both edges gives the high time too, and with it the pulse width and duty cycle.

↑ This step uses the figure at the top of the page.

STEP 2

Resolution is one tick

Each capture is exact to one tick, so N can be off by one: the relative uncertainty is about 1/N. That is excellent for slow signals (a 1 kHz signal on a 1 MHz tick gives N = 1000, 0.1 %) and poor for fast ones (250 kHz gives N = 4, 25 %). Three remedies:

  • a faster tick (a smaller prescaler), limited by counter overflow for slow signals;
  • a capture prescaler, which captures only every 2nd, 4th or 8th edge, so one difference spans several periods;
  • counting edges instead, over a fixed gate time.

STEP 3

Timing periods versus counting edges

Gate counting counts input edges during a fixed time T (on the RP2040, a PWM slice can count edges of its B pin). The count is off by up to one edge, an error of 1/(f·T), which is small for fast signals. Reciprocal counting, capturing one period, has an error of f/f_tick, small for slow ones. For a single-period reciprocal measurement against a gate of T seconds, they cross where

f=ftickTf = \sqrt{\frac{f_{\text{tick}}}{T}}

A reciprocal measurement that spans many periods (a capture prescaler, or capturing over about T) has an error of about 1/(f_tick·T) and beats gate counting at every frequency below f_tick; that is how precision frequency counters work.

INTERACTIVECount edges or time periods?
Relative error of gate counting and reciprocal counting against input frequency1 Hz1 kHz1 MHz100 %10⁻⁴10⁻⁸orange: gate counting · teal: reciprocalCrossover at √(10 MHz / 100 ms) = 10 kHz, where both errors are 0.1 %. Below it, timeperiods; above it, count edges. Error on the vertical axis runs from 100 % at the topto 10⁻⁸ at the bottom.
Relative error of gate counting and reciprocal counting against input frequency1 Hz1 kHz1 MHz100 %10⁻⁴10⁻⁸orange: gate counting · teal: reciprocalCrossover at √(10 MHz / 100 ms) = 10 kHz, where botherrors are 0.1 %. Below it, time periods; above it,count edges. Error on the vertical axis runs from100 % at the top to 10⁻⁸ at the bottom.
Timer tick (reciprocal)
Gate time (gate counting)
Crossover 10 kHz; error there 0.1 %.

Two ways to measure frequency. Gate counting counts input edges during a fixed gate time T: the count is off by up to one edge, an error of 1/(f·T), good for fast signals. Reciprocal counting times one period with a fast tick: an error of f/f_tick, good for slow signals. They are equally good where the two errors meet, at f = √(f_tick/T).

STEP 4

Clean inputs, right edges

Real signals ring and bounce. Timer inputs typically offer a digital filter that accepts an edge only after the new level has been stable for a number of samples, and edge selection (rising, falling or both). A capture triggered by noise records a nonsense period; filter the input, or reject captures whose period is outside the physically possible range.

STEP 5

Worked example: an RC receiver pulse

A timer ticks at 1 MHz (PSC chosen for a 1 µs step) and captures both edges of the receiver signal. The rising edge captures 12 000, the falling edge 13 502:

thigh=13 502−12 000=1502 μst_{\text{high}} = 13\,502 - 12\,000 = 1502\ \mu\text{s}

slightly off centre (1.5 ms is centre), resolved to 1 µs out of the 1000 µs range: 0.1 %. If the counter wraps between the edges (rise at 65 000, fall at 964 on a 16-bit counter), the unsigned 16-bit difference still gives (964 − 65 000) mod 65 536 = 1500 µs, because the pulse is shorter than one wrap (65.5 ms).

MYTHS AND FACTS

Common misconceptions

The capture time is when the interrupt runs

It is the counter value at the edge; the interrupt only tells you it is ready.

A faster tick is always better

For slow signals the counter overflows between captures; you then need an overflow count or a slower tick.

Timing a single period is best for all frequencies

Above the crossover, counting edges over a gate time is more precise, unless the capture spans many periods.

Every captured edge is a real one

Without filtering, ringing and noise produce extra captures.

Check yourself

Answer in your head, then open the card.

With a 10 MHz tick, two rising-edge captures are 20 000 and 45 000. What is the input frequency and its resolution?

N = 25 000 ticks, f = 10 MHz / 25 000 = 400 Hz, resolution about 1/25 000 = 0.004 %.

A 16-bit timer at 84 MHz measures a 50 Hz signal. What goes wrong?

One period is 84 MHz / 50 = 1 680 000 ticks, far more than 65 536: the counter wraps many times between captures. Use a prescaler (for example PSC = 31, giving 52 500 ticks per period) or a 32-bit timer.

With a 100 MHz tick and a 1 s gate, where is the crossover between gate and reciprocal counting, and what is the error there?

√(100 MHz / 1 s) = 10 kHz; error 1 / √(10⁸ × 1) = 10⁻⁴, 0.01 %.

The rising edge of a pulse is captured at 64 900 and the falling edge at 350 on a 16-bit counter ticking at 1 MHz. How long is the pulse?

(350 − 64 900) mod 65 536 = 986 ticks: 986 µs.

Sources (3)
  1. STMicroelectronics, stm32f4xx-hal-driver, Inc/stm32f4xx_hal_tim.h — TIM_IC_InitTypeDef: ICPolarity (TIM_ICPOLARITY_RISING, FALLING, BOTHEDGE: “Capture triggered by both rising and falling edges”); ICPrescaler (TIM_ICPSC_DIV1 “Capture performed each time an edge is detected”, DIV2, DIV4, DIV8 “once every 8 events”); ICFilter 0x0–0xF
  2. Raspberry Pi Ltd, pico-sdk 1.5.1, hardware_pwm/pwm.h — a slice can “measure the frequency or duty cycle of an input signal”: PWM_DIV_B_HIGH “Fractional divider is gated by the PWM B pin”, PWM_DIV_B_RISING / B_FALLING advance on each edge of the B pin
  3. sigrok, libsigrokdecode, decoders/uart/pd.py — the same quantisation seen from a logic analyser: every edge is known only to one sample period (unit 6, lesson 5)