FIFO, Watermark and Timestamps

A motion sensor keeps its own clock and its own queue. Read the queue late and samples vanish. Stamp it carelessly and every sample lies about when it happened.

Learn why an IMU has a FIFO, what the watermark interrupt promises, how a late interrupt loses data, and how the sensor’s own time counter gives each sample an honest timestamp.

Drag the interrupt latency from 10 ms up past 36 ms and watch the queue overflow. Then press each way of stamping and compare how wrong the oldest sample’s time becomes. Then we build, piece by piece, the queue, the watermark, the burst read, the three clocks and the fix.

You need a rough idea of an interrupt (a signal that makes the processor stop and run a handler) and a little C. We build the rest from zero.

Part of Firmware from Zero to Expertise. Built from the Bosch BMI270 datasheet (BST-BMI270-DS000), the TDK InvenSense ICM-42688-P driver in the Linux kernel, and Zephyr’s sensor streaming docs; the sources are listed in the Field Guide. It follows Interrupts, DMA and the 12 Cycles, I2C, SPI, UART, USB on the wire and the sensor chapter of Sleep, Wake and the Battery Budget.

Read the burst late

10 ms

A model, not silicon. It follows a Bosch BMI270 with accelerometer and gyroscope both in the FIFO at 1,600 Hz: 13 bytes per frame, a 2,048-byte FIFO that holds 157 frames, and a watermark set at 100 frames. The latency is the wait between the watermark interrupt and the start of the burst read. The host clock runs 1% off the chip’s (the datasheet lists an accelerometer ODR accuracy up to 1%).

Chapter 0

The Sample You Never Saw

See why a motion sensor cannot be read like a variable, and what goes wrong when you try

You build a small robot arm. A motion sensor sits on its wrist. The sensor reports how fast the wrist turns, 1,600 times every second. Your filter reads those numbers and tracks the angle of the wrist.

The arm works on the bench. Then you add a camera, a radio and a motor loop. Now the angle twitches. The log shows a hole in the data about 15 times a second. And when you line up the sensor data with the camera frames, the wrist seems to turn a few milliseconds before the camera sees it move. Nothing is broken. The code just treats the sensor like a variable, and a sensor is not a variable.

A sensor works whether you listen or not

A variable holds a value until you change it. A motion sensor behaves like a tap that never stops. Inside the chip, a tiny circuit measures, converts the result to numbers and writes it to a register (a small memory cell on the chip that your code can read). It does this on its own clock. The speed is the output data rate, or ODR: how many new samples the chip makes each second. At 1,600 Hz that is one new sample every 625 microseconds.

Your processor does not share that clock. It runs other work. It sleeps to save power. It handles a radio packet for a few milliseconds. The sensor does not wait. If you do not read a sample before the next one arrives, the next one writes over it.

Two plain questions follow. First, how do I read every sample? Second, when did each sample really happen? This lesson answers both. The first answer is a queue inside the chip. The second is a clock inside the chip. Neither is hard. But each has a trap, and the traps explain the twitch and the early turn.

Try the naive way first

The simplest plan is to poll: read the data register in a loop, as often as you can. Below, the sensor makes a sample every 625 microseconds. Your loop reads the register every few milliseconds. Drag the polling gap and count what you miss.

Poll the data register

The top row shows 32 samples the sensor makes in 20 ms. Each tick on the bottom row is one read by your loop. A read takes the newest sample. Drag the gap between reads.

2.0 ms

Illustrative: 1,600 Hz, so one sample every 0.625 ms, over a 20 ms window. Reads are evenly spaced and start 0.2 ms after the first sample. A read returns the newest sample the sensor has finished. Real loops also jitter; that only makes it worse.

Two failures show up. When the gap is longer than 0.625 ms, samples go unread. The gyro integrates what it sees, so a missed sample is a missed slice of rotation. When the gap is shorter, you read the same sample twice, and the filter thinks time moved when the sensor did not. You can only get one sample per read if you read exactly once per sample. That needs a signal from the sensor, and it needs your processor to be free when the signal arrives.

The data-ready interrupt, and why it is not enough

Sensors offer that signal. A data-ready interrupt is a pin that pulses each time a new sample is done. You connect it to a processor input, and the processor runs a short handler. In the handler you read the 12 bytes of one sample over SPI or I2C (the two common wire links between a chip and the processor, called buses).

That works for slow sensors. At 1,600 Hz it means 1,600 interrupts a second, each with its own bus transaction. The processor never sleeps long. Every radio event or flash write that blocks the handler for more than 625 microseconds costs a sample. The battery drains, and the timing still fails under load.

The idea of this lesson. Let the chip collect samples in its own queue, a FIFO. Wake the processor only after many samples wait. Read them all in one burst. Then rebuild the time of each sample, because the processor was asleep when they happened.

The rest of the lesson builds that in order. We meet the queue and the chip’s clock. We set the watermark, the line that decides when the chip raises its voice. We see what a late interrupt costs. We read the burst. Then we deal with time: three clocks, one honest timestamp, and how to line the samples up with other sensors.

This lesson bridges to the sensor chapter of Sleep, Wake and the Battery Budget, which shows why batching saves energy. We do not repeat that. We stay on the timing: what the data looks like once it arrives. We use the Bosch BMI270 for exact numbers, because its datasheet is open and clear. The ideas fit every modern IMU.

The road

  1. One sample, one clock: what the chip does on its own.
  2. A queue inside the chip: the FIFO, its frames and its fill level.
  3. The watermark: how one number sets latency and wake-ups.
  4. When the interrupt is late: overflow, and what the chip tells you about it.
  5. The burst read: bus time, and reading while the queue fills.
  6. Three clocks: why “when” is harder than “what”.
  7. The sensor time counter: stamping from the chip’s own clock.
  8. Drift and wrap: mapping chip time to host time.
  9. Interpolation: putting samples on someone else’s timeline.
  10. Failure clinic: symptom, measurement, fix.
  11. Field guide: numbers, checklist, code, sources.
A gyro makes a sample every 625 microseconds. Your loop reads its data register once every 3 ms. What happens?

Chapter 1

One Sample, One Clock

Follow one sample from the sensing element to the register, and learn why the chip’s idea of a second is not yours

Picture a metronome ticking in a sealed box. You cannot touch it. You can only read a card it prints at each tick. Every tick, the chip measures, converts and prints a card. The card is a sample. The metronome is the chip’s sample clock.

What one sample is

A sample from an inertial sensor holds three numbers for each sensing element. The accelerometer gives x, y and z. The gyroscope gives x, y and z. Each number is a 16-bit signed integer, so one sample from both sensors is 12 bytes. On the Bosch BMI270 the bytes sit in the data registers DATA_8 to DATA_19, at addresses 0x0C to 0x17. The accelerometer comes first. Each number is sent low byte first.

c/* One sample, the slow way: 12 bytes starting at DATA_8 (0x0C). */
typedef struct { int16_t x, y, z; } vec3_t;

static void bmi_read_sample(vec3_t *acc, vec3_t *gyr)
{
    uint8_t b[12];
    bmi_read_regs(0x0C, b, 12);              /* one SPI or I2C transaction */
    acc->x = (int16_t)(b[1]  << 8 | b[0]);   /* LSB first */
    acc->y = (int16_t)(b[3]  << 8 | b[2]);
    acc->z = (int16_t)(b[5]  << 8 | b[4]);
    gyr->x = (int16_t)(b[7]  << 8 | b[6]);
    gyr->y = (int16_t)(b[9]  << 8 | b[8]);
    gyr->z = (int16_t)(b[11] << 8 | b[10]);
}

The datasheet says the accelerometer data-ready flag clears when you read any of its data registers, DATA_8 to DATA_13. So one burst read of all 12 bytes both fetches the sample and clears the flag. That detail matters later, because a FIFO has its own rules about what a read removes.

The sample grid

The chip does not take a sample whenever it likes. It has a sample grid: a fixed row of moments, one every 1/ODR seconds. At 1,600 Hz the moments are 625 microseconds apart. Inside the chip, an internal counter ticks all the time. The BMI270 calls it sensortime: a free-running 24-bit counter that adds one every 39.0625 microseconds.

Now the useful fact. The datasheet says every sensor event is synchronous to this counter. One bit of the counter toggles for each new sample, and which bit depends on the rate. We can check it. One sample period at 1,600 Hz is 625 microseconds. Divide by the tick: 625 / 39.0625 = 16 ticks exactly. Sixteen is 24, so bit 4 of the counter toggles once per sample. The datasheet table lists bit 4 as 0.625 ms and 1,600 Hz. The numbers agree.

Think of it this way. The chip owns a stopwatch that counts in 39 microsecond ticks. Every sample is made at a whole number of ticks. If you could read the stopwatch at the moment of each sample, you would know exactly when it happened, in the chip’s time.

The chip’s second is not your second

The stopwatch is driven by an oscillator (a circuit that makes a steady beat) inside the chip. Every oscillator is a little off. Your microcontroller has its own, usually a crystal that is far more exact. The two beats do not match.

How far off? The BMI270 datasheet lists ODR accuracy, the allowed error in the sample rate, at 1% for the accelerometer and 1.7% for the gyroscope, at 25 °C with a normal supply. These are the limits on the datasheet, so a real part may be better. But they are the numbers a design must survive.

Do the sums for a gyro that runs 1% fast. You set 1,600 Hz and expect 16,000 samples in 10 seconds. You get 16,160. If your code assumes each sample is 625 microseconds after the last, it believes 10.1 seconds passed in only 10. After a minute the error is 0.6 seconds. Drag the error below and watch it grow.

Count samples as time

The line is how far your time falls behind or ahead of real time if you simply count samples and multiply by 625 microseconds. Drag the chip clock error and look at the error after 60 seconds.

+1.0%

Illustrative: the host clock is taken as exact. The range ±1.7% is the largest ODR accuracy the BMI270 datasheet lists (gyroscope, 25 °C, nominal supply); accelerometer parts list 1%. A single device is usually much closer, and it also moves with temperature.

The error is a straight line. A fixed error in the clock gives an error in time that grows without limit. That is called drift. It is why we never trust “sample number times period” for long. We need to tie the chip’s stopwatch to the host’s clock again and again. Chapter 8 does that.

Why do you care about time at all? A gyro reports rotation rate. Your filter multiplies each rate by the time step to get an angle. Drift in that time step becomes drift in angle, and any other sensor (a camera, a lidar) is on its own clock too. Section by section, we will give every sample the one thing it needs: a time you can trust.

On real hardware. Take an STM32 Nucleo and a BMI270 breakout. Route the data-ready pin to a timer input-capture channel and let the timer log 1,000 edges. Compare the average gap with 625 microseconds. The difference, in parts per million, is your chip’s clock error at room temperature. Warm the part with a hair dryer and measure again.

The chip’s clock runs 1% fast and your code assumes 625 microseconds between samples. After 60 seconds of real time, how far is your computed time from the truth?

Chapter 2

A Queue Inside the Chip

Meet the FIFO: a short line of samples that waits for you, with a header on each frame and a counter that says how many are in line

Think of a mailbox at the end of a long lane. The mail carrier drops a letter in it every 625 microseconds, whether you are home or not. You come by when it suits you and empty the box in one trip. As long as the box does not overflow, you lose nothing. The letters also stay in the order they arrived.

That box is a FIFO, short for first in, first out. It is a queue: the oldest sample leaves first. Most modern IMUs build one in. The BMI270 FIFO holds 2,048 bytes. The TDK ICM-42688-P holds 2,048 bytes too. Under the hood a FIFO is a ring buffer: a block of memory with a write position and a read position, both chasing each other around the ring.

The frame: one sample plus a label

The FIFO does not store bare numbers. It stores frames. A frame is one entry in the queue. In its standard header mode the BMI270 puts a one-byte header in front of each frame. The header tells you what the frame contains. Without it, you could not tell a gyro sample from an accelerometer sample, or a sample from a note about the queue itself.

Here is the header, bit by bit, from the datasheet. Bits 7 and 6 are fh_mode: binary 10 means a regular data frame and 01 means a control frame. Bits 5 to 2 are fh_parm. For a regular frame they say which sensors are inside: one bit each for accelerometer, gyroscope and the auxiliary sensor. Bits 1 and 0 are fh_ext, a tag you can attach with an external pin.

Take a frame with accelerometer and gyroscope. The accelerometer bit is bit 2 and the gyroscope bit is bit 3 of the header byte. So the header is binary 1000 1100, which is 0x8C. Gyro only is 0x88. Accelerometer only is 0x84. A header of 0x80 means “no sensor”, which the datasheet calls an uninitialized frame. The chip returns it when you read more bytes than the FIFO holds.

The payload follows. For 0x8C it is 12 bytes: the gyroscope first (x, y, z, low byte first), then the accelerometer. The datasheet notes that this order differs from the data registers. So one frame is 1 + 6 + 6 = 13 bytes. The FIFO holds 2,048 / 13 = 157.5, so 157 whole frames.

The ICM-42688-P makes a different choice. Its packet is 16 bytes for accelerometer and gyroscope: a header, 6 bytes of accelerometer, 6 of gyroscope, one temperature byte and a two-byte timestamp. That is from TDK’s own Linux driver. Two chips, two layouts, the same idea. Always read the layout from the datasheet of the part on your board.

How many are in line

A fill level register tells you how much is waiting. On the BMI270 it is a 14-bit byte count in FIFO_LENGTH_0 and FIFO_LENGTH_1 (addresses 0x24 and 0x25). The datasheet says the count updates each time a whole frame is read or written. Try it below. Choose what goes in each frame, then drag the time since your last read.

Fill the FIFO

Top: one frame, byte by byte. Bottom: the 2,048-byte FIFO, one box per frame. Pick the frame content, then drag how long it has been since you last emptied the queue.

60 ms

Model of a BMI270 at 1,600 Hz, header mode, with the layout from the datasheet (BST-BMI270-DS000-04, FIFO section). The FIFO sample rate follows the fastest enabled sensor. Control frames (skip, sensortime) take no FIFO memory and are left out here. After 98 ms the red boxes are samples the chip has had to overwrite.

Drag past 98 milliseconds with both sensors on. The queue is full. The next sample must go somewhere, and the chip has to choose. Chapter 4 covers that choice. First we turn the FIFO on, in the way the datasheet describes.

c/* Turn the FIFO on (BMI270, after init and with both sensors powered). */
bmi_write(0x48, 0x02);   /* FIFO_CONFIG_0: stop_on_full=0 (overwrite oldest), fifo_time_en=1 */
bmi_write(0x49, 0xD0);   /* FIFO_CONFIG_1: gyr_en (bit 7) | acc_en (bit 6) | header_en (bit 4) */

static uint16_t fifo_bytes(void)
{
    uint8_t b[2];
    bmi_read_regs(0x24, b, 2);                  /* FIFO_LENGTH_0, FIFO_LENGTH_1 */
    return (uint16_t)((b[1] & 0x3F) << 8 | b[0]);   /* 14-bit byte count */
}

Reading the queue is simple in principle. You read bytes from one address, FIFO_DATA (0x26). The chip hands over the oldest byte first. The datasheet says a frame you read in full is deleted from the FIFO. A frame you read only in part comes again, whole, on the next read. So an interrupted read does not corrupt the queue. It just repeats that frame.

The ICM-42688-P works the same way with different addresses. Its count sits at 0x2E and 0x2F, and the data port at 0x30. TDK’s driver also notes that the first count read after a FIFO reset returns zero, so the driver reads it once and throws it away. Little quirks like this are why a datasheet read-through pays.

Why a header and not a fixed layout. The queue holds more than samples. It also holds notes about the queue: how many frames were lost, when the last sample was taken, that a setting changed. A header lets one stream carry both. Chapters 4 and 7 use those notes.

On real hardware. Using an STM32 Nucleo and a BMI270 board, enable both sensors in the FIFO at 1,600 Hz. Wait 50 ms and read FIFO_LENGTH. You should see about 80 frames, or 1,040 bytes. Then change to gyro only and repeat. The count stays at 80 frames, but the byte count falls to 560.

A BMI270 FIFO holds both sensors in 13-byte frames. FIFO_LENGTH reads 1,300 bytes. How many samples wait, and what is the first byte of each frame?

Chapter 3

The Watermark

Choose one number that decides how often the chip wakes you, how old the data is when you hear about it, and how much room you have left

Back to the mailbox. You do not want to check it every minute. You do not want to find it overflowing either. So you put a flag on the box that pops up when it holds a set number of letters. You come when you see the flag.

The chip’s flag is the watermark: a fill level, set by you, at which the chip raises an interrupt pin. The name comes from the mark a flood leaves on a wall. When the water in the FIFO rises to the mark, the chip tells you.

One number, three consequences

On the BMI270 the watermark is a number of bytes in FIFO_WTM_0 (0x46) and FIFO_WTM_1 (0x47). The datasheet says the interrupt fires when the FIFO holds at least that many bytes. The reset value is 0x200, or 512 bytes. You also map the interrupt to a pin with the interrupt-map register, and you wire that pin to a processor input.

Let W be the watermark in frames, f the frame rate, and N the FIFO capacity in frames (157 here). Three things follow at once.

  1. Wake-ups per second = f / W. A high watermark means fewer interrupts.
  2. Latency = W / f. When the flag rises, the oldest sample is already W / f seconds old. A high watermark means older data.
  3. Headroom = (N − W) / f. This is how long the processor can ignore the flag before the queue is full. A high watermark means less room.

Work three cases at 1,600 Hz. With W = 1, the watermark is a data-ready interrupt in disguise. You wake 1,600 times a second, the oldest sample is 0.625 ms old, and you have 97.5 ms of headroom. With W = 100, you wake 16 times a second, the oldest sample is 62.5 ms old, and the headroom is 57 frames, or 35.6 ms. With W = 150, you wake about 10.7 times a second, the data is 93.75 ms old, and the headroom is only 4.4 ms.

So the watermark is a trade among three things you care about: battery (fewer wake-ups), freshness (younger data) and safety (more headroom). The two ends of the dial are both bad. No single value is best. The right value depends on two facts about your system, and you can measure both.

Set the watermark

The rising line is how old the oldest sample is when the interrupt fires. The falling line is the time you have left before the FIFO is full. Drag the watermark, then drag the longest delay your firmware ever has between the interrupt and the start of the read.

100 frames
20 ms

BMI270 at 1,600 Hz with accelerometer and gyroscope in 13-byte frames, so the FIFO holds 157 frames. The cost of a wake-up is illustrative: 100 microseconds of fixed work per interrupt (wake, enter, set up the transfer), plus 10.4 microseconds per frame on a 10 MHz SPI bus (13 bytes at 8 bits each).

The two facts that choose it

The first fact is your latency budget: how old a sample may be when your code sees it. A step counter can wait a second. A flight controller wants a few milliseconds. The budget caps the watermark: W ≤ budget × f.

The second fact is your worst-case interrupt delay: the longest time from the pin edge to the start of the read, in your real system. This is not the average. It is the worst case, including a radio event, a flash erase or a higher-priority handler that holds the processor. That delay eats headroom, so W ≤ N − delay × f. Add a margin of a few frames.

Take a budget of 50 ms and a worst delay of 20 ms. The first rule gives W ≤ 80. The second gives W ≤ 157 − 32 = 125. The smaller value wins: W = 80, with 77 frames (48 ms) of headroom against a 20 ms worst case. In the device above, set the delay to 20 ms and drag the watermark. The red zone shows where the rule breaks.

TDK ships an example of this rule. The vendor’s Linux driver for the ICM-42688-P caps the watermark at 2,048 minus 12 packets of 16 bytes, which is 1,856 bytes or 116 packets. A comment says the 12 packets are left “for reading latency”. The same idea, with a margin of 12 frames.

A trap: the interrupt stays up

The BMI270 datasheet adds a detail that bites. In latched mode, a FIFO interrupt clears only when you read the status register and the fill level is below the threshold. If you read part of the queue and it is still above the mark, the pin stays high. Then you get no new edge, and an edge-triggered handler (one that runs only when the pin changes from low to high) never runs again. Two safe habits follow. Read until the FIFO is empty, or at least below the mark. And treat the pin as a level, not a one-time event.

On real hardware. On a Nucleo, toggle a spare pin at the top of the interrupt handler and again when the SPI read starts. Capture many bursts with a logic analyzer. The largest gap between the sensor’s interrupt edge and the first clock is your worst-case delay. Set the watermark from that measured number, not from a guess.

Frame rate 1,600 Hz, capacity 157 frames, latency budget 100 ms, worst-case interrupt delay 40 ms. What is the largest safe watermark by the two rules?

Chapter 4

When the Interrupt Is Late

See which samples a full FIFO throws away, how the chip reports the loss, and how to find the cause in your own firmware

Your robot arm is moving. The radio stack grabs the processor for 45 milliseconds to finish a connection event. During those 45 milliseconds the chip raises its watermark flag, then keeps making samples. The mailbox fills up. At sample 158 there is no room. What now?

Two choices when the queue is full

The chip has to drop something, and the datasheet lets you pick what. In the BMI270 the bit fifo_stop_on_full in FIFO_CONFIG_0 chooses between two modes.

Streaming mode (the bit is 0) keeps the newest data. When the FIFO is full, the chip deletes the oldest frames to make room. You always hold the latest 157 frames. This is the right pick for a control loop, which wants the recent past.

FIFO mode, also called stop on full (the bit is 1), keeps the oldest data. When the FIFO is full, the chip discards the newest frames. This is the right pick when the start of an event matters more than the end, such as a gesture that began when the buffer was empty. The ICM-42688-P has the same two modes, set in its FIFO_CONFIG register (stream, or stop on full).

Either way, the loss is real and silent unless you look. Try it. The bar below shows every sample the chip made between two reads. Drag the delay and flip the mode.

Overflow the FIFO

The bar is every frame the chip made from one read to the next, oldest on the left. Warm-coloured frames survive. Red frames are gone. Drag the delay between the watermark interrupt and the start of your read.

50 ms

BMI270 at 1,600 Hz, 13-byte frames, 157-frame FIFO, watermark at 100 frames. Frames are counted from the last read. The skip count is the number the chip reports; the datasheet caps it at 255 (0xFF). The model assumes the read itself takes no time; Chapter 5 adds it.

How the chip tells you

The BMI270 does not lose frames quietly if you use header mode. It inserts a skip frame, a control frame whose header has the control type and whose single payload byte counts the lost frames. The datasheet says it is prepended at the next read, always as the first frame of the burst, and it takes no FIFO memory. If more than 255 frames were lost, the byte stays at 0xFF. In stop-on-full mode, the datasheet warns that the skip frame is not at the position where frames were discarded.

There is a second, nastier case. While you read, new samples keep arriving. The datasheet says no data at the tail may be dropped during a read. So if you read more slowly than the chip writes, the chip may be forced to drop new data even in streaming mode. It records that event in the fifo_err bit of the ERR_REG register. Chapter 5 shows when this happens.

The ICM-42688-P reports the other half of the story: its header has a message bit that marks “FIFO empty” when you over-read, and TDK’s driver treats a sample whose x, y and z all read −32,768 as invalid. Different chip, same lesson: the stream carries markers, and your parser must check them.

Symptom, measurement, fix

Symptom. A hole in the data, often at a regular spacing. The filter jumps. A plot of the gyro shows a flat step or a spike where rotation continued. With the numbers from the device: a 50 ms delay on a 100-frame watermark loses 23 frames, which is a 14.4 ms hole, and the cycle repeats every 112.5 ms.

Measurement. Log the skip count from every burst and keep a running total. Count frames per second at the parser and compare with the ODR: 1,600 frames per second means nothing was lost. On a logic analyzer, measure the time from the interrupt edge to the first clock edge of the read. If that gap, times the frame rate, plus the watermark, exceeds 157, you have found the cause.

Fix. Work from cheap to costly. First, lower the watermark, which buys headroom at the price of more wake-ups (Chapter 3). Second, shorten the handler. The handler should start a DMA transfer (the bus engine moves the bytes without the processor) and return, not copy bytes in a loop. Third, give the sensor interrupt a higher priority than whatever blocks it, or cut the length of the blocking code. Fourth, reduce what you store: drop a sensor, or lower the ODR. The loss is not the real danger. The real danger is a design that never counts it.

A rule worth keeping. Treat a lost sample like a dropped packet in a network. Count it, log it, and make the filter aware of it. A filter that is told “23 samples are missing here” can widen its uncertainty. A filter that is not told will trust a wrong angle.

On real hardware. On a Nucleo and a BMI270 board, put a 50 ms busy loop in a lower-priority task and run it every second. Read the skip frame in the next burst. It should say about 23 frames lost. Then lower the watermark to 50 frames and repeat. The skip count should fall to zero.

A burst begins with a skip frame whose payload byte is 0x17. What does it tell you?

Chapter 5

The Burst Read

Empty the queue in one transaction, count what the bus costs, and parse frames that cross the edge of a buffer

The flag is up. You hurry to the mailbox with a bag. But the lane is narrow, and you can only carry so many letters per minute. While you walk back and forth, the carrier keeps adding more. Will you ever empty the box?

That question is the whole of this chapter. A burst read is one bus transaction that clocks out many bytes from a single register, here FIFO_DATA (0x26 on the BMI270). You do not step an address for each byte. The chip hands over the oldest byte first, then the next, until you stop clocking.

How long the bus takes

Every byte costs clock cycles. On SPI a byte takes 8 clocks. On I2C a byte takes 9 clocks, 8 for data and one for the acknowledge bit. We ignore the address and start bytes, which add a small fixed cost. The BMI270 datasheet gives 10 MHz as the top SPI clock and 1 MHz as the top I2C clock (fast mode plus).

The sums for the 1,300 bytes of 100 frames are short. SPI at 10 MHz: 1,300 × 8 / 10,000,000 = 1.04 ms. I2C at 1 MHz: 1,300 × 9 / 1,000,000 = 11.7 ms. I2C at 400 kHz: 1,300 × 9 / 400,000 = 29.25 ms.

Now compare with how fast the chip writes. At 1,600 Hz with 13-byte frames it writes 20,800 bytes per second. A 400 kHz I2C bus can move 400,000 / 9 = 44,444 bytes per second at best. So the bus is busy 47% of the time just keeping up. At 3,200 Hz it would be 94% busy, and in practice it would lose. That is the second reason SPI is the usual choice for a fast IMU.

Reading while it fills

While you read, the chip keeps writing. So the level does not fall at the bus rate; it falls at the difference between the bus rate and the write rate. Over I2C at 400 kHz, the bus moves 3.42 frames per millisecond and the chip writes 1.6. The queue drains at only 1.82 frames per millisecond. Starting from 116 frames (the 100-frame watermark plus 10 ms of delay), the read lasts 116 / 1.82 = 64 ms, not 34 ms. Over SPI it lasts about 1.2 ms. Try it.

Drain the FIFO

The line is the FIFO level from the moment you start the read. The chip keeps writing while you read. Choose a bus, then change the watermark and the delay before the read starts.

100 frames
10 ms

Derived, not measured: bytes per second is clock rate divided by clocks per byte (8 for SPI, 9 for I2C), and the address and start bytes are left out, so real reads take a little longer. The chip writes 1.6 frames per millisecond (1,600 Hz). One frame is 13 bytes.

The lesson for firmware: never read the FIFO with the processor spinning. Start a DMA transfer (the bus controller moves bytes into RAM on its own, as in the interrupts and DMA lesson) and let the processor sleep or do other work until the transfer-complete interrupt. A 64 ms I2C read is 64 ms of processor time if you copy bytes in a loop.

Parsing what arrives

The burst is a byte stream, not an array of frames. You read it into a buffer, often in chunks, and a frame can straddle two chunks. The parser must never assume a chunk ends on a frame boundary. It reads the header, works out the frame length, and if the whole frame is not there yet, it keeps the leftover bytes for the next chunk.

c/* BMI270 header mode. Returns bytes used, or 0 if the frame is not complete yet. */
size_t fifo_parse_one(const uint8_t *p, size_t n, struct imu_sample *out, struct burst_info *bi)
{
    if (n < 1) return 0;
    uint8_t h = p[0];
    if ((h & 0xC0) == 0x80) {                         /* regular frame */
        uint8_t parm = (h >> 2) & 0x0F;
        if (parm == 0) { bi->empty = true; return n; }  /* 0x80: over-read, stop */
        size_t len = 1 + ((parm & 2) ? 6 : 0) + ((parm & 1) ? 6 : 0);  /* no aux */
        if (n < len) return 0;                     /* frame crosses the chunk edge */
        const uint8_t *d = p + 1;
        if (parm & 2) { out->gyr = le_vec3(d); d += 6; }  /* gyro comes first */
        if (parm & 1) { out->acc = le_vec3(d); }
        out->valid = true;
        return len;
    }
    if ((h & 0xC0) == 0x40) {                         /* control frame */
        switch ((h >> 2) & 0x0F) {
        case 0: if (n < 2) return 0; bi->skipped = p[1]; return 2;                  /* skip frame */
        case 1: if (n < 4) return 0; bi->sensortime = p[1] | p[2]<<8 | (uint32_t)p[3]<<16; return 4; /* sensortime */
        case 2: if (n < 5) return 0; bi->config_changed = true; return 5;        /* input config */
        }
    }
    bi->corrupt = true; return n;                       /* unknown header: resync */
}

Read the code with the datasheet beside it. A skip frame is a header plus one byte. A sensortime frame is a header plus three bytes. An input-config frame is a header plus four bytes. The code treats a header it does not know as a sign of corruption and stops. That choice is deliberate. Guessing the length of an unknown frame would turn one error into a stream of garbage.

The datasheet also says one sensortime frame is expected as the last frame of a burst, and only if the FIFO became empty during the read. That frame is the key to Chapter 7. For now note that it is a control frame and not a sample, so the parser must keep it out of the sample count.

On real hardware. On a Nucleo with a BMI270 breakout, time the full read of 100 frames with a GPIO pulse around the DMA transfer and compare with the formula. Run it on SPI at 10 MHz, then on I2C at 400 kHz. The measured time will be a little longer than the sums here because of address bytes and DMA setup. That gap is your bus overhead.

Over I2C at 400 kHz the bus moves 3.42 frames per ms and the chip writes 1.6. You start a read at 116 frames. About how long until the FIFO is empty?

Chapter 6

Three Clocks

Learn what a timestamp means, which clocks can supply one, and how a careless stamp turns timing jitter into a wrong angle

A camera takes a picture at 12:00:00.500. Your gyro burst arrives at 12:00:00.560. In that burst are 100 samples. Which one belongs with the picture? To answer, you need to know when each sample was made. The burst only tells you when it was read.

What a timestamp is

A timestamp is a number that places a sample on a timeline. The timeline must be the same one the other sensors and your filter use. A timestamp is only useful when two things hold: it says when the sample was taken, not when you heard about it, and it uses a clock that other data shares or can be mapped to.

Three clocks are in play in the burst-read setup.

  1. The sensor clock. The free-running counter inside the chip (the BMI270 sensortime, 24 bits, 39.0625 µs per tick). It is exact about spacing between samples, because the samples are made on this same clock. It knows nothing about the world outside.
  2. The host clock. A timer in your microcontroller, driven by its crystal. It is the clock your filter, your radio log and your camera driver can share. It does not see inside the chip.
  3. The order of frames. The position of a frame in the FIFO. It gives no time on its own, but with the frame rate it gives the gap between neighbours.

A good timestamp uses the strength of each. The sensor clock gives accurate spacing. The host clock gives the anchor to the outside world. The order tells you which sample came before which. The rest of this lesson combines them. First, let us look at the common wrong ways.

Three wrong ways

Stamp at read time. You parse a frame and write now() beside it. Every frame in the burst gets the same time, give or take the microseconds your parser needs. The newest sample is stamped a little late, the oldest is stamped W / f too late. For W = 100 that is 62 ms.

Stamp at the interrupt. You note now() in the interrupt handler and give it to the whole burst. This is better: it is closer to the time of the newest sample. But the burst has 100 samples spread over 62 ms. If you give them all one time, you bunch them.

Back-fill from the read time. You stamp the last frame with now() and step back by 625 microseconds for each earlier frame. The spacing is now right. But the anchor is the moment of the read. That moment is the interrupt time plus your delay, and the delay changes from burst to burst. The whole burst slides by the delay.

The last one is the dangerous one, because the data looks clean. Spacing is perfect. Only the offset is wrong, and it changes from burst to burst. A changing offset is jitter. The filter cannot tell jitter in the timestamps from jitter in the world.

What a time error costs

Take a gyro that reports 200 degrees per second. A time error Δt turns into an angle error of rate × Δt. With a 5 ms error, 200 × 0.005 = 1.0 degree. If the wrist rotates faster, the error grows in proportion. For a camera running at 30 frames per second, a 5 ms offset is 15% of a frame. In a visual-inertial system, that is a visible lag between what the camera sees and what the gyro felt.

Drag the delay jitter below. The bars show how far each burst is stamped from the truth when you back-fill from read time. Then switch to anchoring on the interrupt edge.

Jitter in, angle error out

Each bar is one burst: how late it is stamped. Choose the anchor, then drag how much the interrupt delay varies and how fast the wrist turns.

8 ms
200 deg/s

Illustrative: eight bursts with delays drawn from a fixed seeded sequence between 0 and the slider value. The edge anchor is taken to be within 0.02 ms (a hardware timer capture, a few counts of a 1 MHz timer). Angle error is rate times time error, so it ignores everything else in a real filter.

With the read anchor, the timestamp error equals the delay, so it is as erratic as your scheduler. With the edge anchor it is almost zero, because a hardware timer saved the exact moment of the pin edge, before any software ran. The lesson: take the time in hardware, as close to the event as you can, and do the rest later. Chapter 7 uses that edge to anchor a whole burst. Chapter 8 replaces it with the chip’s own counter.

On real hardware. On an STM32 Nucleo, set a timer in input capture mode on the pin that carries the sensor’s interrupt. The timer copies its counter into a capture register on the edge, in hardware. Log the capture value at the start of the handler and compare it with a software now() taken a few instructions later. The difference is your interrupt latency, and its spread is the jitter you just removed.

You stamp the newest frame of each burst with the host time at the start of the read, and step back 625 microseconds per frame. The interrupt delay varies between 2 and 10 ms. What is wrong?

Chapter 7

Back-Fill and the Sensor Time Counter

Date every frame from one trusted moment, count the frames you lost, and see why the chip’s own counter beats the host’s guess

Detectives date a crime scene from one fixed point: the 911 call came in at 9:14. Everything else is placed before or after that call, by how many minutes apart. We will do the same with samples. We need one trusted moment, and we need the gap between neighbours.

Back-fill from the interrupt edge

The trusted moment is the edge of the interrupt pin. A hardware timer in input-capture mode saves its count at that edge, so the time is exact to a timer tick. Call it te. At that instant the FIFO had just reached the watermark: it held W frames, and the newest one had just been made.

Now count frames by ordinal: the number of a frame since the FIFO was last emptied. The frame with ordinal W was the newest at the edge. A frame with ordinal k was made (k − W) periods after the edge. Negative means before. So:

t(k)
The host-clock time of the sample with ordinal k.
te
The host timer value captured at the interrupt edge.
k
The ordinal: how many frames since the FIFO was last emptied, counting the lost ones.
W
The watermark in frames: the ordinal of the frame that raised the interrupt.
T
The period between samples: 625 µs at 1,600 Hz.

Here is the worked case from Chapter 4. The watermark is 100 frames and the read starts 50 ms late. The chip makes 180 frames, 23 are lost, and 157 are read. The oldest surviving frame has ordinal 24. Its time is te + (24 − 100) × 0.625 ms = te − 47.5 ms. The newest has ordinal 180: te + 80 × 0.625 = te + 50 ms. That matches the 50 ms delay, so the sums are consistent.

Notice what the skip frame did. The first frame in the burst is number 1 in the buffer but number 24 in the count. If you forget the skip count, every stamp is wrong by 23 × 0.625 = 14.4 ms. That is why Chapter 4 told you to log it. Use it here.

This method has two weak spots. It trusts the nominal period T. If the chip’s clock runs 1% fast, a frame 100 periods from the anchor is off by 100 × 1% × 0.625 ms = 0.625 ms. And it needs the FIFO emptied each time, so that ordinal 1 means “first frame after the last read”. Change the ODR or the frame content without flushing, and the count breaks.

The sensor time counter

The chip already has a clock that shares the sample clock. Chapter 1 met it: the 24-bit sensortime counter, with 39.0625 µs per tick. The BMI270 can put its value into the stream. Setting fifo_time_en in FIFO_CONFIG_0 (on by default) makes the chip append a sensortime frame to the end of a burst. It is a control frame with a 3-byte payload, and the datasheet says it copies the counter at the moment the last byte of the last sample frame was read. It takes no FIFO memory. It is only sent if the FIFO became empty during the read.

Because the samples are made on this same clock, they sit on a grid. At 1,600 Hz the grid step is 16 ticks. The newest sample therefore happened at the latest grid point at or before the counter value in the frame. And the sample before it happened exactly 16 ticks earlier, and so on. Spacing in chip time is exact, with no drift at all, because nothing but one oscillator is involved.

The sensor-time idea. Do not guess spacing with the host clock. Date every frame in the chip’s own ticks, from the sensortime frame and the frame order. Then, separately and rarely, learn how chip ticks map to host time (Chapter 8).

Compare the two methods in the device. Both sit on the same burst. The host-side back-fill carries the clock skew and any miscounted loss. The sensor counter is exact in the burst, apart from the rounding of one tick, which is 39 µs.

Compare two stamps

Each point is one frame of a 120-frame burst: how far its stamp is from the truth. Drag the chip clock error and the number of frames lost. Toggle whether your code uses the skip count.

+1.0%
20

Model: watermark 100, period 625 µs, a 120-frame burst. The edge back-fill uses t(k) above; the truth uses the chip’s real period 625 µs divided by one plus the error. The sensor-time band is plus or minus half a tick (19.5 µs), the rounding of the 39.0625 µs counter. The mapping from chip time to host time is left out here and comes in Chapter 8.

TDK’s ICM-42688-P takes a related route. Each packet carries a 16-bit timestamp, and the vendor’s Linux driver also anchors on the interrupt time. It estimates the chip period from the gap between interrupts divided by the frame count, and keeps the estimate inside the chip’s stated jitter band. It ignores interrupt pairs closer than 20 ms when measuring the period, because short gaps give a noisy estimate. The names differ; the structure is the same as ours: one anchor, one spacing, and a guard against nonsense.

c/* Stamp a parsed burst. All times in nanoseconds on the host timer. */
void stamp_burst(struct imu_sample *s, int n, const struct burst_info *bi,
                 int64_t t_edge_ns, int wm_frames, int64_t period_ns)
{
    int first_ordinal = ordinal_since_empty + bi->skipped + 1;   /* count the lost frames */
    for (int i = 0; i < n; i++)
        s[i].t_ns = t_edge_ns + (int64_t)(first_ordinal + i - wm_frames) * period_ns;
    ordinal_since_empty = 0;                        /* the burst emptied the FIFO */
}

/* Or, in the chip's own time: sensortime frame -> ticks of 39.0625 us. */
uint32_t sensor_ticks_of_frame(uint32_t st_end, int n, int i, uint32_t ticks_per_sample)
{
    uint32_t newest = st_end - (st_end % ticks_per_sample);   /* snap to the sample grid */
    return (newest - (uint32_t)(n - 1 - i) * ticks_per_sample) & 0xFFFFFF;   /* 24-bit wrap */
}

On real hardware. On a Nucleo with a BMI270 board, wire the interrupt pin to a timer capture and also read SENSORTIME_0 to SENSORTIME_2 in the data-ready handler. Plot sensortime against the captured host time over 30 seconds. A straight line confirms the model. Its slope is the chip clock error. Its scatter is your capture jitter plus one tick.

A burst arrives with a skip frame that reports 12 lost frames. You back-fill from the interrupt edge. What must you do with the 12?

Chapter 8

Drift and Wrap

Learn the line that turns chip ticks into host time, how a longer baseline sharpens it, and how a 24-bit counter wraps

You keep a diary in Tokyo time. A friend keeps one in London time. To compare entries you need two numbers: the offset between your clocks, and whether one of them runs fast. If both clocks were perfect, the offset would be enough. They are not, so you also need the speed ratio.

The chip and the host are in the same position. Chapter 7 left us with every sample dated in chip ticks, exactly spaced. The host, your filter and other sensors speak host time. The bridge is a straight line.

The line between two clocks

thost
A time on the host clock, in seconds.
a
The offset: the host time when the chip counter read zero. It is large and arbitrary, because the counter started when the chip powered up.
b
The skew ratio: host seconds per chip second. It is close to 1. A chip that runs 1% fast has b near 0.990.
tchip
The chip time: sensortime ticks times 39.0625 µs, after unwrapping.

To find a and b you need pairs: a chip time and the host time of the same event. Every watermark interrupt gives one. The chip time of the frame that raised the interrupt is on the grid (Chapter 7). The host time is the captured timer value of the pin edge. Collect a pair at every burst. At 16 bursts a second, that is 960 pairs per minute, for free.

The pairs are noisy. The edge capture has some jitter. The chip raises its pin a fixed short time after the sample, which only shifts a. Fit a line through the pairs by least squares (find the line with the smallest total squared miss). The slope is b.

A longer baseline sharpens the slope

Why does time help? The skew is a ratio of two differences: how far the host clock moved divided by how far the chip clock moved between two pairs. Noise of σ (sigma, the typical size of the timing noise) on each pair puts about 1.4 × σ of noise on the difference of two pairs. Wait twice as long, and the difference is twice as big while the noise stays the same. So the error in b is about 1.4 × σ / baseline for two pairs, and a fit through many pairs does a little better. With σ = 100 µs and a 10 s baseline, that is 14 parts per million (ppm). With a 60 s baseline it is 2.4 ppm.

What does 14 ppm cost? It is 14 microseconds of error per second of extrapolation. Fine for a camera frame at 30 Hz. Not fine if you stop updating the fit and coast for an hour: 50 ms. So keep updating. The fit is a tracker, not a calibration done once.

Fit the two clocks

One pair per burst, 16 a second. The line is how wrong the fitted mapping is, in microseconds, using only the pairs seen so far. The shaded part is extrapolation beyond what you have observed. Drag the noise and the observation time, then switch on late interrupts.

100 us
10 s

Simulated, seeded noise. The chip clock is set 1% fast. Noise is a bell-shaped spread of the stated size. Late interrupts add a delay between 0 and 20 ms to 3% of the pairs. Rejecting outliers fits once, drops pairs more than three robust spreads from the line, and fits again.

Switch on the late interrupts. A few pairs are 10 or 20 ms off, and a plain fit follows them. The error jumps by hundreds of microseconds. Now reject outliers: fit, drop the pairs that sit far from the line, and fit again. The error falls back. A late interrupt can only make an edge look later, never earlier. So robust fits that favour the early side of the data are a sound habit.

Wrap: a counter has an end

The sensortime counter has 24 bits, so it holds 16,777,216 different values. At 39.0625 µs per tick it wraps to zero every 16,777,216 × 39.0625 µs = 655.36 s, about 10.9 minutes. The ICM-42688-P puts only a 16-bit timestamp in each packet. With the 16 µs resolution bit (TMST_RES_16US in the vendor’s driver header) that wraps every 65,536 × 16 µs = 1.048576 s.

You must extend the counter to more bits in software. The trick is to compare each new raw value with the last one. If it went down by more than half the range, it wrapped, so add one range to a high word.

c/* Extend the 24-bit sensortime to 64 bits. Call at least once per half-wrap (327 s). */
uint64_t sensortime_unwrap(uint32_t raw24)
{
    static uint32_t last;
    static uint64_t hi;                    /* counts whole wraps, in ticks */
    if (raw24 < last && (last - raw24) > (1u << 23))
        hi += (uint64_t)1 << 24;            /* went backwards by more than half: it wrapped */
    last = raw24;
    return hi + raw24;                       /* ticks; multiply by 39.0625 us for time */
}

The rule has a limit. You must see the counter at least once every half wrap. For the BMI270 that is 327 s; for a 16-bit, 16 µs timestamp it is about half a second. If the host sleeps longer, one wrap goes uncounted and every later stamp is off by 655.36 s. A host that sleeps for minutes must keep its own low-power timer running and use it to count wraps. This is a common bug in battery devices.

The BMI270 also helps at configuration changes. When you change a rate or filter, it inserts an input-config frame. That frame carries the sensortime of the next frame. Treat it as a fresh anchor, because the sample grid may change at that moment.

On real hardware. Log one (sensortime, timer capture) pair per burst for ten minutes on a Nucleo, then run the least-squares fit offline. Plot the residuals. Heat the sensor gently and watch the slope change. Then remove the unwrap code on purpose and watch the stamps jump by 655.36 s at minute eleven.

Your host sleeps for 12 minutes between reads of a BMI270. You unwrap the 24-bit sensortime by comparing each value with the last. What goes wrong?

Chapter 9

Interpolation

Ask the IMU for its value at a time it never sampled, and learn when a straight line between two samples is good enough

A camera opens its shutter at host time 12.345 678 s. Your gyro made samples at 12.345 000 s and 12.345 625 s. Your filter wants the rotation rate at the shutter moment, not at either sample. No sample sits exactly there. The other sensor lives on a different grid, and the two grids almost never line up.

The tool for this is interpolation: estimating a value between two known samples. Once every sample has an honest timestamp, interpolation is cheap, and it is the step that finally joins the IMU to everything else.

The straight-line estimate

Take two neighbouring samples, v0 at time t0 and v1 at t1. Let t be the query time, between them. Linear interpolation draws a straight line between the samples and reads it at t.

v(t)
The estimated value at the query time, for each axis.
v0
The sample just before the query time.
v1 − v0
How much the signal changed between the two samples.
u
How far along the gap the query sits: 0 at the first sample, 1 at the second.

Work the example. Gyro x reads 20.0 deg/s at 12.345 000 s and 21.0 deg/s at 12.345 625 s. The shutter is at 12.345 678 s, which lies after the second sample, so we need the next pair. Say the next sample, at 12.346 250 s, reads 21.6. Then u = (12.345 678 − 12.345 625) / 0.000 625 = 0.085, and v = 21.0 + 0.6 × 0.085 = 21.05 deg/s. Two samples, one multiply.

How wrong can a straight line be?

A straight line is only right when the signal is straight between the samples. If the gyro vibrates, the line cuts the corner. For a sine wave with amplitude A and frequency f, sampled with period T, the worst miss of linear interpolation is at most (T2 / 8) × A × (2πf)2. The bound grows with the square of the ratio of signal frequency to sample rate.

Put in numbers. At 1,600 Hz, T = 0.625 ms. A 50 Hz vibration gives a worst miss of about 0.5% of the amplitude. A 400 Hz vibration gives about 31%. At a 100 Hz output rate (T = 10 ms), a 10 Hz motion gives 4.9%. Drag the device and watch the nearest-sample guess and the line side by side.

Ask for a value between samples

The curve is the true gyro signal. Dots are the IMU samples. The vertical line is the camera shutter. Choose a sample rate, a vibration frequency and where the shutter falls between two samples.

150 Hz
40%

A pure sine wave, amplitude 1, with a fixed phase, so the numbers are exact for this signal. The vibration slider stops at 40% of the sample rate, because a real sensor’s low-pass filter removes content near or above half the rate (see What an IMU Really Measures). Errors are shown as a percentage of the amplitude. The worst-case figure is the formula above.

Two lessons come out of the device. First, linear interpolation beats picking the nearest sample by a wide margin when the signal is slow compared with the sample rate. Second, both fail when the vibration approaches the sample rate. That is not a bug in the method. The samples simply do not hold enough information. The fix is a higher ODR, not a cleverer formula.

Two rules for batched data

Rule one: wait for the bracket. To interpolate at the shutter time, you need a sample after it. With batching, that sample may still be inside the chip. The fusion must wait until a burst arrives that covers the query time, so it runs behind real time by up to W / f plus the interrupt delay. That is Chapter 3’s latency, paid again. If the camera time must be known sooner, lower the watermark. Never extrapolate to cover the wait.

Rule two: never bridge a hole. If the two nearest samples are more than one and a half periods apart, a frame was lost between them (Chapter 4). A straight line across the hole hides the loss. Return a flag, and let the filter widen its uncertainty.

To sum rotation between two camera frames, do not interpolate the rate and then sum. Integrate the rate over the exact span: interpolate to the first frame time, add every full sample interval in between with the trapezoid rule (average of neighbours times T), then interpolate to the second frame time. This matters when the span is only a few samples long.

c/* Value of the IMU at host time t_ns. ring holds stamped samples, oldest first. */
typedef enum { Q_OK, Q_WAIT, Q_HOLE, Q_OLD } qres_t;

qres_t imu_at(const struct ring *r, int64_t t_ns, int64_t period_ns, vec3f_t *out)
{
    if (t_ns < r->s[r->head].t_ns) return Q_OLD;           /* already dropped from the ring */
    if (t_ns > r->s[r->tail].t_ns) return Q_WAIT;          /* the next burst has not arrived */
    int i = ring_find_before(r, t_ns);                   /* binary search, last sample <= t */
    const struct imu_sample *a = &r->s[i], *b = &r->s[i + 1];
    if (b->t_ns - a->t_ns > period_ns * 3 / 2) return Q_HOLE;   /* a lost frame sits between */
    float u = (float)(t_ns - a->t_ns) / (float)(b->t_ns - a->t_ns);
    out->x = a->gyr.x + (b->gyr.x - a->gyr.x) * u;               /* same for y and z */
    return Q_OK;
}

The function returns four answers, not one number. Q_WAIT and Q_HOLE are not errors. They are honest statements about the data. A fusion loop that treats them as normal cases is the sign of a driver done well.

On real hardware. Mount a BMI270 on a small speaker cone driven at 80 Hz, with a Nucleo logging at 1,600 Hz. Treat every fourth sample as a camera query and compare the interpolated value with the true sample you skipped. The error should land near the bound in the formula. Repeat at 400 Hz output to see it grow.

The IMU makes samples every 10 ms. A camera shutter falls 4 ms after a sample, and the next IMU burst has not arrived yet. What does a careful driver do?

Chapter 10

Failure Clinic

Match six symptoms from the bench to their cause and fix, and learn to build the counters that make these failures visible

A bug in this area rarely says what it is. It shows up as a twitch in a filter, a jump in a plot, a drift after a few minutes. By then the data has passed through three layers of code. To find the cause you need a habit: name the symptom (what you see), pick a measurement (what number would confirm a cause) and only then choose a fix.

The table you will use

Every failure in this lesson falls in one of three families. Data is lost (the queue overflowed). Data is late (the queue was read at the wrong time). Data is mis-dated (the clocks were mixed). The table maps what you see to what to measure.

SymptomCauseMeasureFix
A flat gap in the data, a regular spacing apartInterrupt delay beyond the headroom (Ch 4)Skip count per burst; edge-to-first-clock timeLower the watermark; shorten the handler; start DMA
Timestamps jitter from burst to burst, spacing inside bursts is cleanAnchor taken at read time (Ch 6)Timer capture minus software time at handler entryCapture the pin edge in hardware, or use the sensor counter
One interrupt, then silenceLatched watermark still above threshold after a partial read (Ch 3)Pin level after the read; FIFO byte countRead until below the mark; treat the pin as a level
Timestamps jump by 655.36 s after about 11 minutes24-bit counter wrapped unseen (Ch 8)Raw sensortime going backwards between burstsUnwrap every burst; count wraps with a host timer in sleep
Overflow at a high rate with tiny delaysBus too slow to drain while the chip writes (Ch 5)Bus bytes per second against the chip’s write rateUse SPI or a faster bus; lower the rate; drop a sensor
IMU and camera agree at start, then slide apartClock skew left uncorrected (Ch 1, 8)Residual of (chip time, host edge) pairs against timeFit offset and skew continuously

Now try it on cases. Each card gives a symptom as you might see it in a log. Pick the fix that addresses the real cause. A wrong pick tells you what that fix would actually do.

Diagnose the bench

Read the symptom and its measurement. Press the fix you would try first.

The six cases follow the table above. The numbers come from earlier chapters: BMI270 at 1,600 Hz, 13-byte frames, a 157-frame FIFO, a 24-bit sensortime of 39.0625 µs per tick.

Build the instruments before you need them

Every symptom above is easy to confirm if the driver keeps a few counters. Counters cost a few bytes and a few cycles. They turn a day of guessing into a minute of reading. A good IMU driver keeps at least the following.

cstruct imu_health {
    uint32_t bursts;            /* watermark interrupts handled */
    uint32_t frames;            /* sample frames parsed; expect ODR x seconds */
    uint32_t skipped;           /* sum of skip-frame counts: samples lost */
    uint32_t corrupt;           /* unknown headers seen by the parser */
    uint32_t irq_to_read_us_max; /* worst edge-to-first-clock delay */
    uint32_t irq_to_read_us_avg;
    uint16_t fifo_level_max;    /* highest frame count seen at read start */
    uint16_t wraps;             /* sensortime wraps counted */
    int32_t  skew_ppm;          /* current fitted chip clock error */
    int32_t  fit_resid_us_max;  /* worst residual of the clock fit */
};

Read the fields as a story. frames against ODR times uptime says whether anything was lost. skipped says how much. irq_to_read_us_max times the frame rate, plus the watermark, compared with 157 says how close you are to overflow, before it happens. skew_ppm should sit near the chip’s datasheet accuracy and move slowly. fit_resid_us_max catches a bad fit before the filter does.

Print the structure once a minute to a log, or send it with the telemetry. The best time to see a margin shrinking is a week before it becomes a bug. For how to see inside a running chip, with trace and cycle counters, see Seeing Inside a Running Chip, and for the bench side see Bench Work and Root Cause.

The habit. Count what you lose. Time what you wait. Fit what you assume. A driver that does these three things reports its own failures before the filter downstream is fooled.

On real hardware. Run your driver on a Nucleo for ten minutes with the health structure printed every 60 seconds. Then break it on purpose, one failure at a time: a 50 ms busy loop, a missing unwrap, a partial read. Check that exactly one counter moves each time. If two move, your counters overlap, and the next real failure will be harder to read.

After a 5-hour run you see: frames parsed equal 1,600 times uptime, skipped is zero, but the camera and IMU slide apart by 70 ms. Which counter or fit do you check first?

Chapter 11

Field Guide

Keep the numbers, the terms, the checklist and the core code, then follow the links onward

You can now follow a motion sample from the chip to your filter and say when it happened. The chip makes samples on its own clock. A FIFO holds them. A watermark tells you when to come. A burst read empties the queue. The skip count tells you what was lost. The sensor counter tells you when each sample was made in chip time, and a running line fit turns that into host time. Interpolation puts the samples on anyone else’s timeline.

The numbers that matter

WhatNumberSource and why it matters
BMI270 FIFO size2,048 bytesDatasheet, FIFO section. Sets how long you can ignore the chip.
BMI270 frame, accel + gyro1 + 6 + 6 = 13 bytes, 157 framesDatasheet frame layout; 157 is derived (2,048 / 13). Fills in 98.1 ms at 1,600 Hz.
BMI270 skip frame1 payload byte, capped at 0xFFDatasheet control frames. The count of lost frames.
BMI270 sensortime24 bits, 39.0625 µs per tick, wraps at 655.36 sDatasheet, sensor time. 625 µs is 16 ticks.
BMI270 ODR accuracyup to 1% (accel), 1.7% (gyro)Datasheet electrical tables, 25 °C. Why counting samples is not timing.
BMI270 bus limitsSPI 10 MHz, I2C 1 MHzDatasheet interface specs. Sets the burst time.
BMI270 default watermark512 bytes (register reset 0x0200)Datasheet register map: FIFO_WTM_0 and FIFO_WTM_1.
ICM-42688-P FIFO2,048 bytes; 16-byte packet with timestampTDK’s Linux driver source (header and buffer code).
ICM-42688-P watermark cap in TDK’s driver1,856 bytes = 116 packetsDriver comment: 12 packets kept for reading latency.
16-bit, 16 µs timestampwraps at 1.048576 sArithmetic from the driver’s timestamp width and resolution bit.
I2C 400 kHz throughputabout 44,400 bytes per secondDerived: 400,000 / 9 clocks per byte. 94% busy for 13-byte frames at 3,200 Hz.

The terms

ODR
Output data rate: how many samples the chip makes each second.
FIFO
A queue in the chip that holds samples until you read them, oldest first.
Frame, header
One entry in the FIFO, and the byte that says what it holds.
Watermark
The fill level at which the chip raises its interrupt. It sets latency, wake-ups and headroom.
Headroom
Time before a full FIFO loses samples: (capacity minus watermark) divided by frame rate.
Streaming, stop on full
The two overflow modes: keep the newest, or keep the oldest.
Skip frame
A control frame that counts the frames lost to overflow.
Ordinal
A frame’s number since the FIFO was last emptied, counting lost frames.
Sensortime
The chip’s free-running counter. Samples are made on its grid.
Offset, skew
The two numbers of the line from chip time to host time.
Jitter, drift
Random timing error that changes each burst, and steady error that grows with time.

The checklist

  1. Pick the frame content and the ODR. Work out the frame size and how many frames fit.
  2. Measure your worst-case interrupt delay. Set the watermark from the latency budget and the headroom rule.
  3. Choose the overflow mode that keeps the data you need. Log every skip count.
  4. Capture the pin edge with a hardware timer. Never date a burst from the moment you parse it.
  5. Read with DMA over the fastest bus the board allows. Check the bus is under about 50% busy.
  6. Parse with a header-aware parser that handles chunk edges and unknown headers.
  7. Date frames with the ordinal and the sensor counter. Unwrap the counter on every burst.
  8. Fit offset and skew continuously. Reject late outliers.
  9. Interpolate to query times. Return wait and hole as answers, not guesses.
  10. Print the health counters. Break each thing once on purpose and see which counter moves.

The core as code

This sketch ties the pieces together for one burst. It is the shape of a real driver, not a full one: error paths and the bus calls are left out.

c/* Watermark interrupt: capture, then read by DMA. */
void imu_irq(void)
{
    t_edge_ns = timer_capture_ns();                 /* hardware latched the pin edge */
    spi_dma_read_start(FIFO_DATA, rx_buf, fifo_bytes());   /* the CPU is free again */
}

/* DMA complete: parse, stamp, publish. */
void imu_dma_done(size_t n_bytes)
{
    struct burst_info bi = {0};  int ns = 0;
    for (size_t off = 0; off < n_bytes; ) {
        size_t used = fifo_parse_one(rx_buf + off, n_bytes - off, &batch[ns], &bi);
        if (used == 0 || bi.empty) break;            /* partial frame: keep for next time */
        if (batch[ns].valid) ns++;
        off += used;
    }
    health.frames += ns;  health.skipped += bi.skipped;
    stamp_burst(batch, ns, &bi, t_edge_ns, WM_FRAMES, PERIOD_NS);
    clock_fit_add(sensortime_unwrap(bi.sensortime), t_edge_ns);   /* Chapter 8 */
    ring_push(&imu_ring, batch, ns);                   /* Chapter 9 reads from here */
}
rust// The same unwrap, as a type that cannot be fed out of order by accident.
pub struct Unwrap24 { last: u32, hi: u64 }
impl Unwrap24 {
    pub fn feed(&mut self, raw: u32) -> u64 {
        if raw < self.last && self.last - raw > (1 << 23) { self.hi += 1 << 24; }
        self.last = raw;
        self.hi + raw as u64
    }
}

Where it sits in the field

Every sensor that batches has this shape. A camera has frame start and exposure time. A lidar has per-point timestamps. A microphone array has a sample clock that drifts against the host. The names change; the questions stay. What did the chip lose? When did it happen? Which clock says so? Later lessons in this course take each on in turn, and a lesson on multi-sensor time synchronisation covers the cross-device version.

Keep going

Sources

Every number above was checked against a source I opened. Bosch Sensortec, BMI270 datasheet (BST-BMI270-DS000; I read revision 1.2, document BST-BMI270-DS000-04): FIFO modes and size, frame headers, skip and sensortime frames, watermark and interrupt behaviour, sensor time resolution, ODR accuracy, bus limits. TDK InvenSense, the ICM-42688-P driver in the Linux kernel: inv_icm42600 (register bits, the 16-byte packet, the watermark cap) and inv_sensors_timestamp.c (period estimate and clamp). The TDK datasheet page itself returned no readable document text, so the ICM-42688-P facts come from TDK’s own source code, not the datasheet; check the datasheet before you rely on a register value. Zephyr project, sensor read and decode: the streaming API (sensor_stream, RTIO) that delivers FIFO frames to an application. Toy numbers (the 100 µs wake-up cost, the delay sequences, the noise) are labelled illustrative where they appear.

The takeaway. A sensor with a FIFO trades latency for sleep. The watermark sets the trade, the skip count keeps the loss honest, and the chip’s own counter, tied to the host by a running fit, turns a pile of batched samples back into a timeline you can trust.
Which set of choices follows the lesson for a 1,600 Hz IMU feeding a filter with a 40 ms latency budget and a measured worst interrupt delay of 25 ms?

Now press Present or Teach and explain one burst out loud, from memory: why the chip needs a queue, what the watermark trades, how a late interrupt loses samples and how the chip says so, why a read-time stamp lies, and how the sensor counter and a line fit fix it. Then go back to the instrument at the top, drag the latency past 36 ms, and explain each of the three stamps.

FIFO, Watermark and Timestamps
BMI270 datasheet · ICM-42688-P Linux driver · Zephyr sensor streaming · Back to microLearning