---
title: Capturing time and counting motion
heading: Input capture, frequency measurement and quadrature encoders
eyebrow: C12 · Lesson 13 · Capturing time and counting motion
xp: 40
---

::: hook
Plenty of sensors report their reading as time rather than voltage: an ultrasonic rangefinder's echo delay, a flow meter's pulse rate, a fan's tachometer, the A and B channels of a motor's encoder. Measuring them well is a matter of reading a timer at exactly the right moment. A hardware **input capture** copies the timer's count into a register on the edge itself; the same job done in an interrupt adds the interrupt's latency and jitter. This lesson works out what resolution each method gives, and how a quadrature encoder reports both position and direction with two square waves.
:::

::: play
- A quadrature encoder makes two square waves, A and B, a quarter cycle apart. Which one leads tells the direction.
- Flip the direction: B now leads A. Each of the four edges per cycle moves the count by one, up or down.
- The readout is the edge rate a decoder must keep up with: four times the pulses per revolution times the revolutions per second.
:::

```sim plot
view: graph
x: t = 0..1 s
y: v = -0.2..2.8
samples: 4000
slider: f = 1..8 step 1 = 3 Hz
slider: d = -1..1 step 2 = 1
plot: 1.5 + step(sin(2*pi*f*t)) | label: A
plot: step(sin(2*pi*f*t - d*pi/2)) | label: B
readout: edges per second = 4*f | digits: 3
```

::: predict
## A 500-line encoder on a motor at 3000 rpm is decoded in software, one 50-cycle interrupt per edge, on the 10 MHz board. How much of the processor does that take?

- [ ] About 1%
- [ ] About 10%
- [x] About half
- [ ] More than all of it

::: reveal
3000 rpm is 50 revolutions a second; four edges per line make 2000 counts a revolution, 100,000 edges a second. At 50 cycles each that's 5 million cycles a second, half the processor. That's why microcontrollers meant for motors have hardware quadrature decoders that count without interrupting at all.
:::
:::

::: nameit
## Input capture

On a chosen edge, the timer's count is copied into a capture register. The time between two captures is their difference (modulo the counter's length, as in the timers lesson), so a period of N counts at $f_\text{clk}$ gives
$$f = \frac{f_\text{clk}}{N}, \qquad \Delta f \approx \frac{f}{N}$$
for ±1 count of uncertainty. A software capture (reading the timer in an edge interrupt) adds the interrupt's latency to each reading, and its variation adds jitter.

## Counting or timing

Counting edges for a gate time $T$ resolves $1/T$ Hz; timing one period resolves $f^2/f_\text{clk}$. They're equal at $f = \sqrt{f_\text{clk}/T}$; above it, count; below it, time.

## Quadrature encoders

Two channels a quarter cycle apart. Counting every edge of both (**4× decoding**) gives $4 \times \text{PPR}$ counts a revolution, where PPR is the pulses (lines) per revolution. The state sequence 00, 01, 11, 10 one way and its reverse the other way give direction; a jump of two states means an edge was missed.

## Speed

Counting edges over a fixed window works at high speed; at low speed only a few counts arrive per window and the resolution is poor, so firmware switches to timing the interval between edges.
:::

::: example
## A capture timer at 10 MHz records edges 25,000 counts apart. What is the frequency, and how finely is it resolved?

::: solution
1. **Frequency.**
   $$\begin{aligned} f &= \frac{10^7}{25\,000}\ \text{Hz} \\ &= 400\ \text{Hz} \end{aligned}$$
2. **Resolution.** One count in 25,000 is $4 \times 10^{-5}$ of the reading:
   $$400 \times 4 \times 10^{-5} = 0.016\ \text{Hz}$$
   so ±0.016 Hz.
3. **Compare with counting edges.** Counting edges for 1 s would only resolve 1 Hz; at this frequency timing is about 60 times finer.

**Answer:** 400 Hz, resolved to ±0.016 Hz.
:::
:::

::: example
## An ultrasonic rangefinder's echo returns 5.83 ms after the ping. How far is the target, and what distance does one 100 ns timer count represent?

::: solution
1. **Distance.** Sound travels out and back at 343 m/s, so halve the round trip:
   $$\begin{aligned} d &= \frac{343 \times 5.83 \times 10^{-3}}{2}\ \text{m} \\ &= 1.000\ \text{m} \end{aligned}$$
2. **One count.**
   $$\begin{aligned} \Delta d &= \frac{343 \times 100 \times 10^{-9}}{2}\ \text{m} \\ &= 17\ \mu\text{m} \end{aligned}$$
3. **Compare with the echo.** That's far finer than the echo's own uncertainty, which is set by the sound's rise time and the air's temperature (0.18% per °C).

**Answer:** the target is 1.000 m away, and one count is 17 µm.
:::
:::

::: example
## A 500-line encoder is counted in 4× mode over 10 ms windows. What speed gives 1000 counts per window, and what is the resolution at 1 rev/s?

::: solution
1. **Counts per second.** 1000 counts in 10 ms is 100,000 counts/s.
2. **Speed.** Over 2000 counts a revolution:
   $$\begin{aligned} \frac{100\,000}{2000} &= 50\ \text{rev/s} \\ &= 3000\ \text{rpm} \end{aligned}$$
   resolved to 0.1%.
3. **At 1 rev/s.** Only 20 counts arrive per window, so a single count is 5% of the reading.
4. **A better method there.** Timing the interval between edges does far better.

**Answer:** 50 rev/s, 3000 rpm, gives 1000 counts per window, resolved to 0.1%; at 1 rev/s a single count is 5% of the reading.
:::
:::

::: check
kind: parts
given: N = 2500 | 25000 | 400000; c = 1 | 10

## A capture timer at {c} MHz records edges {N} counts apart.

::: part
answer: c*1e6/N
unit: Hz
tolerance: 0.5%

### What is the signal's frequency?

::: misses
- [any] $f_\text{clk}/N$.
:::
:::

::: part
answer: c*1e6/N/N
unit: Hz
tolerance: 0.5%

### What is the resolution for ±1 count?

::: misses
- [any] $f/N$.
:::
:::
:::

::: check
kind: parts
given: P = 100 | 500 | 1024; r = 600 | 3000 | 6000; c = 30 | 50 | 80

## A {P}-line encoder, decoded 4×, turns at {r} rpm; each edge costs a {c}-cycle interrupt at 10 MHz.

::: part
answer: 4*P*r/60
unit: edges/s
tolerance: 0.5%

### How many edges arrive per second?

::: misses
- [P*r/60] 4× decoding counts every edge of both channels.
- [any] $4 \times \text{PPR} \times$ rev/s.
:::
:::

::: part
answer: 4*P*r/60*c/1e7*100
unit: %
tolerance: 0.5%

### What share of the processor does decoding take?

::: misses
- [any] Edge rate × cycles ÷ clock.
:::
:::
:::

::: check
kind: parts
given: n = 20 | 150 | 1000; P = 256 | 500; w = 5 | 10 | 20

## A {P}-line encoder in 4× mode gives {n} counts in a {w} ms window.

::: part
answer: n/(4*P)/(w/1000)*60
unit: rpm
tolerance: 0.5%

### What is the speed?

::: misses
- [any] Counts ÷ (4 PPR) ÷ window, times 60.
:::
:::

::: part
answer: 100/n
unit: %
tolerance: 0.5%

### What fraction of the reading is one count?

::: misses
- [any] 1/n.
:::
:::
:::

::: check
kind: parts
given: t = 0.583 | 5.83 | 23.3; T = 0 | 20 | 35

## An ultrasonic echo returns {t} ms after the ping, in air at {T} °C, where sound travels at $331.3 + 0.606T$ m/s.

::: part
answer: (331.3 + 0.606*T)*t/1000/2*100
unit: cm
tolerance: 0.5%

### How far away is the target?

::: misses
- [(331.3 + 0.606*T)*t/1000*100] The sound travels there and back.
- [any] $vt/2$.
:::
:::

::: part
answer: (331.3 + 0.606*T)*1e-7/2*1e6
unit: µm
tolerance: 0.5%

### What distance does one 100 ns count represent?

::: misses
- [any] $v \times 100\text{ ns}/2$.
:::
:::
:::

::: check
kind: parts
given: c = 1 | 10 | 100; T = 0.1 | 1

## A frequency is measured either by counting edges for {T} s or by timing one period with a {c} MHz clock.

::: part
answer: sqrt(c*1e6/T)
unit: Hz
tolerance: 0.5%

### Above what frequency is counting better?

::: misses
- [any] $\sqrt{f_\text{clk}/T}$.
:::
:::

::: part
answer: 1/T
unit: Hz
tolerance: 0.5%

### What does counting resolve?

::: misses
- [any] $1/T$.
:::
:::
:::

::: check
kind: parts
given: p = 0 | 9 | 99; b = 16 | 24

## A {b}-bit capture timer runs at $10^7/(\text{PRESCALE} + 1)$ Hz with PRESCALE = {p}.

::: part
answer: 2^b*(p + 1)/1e7*1000
unit: ms
tolerance: 0.5%

### What is the longest period it can time without counting overflows?

::: misses
- [any] $2^b$ counts.
:::
:::

::: part
answer: (p + 1)/1e7*1e9
unit: ns
tolerance: 0.5%

### What is its resolution?

::: misses
- [any] One count.
:::
:::
:::

::: check
kind: order

## A quadrature encoder turns in the direction where A leads B. Starting from A = 0, B = 0, put the states (A, B) in the order they appear.

1. (0, 0)
2. (1, 0)
3. (1, 1)
4. (0, 1)

::: misses
- [any] A changes first, then B follows a quarter cycle later.
:::
:::

::: check
kind: python

## Write `decode(states)`: `states` is a list of (A, B) pairs sampled from an encoder. Return (count, errors), where the count goes up by one for each step in the order 00 → 10 → 11 → 01 → 00, down by one for each step the other way, doesn't change when the state repeats, and a jump of two states adds one to errors instead.

```python starter
def decode(states):
    return (0, 0)
```

```python solution
ORDER = {(0, 0): 0, (1, 0): 1, (1, 1): 2, (0, 1): 3}

def decode(states):
    count = errors = 0
    prev = ORDER[tuple(states[0])]
    for s in states[1:]:
        cur = ORDER[tuple(s)]
        d = (cur - prev) % 4
        if d == 1:
            count += 1
        elif d == 3:
            count -= 1
        elif d == 2:
            errors += 1
        prev = cur
    return (count, errors)
```

```python tests
fwd = [(0, 0), (1, 0), (1, 1), (0, 1)] * 5 + [(0, 0)]
assert decode(fwd) == (20, 0), "Five full cycles forward: 20 counts."
assert decode(fwd[::-1]) == (-20, 0), "The same backward: −20."
assert decode([(0, 0), (0, 0), (1, 0), (1, 0), (1, 1)]) == (2, 0), "Repeated samples don't count."
assert decode([(0, 0), (1, 1), (0, 1)]) == (1, 1), "00 to 11 skips a state: an error, then 11 to 01 counts one."
```

::: right
Right. A lookup on the change of state is exactly what a hardware decoder does, and the error count tells you the sampling was too slow.
:::
:::

::: explain
## Why does measuring a low frequency by timing one period give much better resolution than counting edges for a second?

::: model
Counting edges in a fixed gate can only be wrong by one edge, but at a low frequency one edge is a large fraction of the total: a 10 Hz signal counted for a second gives 10 ± 1, a 10% uncertainty. Timing a single period instead counts the fast reference clock between two edges of the signal, and at 10 Hz that's a million counts of a 10 MHz clock, so one count of error is a millionth. The slower the signal, the more clock counts fit in its period and the better timing does; counting edges only wins at frequencies above the square root of the clock rate over the gate time.
:::
:::

::: practice
::: check
given: N = 1000 | 40000; c = 1 | 10
answer: c*1e6/N
unit: Hz
tolerance: 0.5%

## Frequency from captures {N} counts apart at {c} MHz?

::: misses
- [any] $f_\text{clk}/N$.
:::
:::

::: check
given: P = 200 | 1000; r = 1200 | 9000
answer: 4*P*r/60
tolerance: 0.5%

## Edges per second for a {P}-line encoder at {r} rpm, 4× decoding?

::: misses
- [any] $4 \times \text{PPR} \times \text{rpm}/60$.
:::
:::

::: check
given: t = 0.5 | 1 | 2 | 3 | 5 | 12 | 20
answer: 343*t/1000/2*100
unit: cm
tolerance: 0.5%

## Distance for an echo after {t} ms at 343 m/s?

::: misses
- [any] $vt/2$.
:::
:::
:::
