Hardware Timestamps

An edge on a pin happens once. A stamp taken inside an interrupt arrives 0.1 to 40 µs late, and the delay changes every time. Let the timer hardware read the clock, and the error shrinks to one tick.

Learn why the moment you read a clock is not the moment something happened, how a timer latches the count by itself, and how frame-sync pins and trigger fan-out make several sensors sample at the same instant.

Pick a load, then press New 2,000 edges a few times. Watch the warm software stamps spread to the right while the blue hardware stamps stay in one place. Then we build, piece by piece, everything underneath: the interrupt delay, the capture register, the DMA and PPI paths, the camera trigger and the fan-out to many sensors.

You need the idea of a timer that counts clock ticks and an interrupt that runs a function. We teach both again in short form, and build the rest from zero.

Part of the series Firmware from Zero to Expertise, time-sync track, lesson 2. Built from primary sources: the STM32F446 reference manual RM0390, Arm’s interrupt-latency guide, Nordic’s nRF52 product specification, the Luxonis hardware-sync guide and the Linux V4L2 documentation (full list in Chapter 9). The device models are teaching models, not measurements of a real board.

Stamp 2,000 edges two ways

A model, not a measurement. The ISR stamp costs 12 cycles of Cortex-M4 interrupt entry (Arm, zero wait states) plus 0 to 3 flash wait-state cycles, 8 cycles of handler code and a 1-cycle synchronizer, all at 180 MHz (STM32F446). The blocked share and the 8 to 40 µs bursts are illustrative. The capture stamp is quantized by an assumed 90 MHz timer tick (11.1 ns).

Chapter 0

A Stamp Is Not the Event

See why the moment your code reads a clock is later than the moment something happened, and by how much

A small board carries an inertial sensor (an IMU, a chip that measures turning and pushing). Every millisecond the sensor has a new reading. It tells the processor by pulling one wire, a pin, from high to low. That change of level is an edge. Your firmware must write down when the edge happened, so that a filter later can line this reading up with a camera frame.

The usual way is simple. The edge raises an interrupt: the hardware stops the code that was running and jumps to a function you wrote, the interrupt service routine (ISR, also called a handler). Inside the ISR you read a clock and save the number. That saved number is a timestamp, a count from a clock stored next to a measurement.

Here is the catch. The number you saved says when your code looked at the clock. It does not say when the edge happened. A letter stamped at the post office tells you when the clerk stamped it, not when you wrote it. The gap between the two is the lateness of the stamp.

Why the gap is never the same twice

If the lateness were a fixed 1 µs (one millionth of a second), you could subtract it and move on. The trouble is that it changes. The processor might be inside another handler when your edge arrives. It might have switched interrupts off for a moment to protect some data. The edge waits. Then your handler runs, and only then does the clock get read.

The next chapters measure each piece. For now, hold on to one idea: a stamp has a size of lateness and a spread. The size you can subtract. The spread you cannot, because you do not know how late any single stamp is. The spread is called jitter, and it is what this lesson fights.

How small must the error be?

It depends on what you track. A spinning lidar (a sensor that measures distance with laser pulses) turning 20 times a second with 1,024 columns per turn makes one column every 48.8 µs, because 1 s divided by 20 and by 1,024 is 48.8 µs. A stamp that is 40 µs late is 82% of one column. Your picture of the wall is smeared by almost a whole column.

A robot moving at 10 m/s travels 10 µm in each microsecond. A 40 µs error is 0.4 mm of position. A camera at 30 frames per second makes one frame every 33,333 µs, so the same 40 µs is 0.12% of a frame and does not matter. The same stamp is fine for one sensor and broken for another. Try it below.

Measure the lateness against the sensor

Top: one edge on a timeline, and the moment the ISR reads the clock. Bottom: that lateness as a share of one sample period. Pick a sensor, then drag the time another handler blocks the processor.

18 µs

Illustrative. The unblocked lateness is 0.12 µs (22 cycles at 180 MHz, built up in Chapter 1). The 1% line is a rule of thumb for this lesson, not a standard: a stamp error under 1% of a sample period usually hides inside the sensor’s own noise.

Notice what the device shows. The same 18 µs is a rounding error for a camera and larger than a whole sample for audio. Before you pick a technique, ask how big a stamp error your system can bear. Chapter 8 gives you a way to turn that into a pass or fail test.

What this lesson builds

You will meet two ways to put a time next to an edge. In the first, software reads the clock: an ISR runs and reads a timer. In the second, hardware reads the clock: a timer copies its own count into a register at the instant of the edge, with no code running at all. The second way moves the clock read from a place that wobbles to a place that does not.

The lesson also turns the idea around. A camera has a frame-sync pin (an input that starts a frame). If your timer sends the pulse, then the time of the pulse is the time of the exposure, and nobody has to guess. We finish with one trigger that fans out to many sensors. Here is the map.

  1. Where the delay comes from: the pieces of ISR lateness, and the long tail.
  2. Input capture: a timer that latches its own count, and the registers that do it.
  3. When edges come faster than you read: overcapture, and DMA as the fix.
  4. Counters wrap: widths, wrap times and unwrapping to a long timeline.
  5. Capture with no CPU: Nordic PPI and chains of hardware hops.
  6. Frame-sync pins: your timer starts the exposure, and what a camera stamp means.
  7. Trigger fan-out: one pulse, many sensors, and their different delays.
  8. Judge by the tail: percentiles, budgets and a loopback test on a real board.
  9. Field guide: numbers, a checklist, the core code and where to go next.

The lesson before this one, What Time Is It on a Chip, covered crystals, drift and counters that wrap. Interrupt entry itself is covered in Interrupts, DMA and the 12 Cycles. We recap the parts we need, in plain words, as we go.

An ISR reads a timer and saves the value as the time of an edge. What does the saved value tell you?

Chapter 1

Where the Delay Comes From

Follow one edge from the pin to the clock read, add up each delay on the way, and see why the typical stamp is fine while the worst one is not

Picture the board: an STM32 Nucleo-F446RE, a Cortex-M4 chip running at 180 MHz (the datasheet limit). One wire from the IMU goes to pin PA0. The wire falls from 3.3 V to 0 V. Your handler is supposed to read the 32-bit timer TIM2 and save the count. How long does the trip take?

At 180 MHz one processor cycle lasts 5.56 ns (1 s divided by 180 million). Everything below is counted in cycles first, then turned into time.

The trip, one hop at a time

Hop 1, the pin synchronizer. The pin can change at any moment, but the chip works on clock ticks. So the chip samples the pin with its own clock. The edge waits for the next sample. In our model that costs between 0 and 1 cycle.

Hop 2, interrupt entry. The interrupt controller (the NVIC, the part of a Cortex-M that ranks and delivers interrupts) tells the core. The core finishes or abandons its current instruction. It then stacks eight registers (it saves r0 to r3, r12, the link register, the program counter and the status register in memory), reads the handler’s address from the vector table and fetches the first instruction. Arm says this takes 12 cycles on a Cortex-M3 or Cortex-M4, if the memory has zero wait states. That is 66.7 ns at 180 MHz.

Hop 3, wait states. Flash memory is slower than the core at high clock speeds, so the chip adds idle cycles, called wait states, to each flash read. Arm notes that wait states add some jitter to the 12-cycle figure. Our model adds 0 to 3 cycles. The exact number depends on the part, the voltage and the cache, so treat it as illustrative.

Hop 4, your own code. The handler must run a few instructions before it reads the counter: maybe it clears a flag first. Say 8 cycles. A shorter path reads the counter first. Put the clock read at the very top of the handler.

Hop 5, waiting for permission. This is the hop that hurts. The NVIC delivers an interrupt only when no higher-priority handler is running and interrupts are not masked. Code can mask them by setting the PRIMASK bit (the instruction cpsid i) to protect shared data, a critical section. A handler that runs for 20 µs, or a critical section that lasts 20 µs, makes the edge wait for the rest of that time. Arm says the same in plain words: interrupt latency is normally a lot worse for low-priority interrupts.

A worked example, every step

  1. Synchronizer: on average 0.5 cycle.
  2. Entry: 12 cycles.
  3. Wait states: on average 1.5 cycles.
  4. Your code before the read: 8 cycles.
  5. Total: 0.5 + 12 + 1.5 + 8 = 22 cycles, and 22 × 5.56 ns = 122 ns.

Every stamp is about 122 ns late, plus or minus 2 cycles (11 ns). That is a good result. Now let a UART handler run at higher priority for 20 µs, and let it be busy 10% of the time. An edge that lands inside the 20 µs window waits for the rest of it. If the handler started 6 µs ago, the edge waits 14 µs and the stamp is 14.12 µs late.

Look at the odds. The edge lands inside a busy window 10% of the time, and then the extra wait is anywhere from 0 to 20 µs. So 90% of the stamps are 122 ns late and 10% are up to 20 µs late. The median (the middle value when you sort all the stamps) stays at 122 ns. The 95th percentile is 10 µs. The 99th is 18 µs. A percentile is the value that a given share of the stamps stay under. The median hides the tail completely.

Add up the hops

Each bar is one hop, on a log time axis from 1 ns to 100 µs, so a 5 ns hop and a 20 µs hop both fit. The bottom bar is the total. Change the code before the read, then add a block and see the bar jump decades.

8 cycles
0 µs

Entry is Arm’s figure for Cortex-M3 and M4 with zero wait states (12 cycles). The synchronizer (0 to 1 cycle), the flash wait states (0 to 3 cycles) and the blocking time are illustrative model values. Cycle times use 180 MHz, the STM32F446 limit.

Two details are easy to miss. First, the four small hops add up to a stable number, so you can measure it once and subtract it. Only the spread, the 11 ns of wait-state and synchronizer wobble, remains. Second, the blocking hop is not stable at all. It depends on what else the firmware is doing right now, so a test on a quiet bench can look perfect and the product can fail in the field.

Tail-chaining does not remove the wait. When one handler ends and another is already pending, a Cortex-M3 or M4 skips the unstack and restack and starts the next handler after about 6 cycles. That helps throughput. It does not help an edge that arrived while the first handler was still running.

Symptom, measurement, fix

Symptom. Your estimate of turn rate shows a rare spike. Nothing looks wrong in the data otherwise. Measurement. Send a known edge from a timer into the pin and log how late the ISR stamp is, thousands of times. Plot the lateness as a histogram, as in the hero. A lump near 122 ns and a thin tail out to tens of microseconds is the signature. Fix. Give the timing interrupt the highest priority, keep every critical section short, or take the clock read out of software. The next chapter does the last one.

An ISR stamp has a median lateness of 0.12 µs, but 1 stamp in 100 is more than 18 µs late. What most likely causes the rare large values?

Chapter 2

Input Capture: The Timer Stamps the Edge

Wire the pin to a timer channel, so the counter value is copied into a register at the instant of the edge, whatever the processor is doing

Think of a stopwatch with a photo-finish camera. A runner crosses the line, and the camera takes a picture of the stopwatch face in that instant. Later, a judge walks over and reads the photo. It does not matter whether the judge walks fast or slow. The photo shows the time of the finish, not the time of the reading.

A timer in a microcontroller is that stopwatch. It holds a counter (on STM32 the register TIMx_CNT) that goes up by one on every tick of the timer clock. When the count reaches a limit set in TIMx_ARR, it falls back to zero and starts again. Plotted over time, the count looks like a saw: a ramp, a drop, a ramp.

An input capture channel is the photo-finish camera. You connect a pin to the channel and pick an edge, rising or falling. Each timer has a capture/compare register for the channel, TIMx_CCR1 for channel 1. When the chosen edge arrives, the hardware copies the counter into CCR1. No instruction runs. The ST reference manual for the STM32F446 (RM0390) says it plainly: the capture registers “are used to latch the value of the counter after a transition detected by the corresponding ICx signal”.

Then the hardware sets a flag, CC1IF in the status register TIMx_SR. If you enabled it, the flag also raises an interrupt (the enable bit is CC1IE) or a DMA request (the bit CC1DE, Chapter 3). Your ISR can now run 40 µs late and nothing is lost: the number in CCR1 is still the time of the edge. The time of the stamp and the time of the read have come apart. That is the whole trick.

The setup, register by register

RM0390 lists the steps to capture on a rising edge of input TI1. We follow them. Each step names a bit field.

  1. Choose the input. Write CC1S = 01 in TIMx_CCMR1. Channel 1 becomes an input fed from TI1, and CCR1 becomes read-only.
  2. Choose a filter. Write IC1F in the same register. The manual’s example is 0011: a transition counts only after 8 consecutive samples, taken at the timer clock fCK_INT, show the new level.
  3. Choose the edge. Write CC1P = 0 and CC1NP = 0 in TIMx_CCER for a rising edge.
  4. Choose the prescaler. Write IC1PS = 00 to capture every valid edge (a larger value captures every 2nd, 4th or 8th).
  5. Turn it on. Set CC1E in TIMx_CCER. Then set CC1IE or CC1DE in TIMx_DIER if you want an interrupt or a DMA request.

The filter, in plain words

A real wire is noisy. A brief spike can look like an edge. The input filter is a small counter. It samples the pin on every tick and passes a change on only after N samples in a row agree. A spike shorter than N samples never gets through. That is good for clean stamps.

The price is delay. The edge is confirmed N samples after it arrived, so the stamp is late by N ticks. But that delay is the same every time. You measure it once and subtract it. Only the quantization stays as jitter.

A worked example, every step

Take the timer clock to be 90 MHz, a value we assume here (read yours from the clock tree of your own chip). One tick is 11.11 ns. Let the prescaler be 0, so the counter ticks at the full clock, and let the count read 90,000 at the moment 1,000.000 µs on our wall clock.

  1. The true edge arrives at 1,000.005 µs. That is 0.005 µs after tick 90,000, which is 0.45 of a tick.
  2. With no filter, the next tick that sees the new level is tick 90,001. The hardware latches CCR1 = 90,001.
  3. Turn that count back into time: 90,001 ÷ 90 MHz = 1,000.0111 µs. The stamp is late by 6.1 ns, which is 0.55 of a tick.
  4. Now switch the filter to IC1F = 0011 (N = 8). We model it as 8 more ticks before the edge is confirmed, so CCR1 = 90,009 and the stamp reads 1,000.1 µs.
  5. That is late by 95 ns. Eight ticks (88.9 ns) of it are a constant you subtract. The other 6.1 ns is quantization, and it varies between 0 and one tick.

Whatever the edge time, the lateness lies between N and N + 1 ticks. So the jitter of an input-capture stamp is one tick: 11.1 ns here. Compare that with the 18 µs tail of Chapter 1. Try it below, then add a glitch and watch the filter work.

Latch the counter on an edge

Top: the pin. Bottom: the counter, one step per tick. The purple marker is the value copied into CCR1. Drag the edge time inside one tick and watch CCR1 step. Choose a filter, and switch on the glitch.

+45 ns

Model: 90 MHz timer clock (assumed, 11.11 ns per tick); count 90,000 at 1,000.000 µs; the edge is latched at the next tick plus N ticks. A filter sample that sees the glitch counts toward N. Real chips add a pin and synchronizer delay of about a tick or two that you measure once on the bench (Chapter 8). Register names and the N = 8 example are from RM0390, section 17.3.5.

With no filter, the glitch is captured as the edge, and the stamp is about 60 ns early. With N = 2 the glitch is 2.7 ticks wide, so two samples in a row still see it and it still gets through. With N = 4 or more it is rejected. Pick N a little longer than the longest glitch you expect, and no longer: each extra tick of N is a tick of constant delay, and a filter that is too long can swallow a real short pulse.

Reading the result

In the ISR, read CCR1. The manual says reading it also clears CC1IF. Push the value into a ring buffer and leave. Do the heavy work elsewhere. The listing below is the whole setup for the Nucleo-F446RE. Pin PA0 is TIM2 channel 1 through alternate function 1; confirm that in the alternate-function table of your datasheet.

c/* STM32F446, TIM2 CH1 on PA0 (AF1), 32-bit free-running count, rising edge */
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;  RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
GPIOA->MODER  = (GPIOA->MODER & ~(3u<<0)) | (2u<<0);       /* PA0: alternate function */
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFu<<0)) | (1u<<0); /* AF1 = TIM2 */

TIM2->PSC   = 0;                              /* count at the full timer clock */
TIM2->ARR   = 0xFFFFFFFFu;                   /* 32-bit: wraps after 2^32 ticks */
TIM2->CCMR1 = (1u << TIM_CCMR1_CC1S_Pos)       /* CC1S=01: IC1 on TI1, CCR1 read-only */
          | (0u << TIM_CCMR1_IC1F_Pos);      /* IC1F=0000 (use 0011 for N=8) */
TIM2->CCER  = TIM_CCER_CC1E;                 /* rising edge: CC1P=CC1NP=0; enable capture */
TIM2->DIER  = TIM_DIER_CC1IE;                /* interrupt on capture (CC1DE would ask for DMA) */
TIM2->CR1   = TIM_CR1_CEN;                   /* start counting */
NVIC_EnableIRQ(TIM2_IRQn);

void TIM2_IRQHandler(void) {
    if (TIM2->SR & TIM_SR_CC1IF) {
        uint32_t t = TIM2->CCR1;           /* the time of the EDGE, not of this line; also clears CC1IF */
        ring_push(t);
    }
}
On real hardware. Board: STM32 Nucleo-F446RE. Wire the board’s own PWM output (for example TIM3 channel 1 on another pin, at 1 kHz) to PA0 with a jumper. Capture it, and print the difference between successive CCR1 values. At a steady 1 kHz the difference should read 90,000 ticks (if your timer clock is 90 MHz) every time, to within a tick or two. Then run a busy loop in a higher-priority interrupt and see that the capture differences do not change.
Input capture with the filter set to N = 8 stamps an edge 95 ns late, every time, plus or minus one tick. What should firmware do with the 95 ns?

Chapter 3

When Edges Come Faster Than You Read

Learn what happens to a stamp that waits in the capture register, and how a DMA transfer saves it

Back to the photo-finish camera. It keeps one photo only. If a second runner crosses the line before the judge has looked at the first photo, the camera takes a second picture and the first one is gone. The judge sees one photo and no sign that a runner was missed.

The capture register works the same way. CCR1 holds a single stamp. Suppose a fast pulse train feeds the pin: a toothed wheel passing a sensor, or a 100 kHz pulse from another chip. That is one edge every 10 µs. Your ISR must read CCR1 before the next edge lands, or a stamp is lost.

The overcapture flag

The chip does tell you when this happens. RM0390 says: “If a capture occurs while the CCxIF flag was already high, then the over-capture flag CCxOF (TIMx_SR register) is set.” The flag CC1IF is high from one capture until you read the register. A second capture in that gap raises CC1OF. The manual adds that CCxOF clears when you write it to 0.

The manual also gives an order for reading. It recommends reading the data before the overcapture flag. The reason is a race. If you read the flag first, a new capture could land between the two reads, and you would miss that it happened. Read the data, then the flag. If the flag is set, at least one earlier stamp was lost.

A worked example, every step

Edges arrive every 10 µs: edge A at 0, edge B at 10 µs, edge C at 20 µs. At t = −1 µs another handler starts and masks interrupts for 20 µs, so it ends at 19 µs.

  1. t = 0: edge A. The hardware latches A into CCR1 and sets CC1IF. The interrupt cannot run, so it waits.
  2. t = 10 µs: edge B. CC1IF is still high. The hardware latches B, and sets CC1OF. A is gone.
  3. t = 19 µs: the block ends. The ISR starts 0.12 µs later, at 19.12 µs. It reads CCR1 and gets B.
  4. t = 20 µs: edge C arrives after the read, so C is safe.
  5. Result: one 20 µs block at 100 kHz cost one stamp. A longer block, or a faster pulse train, costs more.

So the rule for interrupts is: the longest time your firmware ever blocks this interrupt, plus the time the handler needs to reach the read, must be shorter than the gap between edges. Otherwise you lose stamps.

DMA: a second pair of hands

DMA (direct memory access) is a separate hardware block that copies data from one place to another without the processor. You set the CC1DE bit in TIMx_DIER. Now every capture raises a DMA request instead of an interrupt. The DMA controller reads CCR1 and writes the value into an array in RAM, then moves to the next slot. The processor never sees the individual edges. It looks at the array when it wants to.

DMA has its own delay between the capture and the copy: it must win the bus, and other DMA streams may be ahead of it. That delay is short and fairly steady, and a masked PRIMASK does not stop it. In our model the copy takes 0.1 to 1.0 µs, an illustrative range. At 200 kHz the gap between edges is 5 µs, so the copy always wins. Try both methods below.

Keep up with the edges

Each tick on the line is an edge. Blue ticks were stamped. Red crosses were overwritten before anyone read them. Yellow bands are blocks, and warm boxes are ISR runs. Raise the edge rate, lengthen the blocks, then switch to DMA.

100 kHz
20 µs

Model: 500 edges at the chosen rate; blocks of the chosen length cover about 10% of the time at random places; an ISR needs 0.12 µs to reach its read and 2 µs to finish; a DMA copy takes 0.1 to 1.0 µs. The block share, the 2 µs and the DMA range are illustrative. The overcapture rule is from RM0390, section 17.3.5.

With the interrupt reader, the lost stamps pile up when blocks are long or edges are fast. With DMA, the blocks do not matter, and stamps are lost only if edges outrun the copy. This is the second reason hardware capture wins: it keeps working while the processor is busy.

The ISR that counts what it lost

Even with DMA you want a safety check. A stamp counter that rises without gaps tells you nothing was lost. An overcapture flag tells you something was. In the interrupt version, read the data, then the flag, then clear the flag. Count the losses and report them; a lost stamp that you never count turns into a silent timing error three layers up.

cvolatile uint32_t lost;

void TIM2_IRQHandler(void) {
    uint32_t t  = TIM2->CCR1;      /* 1. the data first (RM0390's advice); this clears CC1IF */
    uint32_t sr = TIM2->SR;        /* 2. then the flags */
    if (sr & TIM_SR_CC1OF) {
        TIM2->SR = ~TIM_SR_CC1OF;   /* CC1OF clears when you write 0 to it */
        lost++;                    /* at least one earlier edge was overwritten */
    }
    ring_push(t);
}

/* DMA version: one request per capture, no CPU in the path (choose the stream and channel
   from the DMA request-mapping table of your reference manual) */
static uint32_t stamps[256];                 /* the DMA controller fills this ring */
/* DMA: peripheral = &TIM2->CCR1, memory = stamps, 256 items, 32-bit, circular */
TIM2->DIER = TIM_DIER_CC1DE;                 /* a capture now raises a DMA request */
On real hardware. Board: STM32 Nucleo-F446RE. Feed a 100 kHz square wave from a second timer into PA0 by jumper. In the interrupt version, add a loop in a second handler that runs 20 µs with higher priority. Print lost after 10 seconds. Then move to the DMA version, print the stamp differences and check they stay at 10 µs (900 ticks at an assumed 90 MHz).
A 100 kHz pulse train is captured with an interrupt, and another handler blocks interrupts for 20 µs now and then. What happens to the stamps, and what helps?

Chapter 4

Counters Wrap: Making a Long Timeline

Work out how long a counter lasts before it starts over, and turn wrapping stamps into one steady timeline

You log two edges. The first stamp reads 60,000. The second, 1 ms later, reads 18,928. A quick subtraction says the second edge came before the first. Nothing is broken. The counter reached its top, fell back to zero and kept going. The stamp is a position on a circle, not a distance along a line.

Chapter 2 gave the saw shape of a counter. Here we ask how long one lap takes, since that sets how far apart two stamps can be and still be read correctly. The previous lesson met the same bug for an RTC; the capture register brings it back.

How long is a lap?

A counter with N bits holds 2N values. At a tick rate f it laps every 2N ÷ f seconds. At our assumed 90 MHz timer clock:

The ST datasheet for the F446 lists TIM2 and TIM5 as 32-bit and the others as 16-bit. On the Nordic nRF52 family the TIMER peripheral runs at 16 MHz divided by 2PRESCALER, and its BITMODE register picks 8, 16, 24 or 32 bits. At 16 MHz a 32-bit nRF52 timer laps every 268.4 s, and a 16-bit one every 4.096 ms.

You see the trade. A fast tick gives fine resolution and a short lap. A slow tick gives a long lap and coarse stamps. A 32-bit counter gives you both for a modest cost, which is why timing-critical code uses the 32-bit timers for capture when it can.

The subtraction trick

Computers store an unsigned number with a fixed width, and subtraction wraps around the same way the counter does. So the difference (uint32_t)(now − last) is the right number of ticks, even if the counter lapped in between. Try with 16 bits and the example above. The first stamp is 60,000. The second edge is 500 µs later, which is 45,000 ticks at 90 MHz.

  1. The second stamp is (60,000 + 45,000) mod 65,536 = 105,000 − 65,536 = 39,464.
  2. Subtract: 39,464 − 60,000 = −20,536. In 16-bit unsigned arithmetic that is −20,536 + 65,536 = 45,000.
  3. 45,000 ticks ÷ 90 MHz = 500 µs. Right.

Now the gap from the first paragraph: 1,000 µs is 90,000 ticks, more than one lap. The second stamp is (60,000 + 90,000) mod 65,536 = 18,928. The same subtraction gives 18,928 − 60,000 = −41,072, which is 24,464 mod 65,536. That reads as 271.8 µs. The answer is wrong by exactly one lap, 728.2 µs, and nothing in the stamp warns you.

So the trick has one rule: you must see a stamp at least once per lap. If the gap between two stamps can be longer than one lap, you must count laps some other way. The timer sets an update flag (UIF) each time it overflows. An interrupt on that flag can add one to a software counter.

Hide a lap, then count it

The dial is the counter. One full turn is one lap. The hands mark two edges. Choose a counter width, then drag the gap between the edges from 0.1 ms to 100 s and watch for the first lap that goes missing.

1.00 ms

Model: 90 MHz timer clock (assumed), first edge at count 60,000 (16-bit) or 3,000,000,000 (32-bit). The lap times are plain arithmetic: 65,536 ÷ 90 MHz = 728.2 µs and 232 ÷ 90 MHz = 47.72 s. The lap counter assumes its interrupt is never missed.

Turning ticks into time

A long, wrap-free tick count is still not a time. You must convert it. The simplest map is time = offset + ticks × period. You find the offset once, by reading a reference clock and the timer together. But the timer’s clock comes from a crystal, and a crystal is off by some ppm (parts per million). At 20 ppm, 47.72 s of ticks hides 47.72 × 20 × 10−6 = 954 µs of error. The lesson on syncing many MCUs shows how to fit that slope. Here we only record the ticks cleanly.

Symptom, measurement, fix

Symptom. Every so often one interval looks short by a round number: 728 µs, or 47.7 s. Measurement. Print the unwrapped difference between consecutive stamps, and check that it equals your known period every time. Round-number errors point to a lost lap. Fix. Use a 32-bit timer for capture. Add the 64-bit accumulator below. If edges can pause longer than a lap, count laps with UIF.

c/* one stamp at least every 2^32 ticks (47.7 s at an assumed 90 MHz): the unsigned difference is exact */
static uint32_t last32;
static uint64_t t64;                          /* a timeline that does not wrap in your lifetime */

uint64_t unwrap32(uint32_t now) {
    t64   += (uint32_t)(now - last32);      /* modular difference: survives one wrap */
    last32 = now;
    return t64;
}
On real hardware. Board: STM32 Nucleo-F446RE. Capture a 2 kHz signal on TIM3 (16-bit) and on TIM2 (32-bit) at the same time. Print the difference between successive stamps from each. Both print 45,000 ticks (500 µs at 90 MHz) every time. Now slow the signal to 1 kHz. TIM2 prints 90,000. TIM3 prints 24,464, because the 1 ms gap is longer than one 728 µs lap and the printout is off by a whole lap.
TIM3 is a 16-bit timer at an assumed 90 MHz. Two capture stamps are 1 ms apart, and you subtract them with unsigned 16-bit arithmetic. What do you get?

Chapter 5

Capture With No CPU in the Path

Chain an event to a task inside the chip, and learn to tell hops that always take the same time from hops that wait for software

A Bluetooth tag is on your desk. Its radio stack grabs the processor at moments you do not choose, for a few hundred microseconds each time, to answer a radio event. In the middle of one of these an IMU edge arrives. Whatever your code does, it cannot start for a while.

Chapter 2 solved this for one chip family with a timer channel. Other chips solve it with a different part, but the idea is the same. Move the whole path from the pin to the stored count into hardware blocks that run on their own clock. Here we look at the Nordic way.

Events, tasks and the PPI

On a Nordic nRF52 chip, every peripheral exposes two kinds of signal. An event says that something happened: a pin changed, a timer reached a value. A task is something the peripheral can be told to do: start, stop, capture the count. Normally the CPU reads an event and writes a task. The PPI (Programmable Peripheral Interconnect) skips the CPU. In Nordic’s words, it “enables peripherals to interact autonomously with each other using tasks and events independent of the CPU”. You connect one event to one task through a PPI channel.

A stamp chain needs three blocks. GPIOTE (the GPIO tasks and events block) turns a pin edge into an event, EVENTS_IN[n], on a rising edge, a falling edge or any change. A PPI channel links that event to the task TASKS_CAPTURE[c] of a TIMER. The Nordic specification says what that task does: “Every time the CAPTURE[n] task is triggered, the Counter value is copied to the CC[n] register.” It is the same photo-finish camera, built from three separate blocks.

The nRF52 TIMER counts at 16 MHz divided by 2PRESCALER. With PRESCALER = 0 it counts at 16 MHz, one tick per 62.5 ns. Set BITMODE to 32 bits and the lap lasts 268.4 s.

Fixed hops and variable hops

Now look at any stamp path as a chain of hops, steps the signal passes through. Sort the hops into two kinds.

A fixed hop is clocked hardware. Its delay is the same each time, or varies only inside one clock period. The input filter, the PPI link and a timer tick are fixed hops. A variable hop waits on software or on a shared resource. The wait for a free processor is a variable hop. The sum of fixed hops is a constant plus a small spread. One variable hop can add a tail that dwarfs everything else.

That gives a design rule. Stamp the edge at the earliest point where every hop before it is fixed. After that point, software can be as late as it likes, because the stamp is already saved.

Counting the hops, every step

On the nRF52 chain, the Nordic text gives the timing of two hops. A PPI link delays an event that is synchronous to the 16 MHz clock by one clock period, and an asynchronous event by up to one period. One period is 62.5 ns. The timer then stores the count at its next tick, which adds up to another 62.5 ns of quantization. Nordic’s specification gives no delay for the pin-to-event step of GPIOTE, so the model uses zero and the lesson tells you to measure it.

  1. Pin to GPIOTE event: a constant you measure once (Nordic gives no figure for it).
  2. PPI link: 0 to 62.5 ns.
  3. Timer tick quantization: 0 to 62.5 ns.
  4. Total spread: 0 to 125 ns, and the stamp never waits for the CPU.

Compare this with the ISR path of Chapter 1 and the STM32 capture of Chapter 2. Pick each path below and send 400 edges through it. The dots sit on a log axis, so a few nanoseconds and a few microseconds share one picture.

Count the hops on each path

Blue hops are fixed hardware. Warm hops wait for software. Below the hops, each dot is one stamp’s lateness on a log axis from 1 ns to 100 µs. Choose a path, then press Send 400 more edges.

A model, not a measurement. ISR hops: 12-cycle entry from Arm, other values illustrative (Chapter 1), blocked 10% of the time for up to 20 µs. Capture hops: IC1F = 0011 filter of 8 ticks at an assumed 90 MHz, one tick of quantization. PPI hops: one 16 MHz period (62.5 ns) for the PPI link and for the timer tick, from the nRF52 product specification. The pin-to-GPIOTE delay is shown as 0 because Nordic gives none.

Look at where the dots land. The ISR path has a dense cluster and a long tail. The two hardware paths are one tight cluster each. The nRF cluster is wider than the STM32 one, since a 16 MHz timer tick is 62.5 ns and the STM32 tick in our model is 11.1 ns. A hardware path is only as fine as its timer clock. You can raise the clock to shrink the cluster, which you cannot do for a tail.

The same idea in the STM32 world

ST parts chain peripherals too. A timer can trigger a DMA request, and a timer can trigger an ADC conversion, which you saw in the timers lesson. The pattern is always the same: ask what is the earliest hop that is not software, and stamp or act there.

c/* nRF52: pin P0.11 rising edge -> GPIOTE event -> PPI channel 0 -> TIMER1 capture 0 (no CPU) */
NRF_TIMER1->MODE      = TIMER_MODE_MODE_Timer;
NRF_TIMER1->BITMODE   = TIMER_BITMODE_BITMODE_32Bit;
NRF_TIMER1->PRESCALER = 0;                              /* 16 MHz / 2^0 = 16 MHz: 62.5 ns per tick */
NRF_TIMER1->TASKS_START = 1;

NRF_GPIOTE->CONFIG[0] = (GPIOTE_CONFIG_MODE_Event    << GPIOTE_CONFIG_MODE_Pos)
                      | (11                          << GPIOTE_CONFIG_PSEL_Pos)
                      | (GPIOTE_CONFIG_POLARITY_LoToHi << GPIOTE_CONFIG_POLARITY_Pos);

NRF_PPI->CH[0].EEP = (uint32_t)&NRF_GPIOTE->EVENTS_IN[0];       /* event end point */
NRF_PPI->CH[0].TEP = (uint32_t)&NRF_TIMER1->TASKS_CAPTURE[0]; /* task end point */
NRF_PPI->CHENSET  = PPI_CHENSET_CH0_Msk;                              /* switch the channel on */

/* later, whenever software gets around to it: */
uint32_t stamp = NRF_TIMER1->CC[0];      /* the time of the edge; read before the next one overwrites it */
On real hardware. Board: nRF52840 DK. Drive the pin from the board’s own second timer through a jumper, at a known period. Capture with the chain above, and again with a plain GPIOTE interrupt that reads the timer in its handler. Start a long radio or flash operation in the background and compare the two histograms. The chain’s spread stays near two timer ticks (125 ns). The interrupt version grows a tail.
Why does a GPIOTE event wired by PPI to a TIMER capture task give a better stamp than a GPIOTE interrupt that reads the timer?

Chapter 6

Frame-Sync Pins: Your Timer Starts the Exposure

Turn the idea around: send the pulse instead of catching it, and the stamp of the image is known before the picture exists

A robot carries two cameras and an IMU. To find depth, the two cameras must look at the world at the same instant. If one captures 4 ms after the other and the robot is moving at 1 m/s, the robot has moved 4 mm between the two pictures, and the stereo match is wrong by that much.

By default, a camera sensor is a free-running machine. It starts a frame whenever its own clock says so, exposes, reads out and sends the data. Your software learns about the frame when it arrives. The only stamp you can put on it is the arrival time, which is the moment of exposure plus the exposure, plus the readout, plus the transfer, plus the driver. All of that varies.

The frame-sync pin

Many sensors have an input that fixes this. It is called FSIN or FSYNC (frame sync), and vendors also use names such as XVS and TRIGGER. A pulse on that pin tells the sensor to start a frame. The Luxonis hardware-sync guide describes it as “a pulse driven high at the start of each frame capture”, and adds that its width is not proportional to the exposure time. Luxonis says the shared trigger “aligns start of exposure by default”.

Now the stamp problem flips. You do not need to catch an edge. You make the edge, with a timer, at a time you chose. The pulse leaves your chip at tick T, and the exposure begins a short fixed time later. The time of the image is known by construction. We call this a hardware timestamp by construction: no capture register, no ISR, no guess.

Two modes

The page also lists the pin direction for several sensors. The OV9282 and OV9782 accept FSYNC as an input or drive it as an output. The AR0234 takes it as an input only. Because directions differ, one camera can be the master (it drives the pulse out) and the others slaves (they take it in). Or your microcontroller can be the master of all. Read the datasheet of your sensor, and check that the sensor is set to the external-trigger mode, because a free-running sensor ignores the pin.

Luxonis claims that its hardware sync is “typically below 10 microseconds” across sensors on its RVC2 platform. That is a vendor figure for one product. Measure your own build.

Which instant does the stamp mean?

An image is not instant. The sensor collects light for the whole exposure, then reads it out. The picture is an average of the world over the exposure. The most honest single time for it is the middle of the exposure.

Linux names two choices in its V4L2 camera interface. A buffer flag V4L2_BUF_FLAG_TSTAMP_SRC_EOF means the timestamp was taken “when the last pixel of the frame has been received”. The flag V4L2_BUF_FLAG_TSTAMP_SRC_SOE means it was taken “when the exposure of the frame has begun”. A third flag says the clock is CLOCK_MONOTONIC. Check which one your driver sets before you trust a stamp.

Here is a worked example. The pulse leaves at T = 0. Take exposure of 10 ms and a readout of 15 ms.

  1. Exposure starts at 0 (we ignore the sensor’s small fixed trigger delay).
  2. The middle of the exposure is at 5 ms. This is the time your fusion filter wants.
  3. Exposure ends at 10 ms, and the last pixel arrives after the readout, at 25 ms.
  4. An end-of-frame stamp reads 25 ms, which is 20 ms after the middle.
  5. At 1 m/s, 20 ms is 20 mm. The camera pose is off by 2 cm, and it changes whenever auto-exposure changes the exposure.

With a hardware trigger, the correct stamp is the trigger time plus half the exposure: 0 + 5 ms = 5 ms. You need the exposure value, which good sensors report in the frame metadata. Try the three conventions below.

Trigger, expose, read out, stamp

The top row is your timer’s pulse. Below it the sensor exposes, then reads out. The purple tick is the best time for the picture, the middle of the exposure. Choose a stamp and drag the exposure to see how far the stamp sits from that tick.

10.0 ms
15 ms

Illustrative timeline: global-shutter sensor, a sensor trigger delay of zero, and a robot speed of 1 m/s. The conventions are from the Linux V4L2 buffer flags (EOF: last pixel received, SOE: exposure begun). Rolling-shutter sensors expose each row at a different time, so no single stamp fits every row.

The trigger stamp is early by half the exposure. The end-of-frame stamp is late by half the exposure plus the readout. The middle stamp is the only one that stays right when you change the exposure. The cost is knowing the exposure number for each frame.

Making the pulse

Use a hardware timer in PWM mode, so the pulse train has no software in it. Set the period to one frame. The rising edge sits at the moment the counter wraps, so frame k starts at tick t0 + k × period. You then know every frame start without capturing anything. Capture the pin anyway in a test, to prove it.

c/* TIM2 channel 2 as a 30 Hz frame-sync output (pin and AF: see your datasheet's table).
   Timer clock assumed 90 MHz: one frame = 90,000,000 / 30 = 3,000,000 ticks. */
TIM2->PSC   = 0;
TIM2->ARR   = 90000000u / 30u - 1u;                 /* 2,999,999 */
TIM2->CCR2  = 9000u;                              /* 100 us high: 9,000 ticks */
TIM2->CCMR1 |= (6u << TIM_CCMR1_OC2M_Pos) | TIM_CCMR1_OC2PE; /* PWM mode 1: high while CNT < CCR2 */
TIM2->CCER  |= TIM_CCER_CC2E;                       /* drive the pin */
TIM2->EGR   = TIM_EGR_UG;                           /* load the shadow registers */
TIM2->CR1   |= TIM_CR1_CEN;                         /* frame 0 starts when CNT wraps to 0 */

/* frame k began at  t0 + k * 3,000,000 ticks;  image time = that + exposure / 2 */
uint64_t image_time_ticks(uint32_t k, uint32_t exposure_ticks) {
    return t0 + (uint64_t)k * 3000000u + exposure_ticks / 2;
}
On real hardware. Board: STM32 Nucleo-F446RE with a global-shutter camera module that has an FSIN or trigger pad (check its datasheet). Drive the pad from the timer above. Point the camera at a flashing LED that you switch on at a known tick. Find the first frame where the LED appears, and compare with the stamp. For a first test without a camera, jumper the PWM pin back to a capture pin and look at the difference between the planned and captured frame starts.
Your timer sends a frame-sync pulse at T = 0. The exposure is 10 ms and the last pixel arrives at 25 ms. Which stamp is best for fusing the image with an IMU?

Chapter 7

Trigger Fan-Out: One Pulse, Many Sensors

Send one timed pulse to a camera, an IMU, a lidar and an audio converter, and learn why they still do not sample at the same instant

You have a robot head with four sensors: a camera, an IMU, a small lidar and an audio converter. You want one moment, call it T, at which all four take a sample. So you connect one output pin of your microcontroller to the sync input of each, and fire the pulse at T. This is trigger fan-out: one source drives several inputs.

Then you look at the data. The camera frame seems to lag the IMU by about a millisecond. The lidar sits somewhere in between. All four got the same pulse at the same time. What went wrong?

Three kinds of skew

Skew is the difference between when two things should happen together and when they do. Three causes add up here.

Wire and buffer skew. The pulse takes slightly different paths to the four inputs. A buffer chip that splits the line adds its own delay, and so does a long trace. These are nanoseconds, and they are fixed for a given board. For most sensor work they are small. They matter if you count single ticks, so measure them with a scope or a logic analyzer that has a fast sample clock.

Electrical mismatch. A 3.3 V pin may not drive a 1.8 V sensor input safely. A slow edge can cross the sensor’s threshold late and wobble. Add a level shifter or buffer, and read each input’s required pulse width and edge speed in its datasheet. Recall from Chapter 6 that some sensors read the pulse width as the exposure time.

Trigger-to-sample latency. This is the big one. Each sensor needs its own time between seeing the pulse and actually sampling. A camera must reset its pixel rows and start an exposure. An IMU must latch its internal conversion. An audio converter may sample at the edge itself. Call this time L for each sensor. The sensors sample at T + L, so a pulse at T does not align them. It lines up the pulses, not the samples.

Fire early by the latency

The fix is simple, and it needs one timer. Give each sensor its own output channel from the same counter. Start each pulse early by that sensor’s latency, at T − L. Then each sensor samples at (T − L) + L = T. Because every channel uses the same counter, the pulse times differ by exact numbers of ticks, with no software jitter.

There are two ways to use latencies, and they answer different needs.

A worked example, every step

All values here are illustrative, since latencies depend on the sensor and its settings. Take T = 10 ms.

  1. Camera: L = 1.2 ms, jitter ±5 µs. IMU sync: L = 0.25 ms, ±2 µs. Lidar: L = 0.6 ms, ±10 µs. Audio converter: L = 0 (it samples at the edge), ±0.02 µs.
  2. Without compensation all pulses leave at 10 ms. The samples happen at 11.2, 10.25, 10.6 and 10.0 ms. They spread over 1.2 ms.
  3. With compensation the pulses leave at 8.8, 9.75, 9.4 and 10.0 ms. Each is a whole number of ticks from the others.
  4. Every sample now lands at 10 ms, except for each sensor’s own jitter. The worst-case spread is from −10 to +10 µs: 20 µs.
  5. If you put the wrong latency for the camera, say 1.0 ms instead of 1.2 ms, the camera samples 200 µs late. Compensation is only as good as the number.

The jitter, not the latency, sets the floor. A constant latency can be removed. A jittery one cannot. That is why you pick the lowest-jitter trigger mode your sensor offers.

Fire each sensor early

Top: when each pulse leaves the timer (hollow) and when each sensor samples (filled). Bottom: a zoom of ±30 µs around the target T. Switch compensation on, then change the camera latency you assumed.

0 µs

Illustrative latencies and jitters, not from a datasheet: camera 1.2 ms ±5 µs, IMU 0.25 ms ±2 µs, lidar 0.6 ms ±10 µs, audio 0 ±0.02 µs. Wire and buffer skew (a few nanoseconds) is left out. Look up your own sensor’s trigger-to-sample time in its datasheet, then measure it.

Notice the zoom. With compensation on and a perfect assumed latency, the four samples sit inside a band as wide as the largest jitter. Move the slider, and the camera slides out of the band by exactly the error you typed. This is the whole game: know the latencies, and keep their jitters small.

Symptom, measurement, fix

Symptom. Two sensors disagree by a steady amount, say 1 ms, that does not change from run to run. Measurement. Pulse an LED at a known tick, or tap the board, and record when each sensor first shows the event. The steady difference is the unmatched latency. Fix. Store the latency per sensor in a table, subtract it in the stamp, or fire early. Re-measure when you change a sensor mode, since latency often depends on exposure, frame rate or output rate.

c/* one counter, four output-compare channels: fire each sensor early by its trigger-to-sample latency.
   Each channel in "set active on match" mode (OCxM = 001); the pulse is ended by a second compare or by software.
   Latencies are illustrative; assumed 90 MHz timer clock = 90 ticks per microsecond. */
#define US(x) ((uint32_t)((x) * 90.0))

void schedule_sample(uint32_t target_ticks) {          /* the instant all four should sample */
    TIM2->CCR1 = target_ticks - US(1200);   /* camera FSIN */
    TIM2->CCR2 = target_ticks - US(250);    /* IMU sync pin */
    TIM2->CCR3 = target_ticks - US(600);    /* lidar sync */
    TIM2->CCR4 = target_ticks;                /* audio converter samples at the edge itself */
}                                                  /* pulses differ by whole ticks from one shared counter */
On real hardware. Board: STM32 Nucleo-F446RE plus two sensors with a sync input. Fire both from one timer, first together and then compensated. Mount both so they see the same event (a clap for a microphone, a tap for an IMU). Plot the apparent delay between them in each case. If you have only one sensor, loop its sync pin back to a capture pin and measure the output channel skew, which is the first term of this chapter.
A camera needs 1.2 ms from the sync pulse to start its exposure, and an audio converter samples at the edge. How do you make them sample at the same instant T?

Chapter 8

Judge a Stamp by Its Tail

Turn "good enough" into a number, measure it with a loopback test, and read the result as percentiles, not averages

On the bench, the ISR stamp looked fine: 122 ns late, every time. In the field, once an hour, a fusion filter jumped. Both facts are true. The bench never ran the UART at full speed, and the field did. A stamp has to be judged by its worst behaviour, since the filter breaks on the worst case and not the typical one.

Words for the tail

Sort all the lateness values from smallest to largest. The median (or p50) is the middle value. The p99 is the value that 99% of stamps stay under, so 1 stamp in 100 is worse. The p99.9 is the 1-in-1,000 value. The maximum is the single worst one you saw. The mean (the average) is the sum divided by the count. A rare 20 µs stamp barely moves the mean, so do not use the mean for this job.

Next, a budget: the largest error your system can accept, together with how often. From Chapter 0, a lidar column lasts 48.8 µs, and we called 1% of a sample period a fair budget, which is 0.49 µs. We can now say a stamp passes if its p99.9 error is under the budget, and fails otherwise. The rate (1 in 1,000) is yours to set. Choose it from how much a bad stamp costs.

Remove the constant first

Every path has a constant part, such as the 122 ns of entry cycles or the 8 ticks of the input filter. A fusion filter can subtract a constant. So judge the spread: each lateness minus the median. A path with a 5 µs constant delay and a 10 ns spread is better than a path with a zero constant and a 5 µs tail.

How many edges are enough?

To see a 1-in-1,000 event you must test enough edges. If the chance of a bad stamp is 1 in 1,000, then after 3,000 edges the chance that you saw at least one is 1 − 0.9993000 = 95.0%. After only 1,000 edges it is 63.2%. A test with 1,000 edges can look clean about a third of the time while the real rate is 1 in 1,000. To check a p99.9, run at least a few thousand edges, and run them while the system does its hardest work.

The loopback test

You can measure all of this on a real board with no extra equipment, in a loopback test. Let the timer make an edge at a tick you choose, with an output-compare channel. Wire that output pin back to the capture pin and to an interrupt pin. Because you chose the tick, you know the true edge time exactly. Then, for each edge:

  1. Pick a random future tick T, and set the output channel to fire then.
  2. When the capture fires, compute lateness = CCR1 − T.
  3. When the interrupt fires, read the counter and compute lateness = CNT − T.
  4. Put each lateness into a log-scaled histogram, one bin per quarter of a power of two.
  5. After thousands of edges, print the median, p99, p99.9 and the maximum.

Choose T at random, so that the test edges do not line up with periodic work in your firmware. If they line up, every edge lands at the same phase of a loop and you see only that phase. Run the test while the real firmware load runs: radio, flash writes, logging. The loopback shares the timer’s clock with the capture, so it measures the path, not the crystal. Crystal error is the subject of the next lesson in this series.

To count cycles on a Cortex-M3, M4 or M7, you can also use the DWT cycle counter. It counts processor cycles and is useful for timing code sections. It is not on the smallest cores such as the Cortex-M0.

Run the loopback test, set the budget

Each cell is the p99.9 spread (lateness minus the median) of a simulated loopback test. Green fits your budget. Red does not. Drag the budget, and change how many edges you test.

500 ns

Simulated, seeded, and not from a real board. ISR: the model of Chapter 1. ISR at top priority: the same model with one third the blocked share and one quarter the block length (illustrative). Capture: one tick of quantization (11.1 ns, assumed). With 1,000 edges the p99.9 cell is the value of the single worst edge or near it, so it is marked as unreliable.

Read down the columns. In the Idle column everything passes at a generous budget. Under Busy and Heavy the ISR rows change colour, and moving the ISR to top priority helps but does not cure it, because masked sections and the longest handler still block. The capture row stays green at every load, since no load touches a hardware latch. Even capture has a floor: its p99.9 spread here is about 6 ns, set by one 11.1 ns tick. Ask for less than that and only a faster timer clock helps.

Symptom, measurement, fix

Symptom. A rare jump in an estimate that you cannot reproduce on the bench. Measurement. The loopback test above, under real load, with p99.9 and the maximum printed. Also count lost captures (CC1OF from Chapter 3) in the field. Fix. Move the stamp into hardware. Or make the blocked time shorter and prove it with the same test.

c/* loopback: TIM2 CH2 (output compare) drives the pin that CH1 captures and EXTI also sees */
static volatile uint32_t truth;                          /* tick at which the next edge is scheduled */
static uint32_t hist_cap[64], hist_isr[64];                /* log2 histograms, 4 bins per octave */

static inline unsigned bin(uint32_t late) { return min(63u, (unsigned)(log2f((float)late + 1.0f) * 4.0f)); }

void schedule_next(void) {
    truth = TIM2->CNT + 900000u + (rand() % 90000u);   /* ~10 ms later, random phase */
    TIM2->CCR2 = truth;                                      /* output compare fires the edge */
}
void TIM2_IRQHandler(void) {                                  /* hardware stamp */
    uint32_t cap = TIM2->CCR1;
    hist_cap[bin(cap - truth)]++;  schedule_next();
}
void EXTI0_IRQHandler(void) {                                 /* software stamp: read the clock here */
    uint32_t now = TIM2->CNT;  EXTI->PR = EXTI_PR_PR0;
    hist_isr[bin(now - truth)]++;
}
On real hardware. Board: STM32 Nucleo-F446RE (or nRF52840 DK with the PPI chain). Build the loopback with a single jumper. Run it for 10 minutes while a second timer fires a 20 µs higher-priority handler 10% of the time. Print the median, p99, p99.9 and maximum for both stamps. Compare them with the simulated grid above, and note where your board differs.
A loopback test of 1,000 edges shows no stamp worse than 150 ns. Can you conclude that 1 stamp in 1,000 is under 150 ns?

Chapter 9

Field Guide: Stamp It Where It Happens

Review the whole path from edge to timeline, then take the numbers, the checklist and the core code to the bench

You can now say where a timestamp comes from, and how far to trust it. A stamp taken inside an interrupt is the time the code read a clock. It is late by a stable part you can subtract and a variable part you cannot. The variable part comes from waiting for the processor, and it has a long tail.

The one-paragraph summary

An ISR stamp is late by the interrupt path (12 cycles on a Cortex-M4 with zero wait states, plus wait states and your own code) and by any time the interrupt waits behind a higher-priority handler or a masked section. A hardware stamp copies a timer count at the edge: an input capture register on an STM32, or a PPI chain from a GPIOTE event to a TIMER capture task on an nRF52. Its error is one tick plus a constant. You must read the register before the next edge (watch CC1OF), or let DMA read it. You must unwrap the counter. When you control the sensor, send the frame-sync pulse yourself: the stamp is then known by construction, and you stamp the middle of the exposure. For many sensors, fire each pulse early by that sensor’s latency from one shared counter. Then prove it all with a loopback test, judged by p99.9.

The numbers that matter

WhatNumberWhere it comes from
Cortex-M3 and M4 interrupt entry12 cycles, zero wait statesArm interrupt-latency guide (M0 is 16, M0+ is 15)
Tail-chainingas few as 6 cyclesArm interrupt-latency guide
12 cycles at 180 MHz66.7 nsarithmetic, STM32F446 clock limit
Unblocked ISR stamp (model)22 cycles = 122 ns, spread about 11 nsChapter 1 worked example, illustrative
Blocked 10% of the time, up to 20 µs (model)p50 0.12 µs, p95 10 µs, p99 18 µsChapter 1, illustrative
Input-capture jitterone timer tick: 11.1 ns at an assumed 90 MHzChapter 2, quantization
Input filter IC1F = 0011N = 8 samples at fCK_INTRM0390, section 17.3.5
OvercaptureCC1OF set if a capture lands while CC1IF is highRM0390, section 17.3.5
Lap of a 16-bit and a 32-bit counter, 90 MHz728.2 µs and 47.72 sarithmetic, assumed clock
nRF52 TIMER clock16 MHz ÷ 2PRESCALER; 32-bit lap 268.4 s at 16 MHzNordic nRF52 product specification
PPI delayup to one 16 MHz period = 62.5 nsNordic nRF52 product specification
Crystal error over one 32-bit lap20 ppm × 47.72 s = 954 µsarithmetic
FSYNC sync across sensorstypically below 10 µs (vendor claim, RVC2)Luxonis hardware-sync guide
EOF stamp vs mid-exposurelate by exposure / 2 + readout; 20 ms is 20 mm at 1 m/sChapter 6, illustrative timeline
Edges needed to see a 1-in-1,000 event3,000 edges for 95%; 1,000 edges for 63.2%1 − 0.999n

The terms, in one place

TermMeaning
TimestampA count from a clock, saved next to a measurement.
LatenessStamp time minus true event time.
JitterHow much the lateness changes from edge to edge.
Input captureA timer channel that copies the counter into a register at an edge.
OvercaptureA second capture before the first was read: a lost stamp, flagged by CCxOF.
PPI / event / taskNordic hardware that connects one peripheral’s event to another’s task with no CPU.
Frame sync (FSIN, FSYNC, XVS)A sensor pin whose pulse starts a frame.
Trigger-to-sample latencyThe time from a sync pulse to the actual sample.
Fan-outOne source pin driving several sensor inputs.
p99.9The lateness that 999 stamps in 1,000 stay under.

A checklist for a new stamp path

  1. Write the budget as a number and a rate: for example, p99.9 spread under 0.5 µs.
  2. Stamp at the earliest hop that is not software: input capture, a PPI chain, or a pulse your own timer sends.
  3. Use a 32-bit timer for capture, or count laps. Keep the 64-bit sum.
  4. In the ISR, read data first, flag second. Count CC1OF. Use DMA when edges are fast.
  5. Pick the filter N just above your longest glitch. Measure the constant once and subtract it.
  6. For a camera, send the trigger, record the exposure, and stamp the middle of it. Check the driver’s EOF or SOE flag.
  7. Keep a latency table per sensor. Fire early by it, or stamp T + L.
  8. Run the loopback test under real load with thousands of edges. Read p99.9 and the maximum.
  9. Log the lost-stamp counter in the field.

The core as code

This is the capture ISR of the whole lesson in one place: it counts lost stamps, builds the long timeline and removes the measured constant. CAL_TICKS is the value from your loopback test, for example 8 ticks of filter plus the pin delay you measured.

ctypedef struct { uint64_t t; uint32_t last, lost; } stamper_t;
static stamper_t S;
#define CAL_TICKS  8u                          /* measured constant: filter + pin, from the loopback test */

void TIM2_IRQHandler(void) {                       /* TIM2: 32-bit, input capture on CH1 */
    uint32_t now = TIM2->CCR1;                  /* 1 data first; clears CC1IF */
    if (TIM2->SR & TIM_SR_CC1OF) {                /* 2 then the overcapture flag */
        TIM2->SR = ~TIM_SR_CC1OF;
        S.lost++;
    }
    S.t   += (uint32_t)(now - S.last);          /* 3 modular difference: survives one wrap */
    S.last = now;
    ring_push(S.t - CAL_TICKS);                 /* 4 time of the EDGE, in ticks since start */
}

Where this sits

This lesson stamps events on one chip, with one clock. The lesson before explained that clock, its drift and its wrap. Timers, PWM and sampling shows the timer that every stamp here depends on, and Interrupts, DMA and the 12 Cycles shows the entry cost in more depth. The IMU version of the problem, with a FIFO and a sensor clock, is in FIFO, Watermark and Timestamps. For lidar, Timing and Sync for Lidar adds PPS and PTP. For cameras, Sensor Bring-Up covers getting the sensor to take a trigger. The same tail story at the operating-system level is in Real-Time Linux, and the clock chapter of Robot Sensor and Actuator Integration shows why robots care. For the next step in this series, go to Many MCUs, One Timeline, where several chips with different crystals share a timeline using a Kalman or least-squares fit (Kalman filter). After that, Prove the Sync checks it afterwards. Biopotential acquisition uses these ideas for sample counters in Acquisition Firmware, and real-time closed-loop BCI shows the stakes. The Ethernet-class cousins, PTP and deterministic Ethernet, have a planned lesson in the physical-AI series.

Also helpful as background: Embedded Real-Time Systems and Embedded Hardware Interfacing.

The takeaway. A stamp is only as good as the least predictable hop between the edge and the saved count. Put the saving in hardware, so every hop is a clocked block. Where you control the sensor, make the pulse yourself so the time is known before the data arrives. Then measure the tail, since the worst case is the one that breaks the filter.

Sources and credit

No lecture slides stand behind this lesson. It was written from primary sources opened for it, listed here. The device models are teaching models. The timer clock of 90 MHz, the load levels, the sensor latencies and the DMA range are illustrative values and are labelled so in each device.

Not verified from a primary source, and to confirm on your own board: the pin-to-capture delay, the alternate-function number of PA0 for TIM2 channel 1, the timer clock of your clock tree, and each sensor’s trigger latency.

Your product stamps IMU edges with an interrupt and sometimes shows a 15 µs error. You cannot change the sensor. What is the best first move?

Now press Teach and explain, from memory, how an edge becomes a stamp in each of the three ways: an ISR read, an input capture and a PPI chain. Say where the tail comes from and why only the first way has one. Then go back to the histogram at the top, set the load to Heavy, and explain why the blue bars did not move.

Hardware Timestamps: Firmware from Zero to Expertise, time sync 2
STM32F446 · Nordic PPI · Luxonis FSYNC · Back to Gleams