What an IMU Really Measures

An IMU never reports motion. It reports motion plus an offset plus noise, clipped to a range and sampled at a rate. Leave one still and its datasheet draws itself.

Your virtual IMU lies flat and still on a table, so the true reading is zero. Drag the bias and the noise density, switch the output rate, and watch the trace and the Allan plot beneath it. Then we build, piece by piece, every number a datasheet prints about it.

You need to know what a voltage and a sample are and a little C. We build the rest from zero. It follows Read a Datasheet and Reference Manual.

Part of Firmware from Zero to Expertise, IMU track. Built from primary sources, not slides: the TDK InvenSense ICM-42688-P datasheet (DS-000347, revision 1.6), the Kalibr IMU noise model and the MathWorks Allan variance guide. Full list in Chapter 8.

Leave the IMU still

8 mg
65 µg/√Hz

Model, not silicon. Defaults follow the ICM-42688-P accelerometer (65 µg/√Hz on X and Y, zero-g tolerance up to ±20 mg, Table 2). The slow wander in the Allan plot (0.01 mg per root second) is illustrative. The Allan curve is computed from the same generator run faster than real time. Bandwidth is taken as half the output rate.

Chapter 0

The Chip That Walks Away While Lying Still

See why a motion sensor that sits on a table still reports a journey, and what firmware must know to stop it

Put a phone flat on your desk. Nothing moves. Now imagine the phone tries to track its own position using only its motion sensor. It starts at zero. A minute later it says it has travelled the length of a football pitch.

Nobody pushed it. The sensor did not break. This is what every motion sensor does when you trust its numbers too far. This lesson explains why, and how a firmware engineer reads the datasheet to predict it.

What an IMU is

An IMU is an inertial measurement unit: a small chip that senses its own motion. It holds two sensors. The accelerometer measures how hard the chip is being pushed along each of three axes. The gyroscope measures how fast the chip is turning around each of three axes. Together that is six numbers, which is why such a chip is called a 6-axis IMU. Some IMUs add a magnetometer, a compass, for nine axes. This lesson stays with the six.

Both sensors are MEMS devices: micro-electro-mechanical systems. They are tiny mechanical parts, etched in silicon, smaller than a grain of sand. A part this small moves by distances smaller than a hair. The chip then turns that movement into a voltage, and an ADC (analog-to-digital converter, a circuit that turns a voltage into an integer) turns the voltage into counts. Firmware reads those counts over SPI or I²C.

So the number you read is never the motion itself. It is a chain: motion, then a mechanical part, then a voltage, then a count. Every link in the chain adds error. A datasheet lists those errors in a table, and firmware has to handle each one.

The walking dot

Here is the surprise in numbers. The ICM-42688-P is a high-grade 6-axis IMU from TDK InvenSense. Its datasheet (DS-000347, revision 1.6, Table 2) says the accelerometer may start with a zero-g offset of up to ±20 mg on any axis. That is the reading you get when the true acceleration is zero. Here g is the pull of gravity, 9.80665 m/s², and 1 mg is one thousandth of that.

Take 8 mg, which is well inside the tolerance. That is 0.0785 m/s² of acceleration that does not exist. To find a position, software adds up the acceleration to get a speed, then adds up the speed to get a distance. That double sum is called integration. A constant error b becomes a distance of ½·b·t² after t seconds.

xerr
The distance the software believes the chip moved, in metres.
b
The bias: the constant false acceleration, in m/s². Here 8 mg = 0.0785 m/s².
t
The time since the software started adding, in seconds. It is squared, so doubling the time gives four times the error.

½ × 0.0785 × 60² = ½ × 0.0785 × 3,600 = 141 m

After ten seconds the dot has moved 3.9 m. After a minute it has moved 141 m. Drag the sliders below and watch the curve bend upward.

Watch a still chip walk away

The curve is the position error for a chip that never moves. The dot is the time you pick. Raise the bias, then drag the time. Dashed lines mark a room and a football pitch.

8 mg
30 s

Pure arithmetic: x = ½ b t² with g = 9.80665 m/s². It assumes the chip is perfectly still and the only error is a constant offset. The 20 mg end of the slider is the datasheet’s maximum initial tolerance (ICM-42688-P Table 2). Real fusion software corrects most of this; Chapter 6 shows what remains.

The gyroscope has the same problem, only gentler. The datasheet gives an initial zero-rate output tolerance of ±0.5 °/s (Table 1). A gyroscope reports a turn rate, and software adds it up once to get an angle. A constant 0.5 °/s adds up to 30° in a minute. The phone on the desk slowly “turns” as well.

What a firmware engineer owns

Software far above the driver, an orientation filter for example, can only work with what the driver gives it. If the driver sets the wrong range, the filter sees clipped spikes. If the driver divides by the wrong number, every angle is off by a clean factor. If the driver picks a low output rate without a filter, the filter sees motion that never happened.

So the firmware engineer owns the first mile of the data. Your job is to know the size of each error before the data leaves the driver, to configure the chip so those errors are as small as the application allows, and to pass the numbers up in honest units. A datasheet is a list of promises about error. Reading it well is the skill this lesson trains.

There is also good news. The two sensors err in opposite ways. A gyroscope is smooth over a second but drifts over a minute. An accelerometer is noisy from sample to sample but always knows which way gravity points. Fusion software uses each to correct the other, and the later lessons in this track and complementary filters and AHRS show how. Fusion only works well when the driver reports each sensor's errors correctly.

Four ways a reading lies

The rest of this lesson takes the lies one at a time, in the order the signal meets them. Think of a reading as passing through four gates.

  1. What it measures: a mass on a spring, and gravity you cannot switch off.
  2. Range and resolution: the full-scale setting trades headroom for fineness.
  3. Bias: the slow error that integration turns into a walk.
  4. Noise density: the fast error, and how the bandwidth you choose sets its size.
  5. Output rate and the anti-alias filter: what sampling does to a fast vibration.
  6. The Allan plot: one curve that shows every error at once.
  7. Configuring the real chip: the registers and the C that turn counts into units.
  8. Field guide: the numbers, a checklist and where to go next.

Every chapter ends with an On real hardware note. It names a board and one measurement you can repeat at your own desk. The first one is the cheapest test in firmware: leave the board still and look at what it says.

On real hardware. Take any STM32 Nucleo or nRF52840 DK with an IMU breakout on SPI. Lay it flat. Read 1,000 samples of the Z axis and print the mean. The mean should be near +1 g (1,000 mg), not zero, and the other two axes should be near zero. The distance of those means from the ideal is your chip’s offset.

A chip lies still. Software integrates its acceleration twice and the position drifts away. What is the most direct cause?

Chapter 1

A Mass on a Spring, and a Mass That Shakes

Follow a push from the real world into a silicon structure, and see why a chip at rest still feels one g

You stand on a bus that brakes hard. You lean forward, and you did not decide to. Your body wanted to keep moving, and the bus did not. Your feet moved with the bus, and your upper body lagged.

An accelerometer is that lean, made tiny and made exact. Inside the chip sits a small block of silicon, the proof mass. Springs hold it in place. When the chip is pushed, the block lags behind the frame. The springs stretch. The stretch tells the chip how hard the push was.

From push to number

The block hangs between fixed plates, and each plate pair forms a small capacitor. A capacitor stores charge, and its capacitance rises as the plates come closer. When the block moves toward one plate, that capacitance goes up and the opposite one goes down. A circuit reads the difference as a voltage. The ADC then turns the voltage into a count.

The physics is one line. A spring with stiffness k holds a mass m. A steady acceleration a stretches it by x.

x
How far the block moves from its rest position, a tiny distance.
m
The mass of the block. A heavier block moves further for the same push.
a
The acceleration of the chip, the quantity we want.
k
The spring stiffness. A stiffer spring moves less, which gives more range and less signal.

The stretch is proportional to the push. Double the acceleration and the block moves twice as far. That proportionality is what lets a single number describe the whole thing, and Chapter 2 gives it a name: the sensitivity.

Why a chip at rest reads one g

Lay the chip flat on a table. The table pushes up on it with a force that cancels gravity, so the chip does not accelerate. But the block inside is held by springs, and the springs must hold it up against gravity. They stretch just as they would for a push of one g. The accelerometer reports +1 g on the axis pointing up.

So an accelerometer does not measure acceleration. It measures specific force: the push on the block by its springs, per unit mass. Gravity itself is invisible to it, because gravity pulls the block and the frame alike. Only the table, or your hand, or a rocket, shows up.

This explains a strange fact. Drop the chip. In free fall the frame and the block fall together and the springs do not stretch. The reading is zero on every axis. A chip lying on a table reads one g. A chip falling toward the floor reads zero. Phone makers use this for drop detection.

It also gives the first useful firmware trick. Tilt the chip by an angle θ. Gravity now splits across two axes. The Z axis reads cosθ times g and the X axis reads sinθ times g. At 30°, Z reads 0.866 g (866 mg) and X reads 0.5 g (500 mg). Two readings give the angle: θ = atan2(ax, az). Try it.

Tilt the chip, or drop it

Left: the chip, its proof mass and the pull of gravity. Right: what the X and Z axes report. Drag the tilt. Then press Free fall and see every bar drop to zero.

30°

Ideal chip: no bias, no noise, no clipping. The readings are g times sine and cosine of the tilt about the Y axis. Real readings add the errors the next chapters describe.

One sample, from end to end

Follow one number through the chain. The chip sits flat. The true specific force on Z is 1 g. At a range of ±4 g the sensitivity is 8,192 LSB/g, so the ideal count is 1 × 8,192 = 8,192. The ADC adds a little bias and noise, so the chip may output 8,201. Firmware reads the two bytes 0x20 and 0x09, joins them into 0x2009 = 8,201, and divides by 8,192. The result is 1.0011 g. The 0.0011 g is 1.1 mg: a small mix of offset and noise.

The gyroscope works the same way. A true turn of 90 °/s at ±250 °/s gives 90 × 131 = 11,790 counts. Every link in the chain can be written as a number, and so every error can be measured.

How a gyroscope feels a turn

A gyroscope is harder, because a block on a spring cannot tell that it is turning. The trick uses the Coriolis effect. Imagine you walk outward along the spoke of a spinning merry-go-round. The ground under you moves faster the further out you go, so you feel pushed sideways. That sideways push is the Coriolis force.

The gyroscope chip makes a block shake back and forth on purpose, thousands of times a second. The ICM-42688-P datasheet lists its gyroscope mechanical frequencies as 25, 27 and 29 kHz (Table 1). If the chip turns, the shaking block is pushed sideways. The sideways push is proportional to the turn rate, and a second sensor, built like the accelerometer above, measures it. The output is a rate in degrees per second.

This costs power and adds a startup delay. The datasheet gives 30 ms from gyro enable to a drive that is ready (Table 1), and says the gyroscope must stay on for at least 45 ms after turning on. An accelerometer needs only 10 ms to come out of sleep (Table 2). Firmware has to wait for these times, and Chapter 7 does.

On real hardware. On an STM32 Nucleo with an IMU on SPI, read the three accelerometer axes while you tilt the board by hand. Plot the square root of x² + y² + z². It should stay near 1 g whatever the tilt. Then drop the board a short way onto a soft cushion and watch the magnitude fall toward zero for a moment.

A phone with a working accelerometer is dropped. For the half second it falls, what does the accelerometer report?

Chapter 2

Full-Scale Range: Headroom Against Fineness

Choose how many g the chip can see, and learn what each choice costs in clipping and in counts

You are setting up a ruler. A ruler that is two metres long can measure a door. A ruler that is ten centimetres long cannot. But the ten-centimetre ruler has finer marks. A fixed number of marks has to cover the whole length, so a longer ruler has marks further apart.

An IMU has the same trade. Its ADC produces a fixed number of codes. The full-scale range (FSR, also FS) is the largest value the chip can report on an axis. You choose it. A bigger range sees harder knocks. A smaller range sees finer detail.

Counts, LSBs and sensitivity

The ICM-42688-P has a 16-bit ADC with output in two's complement form (Table 1 and Table 2 of DS-000347). That means a signed whole number from −32,768 to +32,767. The step between two neighbouring numbers is one LSB, the least significant bit. The datasheet states how many LSB make one unit. That figure is the sensitivity, also called the scale factor.

For the accelerometer, the datasheet gives four settings. At ±16 g the sensitivity is 2,048 LSB/g. At ±8 g it is 4,096. At ±4 g it is 8,192. At ±2 g it is 16,384. Each time the range halves, the sensitivity doubles. You can check this with arithmetic: 32,768 codes spread over ±2 g (a span of 2 g on each side) is 16,384 codes per g.

The gyroscope works the same way, with eight ranges. At ±2000 °/s the sensitivity is 16.4 LSB per °/s. At ±250 °/s it is 131. At the narrowest, ±15.625 °/s, it is 2,097.2 LSB per °/s.

a
The physical value, in g (or in degrees per second for the gyroscope).
raw
The signed 16-bit integer your firmware reads from the data registers.
S
The sensitivity for the range you chose, in LSB per g. It changes when you change the range.

raw = 6,000 at ±4 g: a = 6,000 / 8,192 = 0.732 g   |   raw = 6,000 at ±16 g: a = 6,000 / 2,048 = 2.93 g

The same raw number means four times more at the wider range. This is a classic bug. Firmware switches the range and forgets to change the divisor, and every reading becomes wrong by a clean factor of 2, 4 or 8.

What a count is worth

One LSB at ±16 g is 1/2,048 g, which is 0.488 mg. At ±2 g it is 1/16,384 g, which is 0.061 mg. So the narrow range sees steps eight times finer.

Does finer always help? Only down to the noise. The datasheet gives the accelerometer RMS noise as 0.65 mg on X and Y at 100 Hz bandwidth (Table 2). At ±16 g one LSB is 0.488 mg, so the noise spans about 1.3 counts. At ±2 g one LSB is 0.061 mg and the noise spans about 11 counts. The extra fineness there is mostly describing the noise more carefully. It is not describing the motion any better. So the fine range does not buy you much unless the noise is lower than one LSB.

The cost of too small a range

The other side is clipping. Suppose a robot arm hits a stop and the chip feels a 6 g spike. At ±4 g the largest code, +32,767, means 4 g. The spike is cut off flat. The chip reports 4 g for as long as the true push stays above that level. The peak, and the shape of the peak, are lost. No later maths can bring them back.

A clipped reading is also dangerous inside a filter. The filter believes 4 g and may conclude that the hit was gentler than it was. If you then integrate the signal, the speed change is too small.

The rule is simple. Pick the smallest range that is larger than the largest push you expect, with a margin. As a rough guide, not a datasheet figure: gentle wrist motion stays within a few g, a footstep can reach several g, and a crash can pass 16 g. Measure your own motion. Try the device and see where each range fails.

Choose the range, meet the clip

The blue wave is the true push on the chip. The warm wave is what the chip reports. Pick a range, then drag the size of the push past it.

6 g

Sensitivities are the ICM-42688-P’s (Table 2): 16,384, 8,192, 4,096 and 2,048 LSB/g. The wave is an illustrative sine. The device clips at ±32,767 counts, which is the largest value of a 16-bit two’s complement word. The chip’s exact behaviour at the limit is not specified in the part of the datasheet read for this lesson.

Other gain errors

The sensitivity is not perfect either. The datasheet gives a scale factor initial tolerance of ±0.5 % (Table 2), a nonlinearity of ±0.1 % and a cross-axis sensitivity of ±1 %. Take the ±0.5 % at a reading of 1 g. It is 5 mg of possible error. That is eight times the 0.65 mg noise. At 1 g, gain error is bigger than noise. Chapter 3 and the later lesson on on-device calibration cover how firmware measures and removes it.

The gyroscope has the same set of tolerances. Its scale factor initial tolerance is ±0.5 % and its nonlinearity is ±0.1 % (Table 1).

On real hardware. On an nRF52840 DK or STM32 Nucleo with an ICM-42688-P breakout, set the range to ±2 g and shake the board hard. Print the raw Z value. You will see it pin at about 32,767. Repeat at ±16 g and the same shake stays in range. Count how many samples sit at the limit in each case.

Firmware reads raw = 4,096 from the accelerometer at ±8 g and divides by 16,384, the ±2 g sensitivity. What does it report, and what is the truth?

Chapter 3

Bias: The Slow Error That Integration Loves

Measure an offset, subtract it, and find out why it comes back when the chip warms up

A kitchen scale shows 12 g with nothing on it. You press the tare button and it shows zero. Ten minutes later, with nothing on it, it shows 3 g. The scale did not break. Its zero moved while it warmed.

An IMU has the same trouble on every axis. The offset has a name: bias. Bias is the reading the chip gives when the true input is zero. It changes slowly, over seconds, minutes and degrees. Noise, which Chapter 4 covers, changes quickly. This split, slow error against fast error, runs through the whole lesson.

What the datasheet promises

The ICM-42688-P datasheet (DS-000347, revision 1.6) states the accelerometer's zero-g output as an initial tolerance of ±20 mg for any axis at board level (Table 2). It then adds a change with temperature of ±0.15 mg per °C across −40 to +85 °C. For the gyroscope, the zero-rate output (ZRO) initial tolerance is ±0.5 °/s at 25 °C, with a change of ±0.005 °/s per °C from 0 to +70 °C (Table 1).

Look at the tags on those lines. The datasheet marks the zero-g tolerance and the temperature changes as derived from validation or characterization, not tested in production. That matters: your unit may differ from the typical part, and the datasheet does not promise otherwise. Learning to read those small note numbers is part of the skill from the previous lesson, Read a Datasheet.

What a bias does in practice

Chapter 0 showed the walk: 8 mg double-integrated gives 141 m in a minute. Bias also fools a tilt estimate. Gravity gives the X axis sinθ times g. If X has a 20 mg offset, a flat chip reads 20 mg on X and the tilt formula says θ = asin(0.020) = 1.15°. A tilt of just over one degree appears from nothing. For a drone holding level, that is a drift to one side.

The gyroscope is even more direct. Its output is a rate, and an angle is its running sum. A constant offset b gives an angle error of b times t. At 0.5 °/s that is 30° in a minute and 1,800° in an hour. Software that integrates a raw gyroscope for long is wrong within seconds.

The firmware fix, and where it fails

The first cure is easy. At power-up, while the device is known to be still, read many samples and average them. The mean is your estimate of the bias. Subtract it from every later reading. This is a bias calibration.

Averaging works well on noise. If the noise is 0.65 mg rms (Table 2, at 100 Hz bandwidth) and you average 100 samples, the noise left in your estimate falls by the square root of 100, which is 10. The estimate is good to about 0.065 mg. That is far smaller than a 20 mg offset.

The cure has one hole. It gives you the bias at that moment and that temperature. Suppose you calibrate the gyroscope at 25 °C. The chip then warms to 55 °C inside a case. The temperature changed by 30 °C. The datasheet allows the zero to move by 0.005 × 30 = 0.15 °/s. Integrated for a minute, that is 9° of new error. For the accelerometer, 0.15 mg/°C × 30 °C = 4.5 mg.

residual = tempco × (T − Tcal)  =  0.005 °/s per °C × (55 − 25) °C = 0.15 °/s

So a good driver does more than one calibration. It reads the on-chip temperature, which the ICM-42688-P exposes as TEMP_DATA, and it either re-zeroes whenever it detects stillness or fits a temperature curve. The later lesson on on-device calibration builds that. Here the point is to see the shape of the problem. Move the temperature in the device below.

Zero it, then warm it

The warm line is the worst-case zero-rate error the datasheet allows as the chip changes temperature. Press Zero at this temperature, then drag the temperature away.

25 °C

Worst-case line from Table 1: a ±0.005 °/s per °C change over 0 to 70 °C, drawn as a straight line from a 0.5 °/s offset at 25 °C. Real parts curve and vary; the datasheet marks this row as characterized, not tested in production. Angle error per minute is the residual times 60 s.

It helps to write the bias as counts. At a range of ±250 °/s, the sensitivity is 131 LSB per °/s. A bias of 0.5 °/s is 0.5 × 131 = 65.5 counts. So a gyroscope that lies perfectly still can legally sit 65 counts away from zero. The same bias at ±2000 °/s, with 16.4 LSB per °/s, is about 8 counts. The physical error is the same; only the count changes. This is another reason to convert to units before you compare numbers.

Slow wander: bias instability

Even at fixed temperature, bias is not perfectly fixed. It wanders by small amounts over minutes. Engineers call this bias instability. It is the best the bias can be held, after you remove everything that you can model. Datasheets for high-end gyroscopes quote it in degrees per hour. Chapter 6 shows how it appears on the Allan plot, and why no amount of averaging removes it.

On real hardware. Put an STM32 Nucleo with an IMU board in a drawer to keep it still. Log the gyroscope Z mean over each 10-second window for ten minutes, and log the TEMP_DATA value too. Then hold a warm hand over the board for two minutes and log again. Plot mean against temperature. The slope is your chip's own tempco.

You average 400 still samples to find the gyroscope bias, then use it for ten minutes while the chip warms by 20 °C. What limits the accuracy now?

Chapter 4

Noise Density: Noise Per Square Root of Bandwidth

Turn the datasheet's odd unit into a number of milli-g on your own trace, and see which knob changes it

You listen to a radio between stations. You hear a steady hiss. The hiss is made of tiny random signals at every frequency at once. If you could cut the radio so that it only hears a narrow slice of frequencies, the hiss would get quieter. A narrower slice holds less hiss.

The IMU's electrical noise acts the same way. It is spread evenly across all frequencies, so engineers call it white noise, by analogy with white light. The noise you see on a trace depends on two things: how loud the hiss is per slice of frequency, and how wide a slice you let in.

A strange unit with a good reason

The datasheet gives the accelerometer noise as 65 µg/√Hz on X and Y and 70 µg/√Hz on Z (ICM-42688-P Table 2, measured at 10 Hz). The gyroscope is 0.0028 °/s per √Hz (Table 1). This is the noise density. Read the unit aloud: micro-g per root hertz.

Why the root? Independent random contributions add in power, which is the square of the amplitude. Each hertz of bandwidth brings the same power d². With a bandwidth of BW hertz, the total power is d² times BW. Take the square root to get back to an amplitude.

σ
The RMS noise on your trace: the typical size of the random wiggle, in the same unit as d without the per-root-hertz part.
d
The noise density from the datasheet, for example 65 µg/√Hz.
BW
The noise bandwidth in hertz: how much of the frequency range your filter lets through.

65 µg/√Hz × √100 Hz = 65 × 10 = 650 µg = 0.65 mg

That matches the datasheet's own row. Table 2 lists an RMS noise of 0.65 mg on X and Y at a bandwidth of 100 Hz, and a footnote says the value is calculated from the power spectral density. For the gyroscope, 0.0028 × 10 = 0.028 °/s, which is the 0.028 °/s-rms in Table 1. Good. You can now check a datasheet's rows against each other, a useful habit.

The knob you control

You do not control d. The silicon and the circuit set it. You do control BW, in two ways. The first is the output data rate, which Chapter 5 covers. The second is the digital filter on the chip. The datasheet says its programmable anti-alias filter “allows trading off RMS noise vs. latency for a given ODR” (section 5.3 and the filter block description). A narrower filter gives lower noise and a slower response.

Take the same part with a 1 kHz output rate. If the filter passes 500 Hz, the noise is 65 × √500 = 1.45 mg. If you narrow it to 50 Hz, it is 65 × √50 = 0.46 mg. A tenfold cut of bandwidth cut the noise by only √10, about 3.2 times. Noise falls slowly. To halve it, you must quarter the bandwidth.

Open the filter, hear the hiss

Top: one accelerometer axis at rest, as a noisy trace. Bottom: the RMS noise against bandwidth for your density. Drag the bandwidth and the density.

65 µg/√Hz
100 Hz

The trace is a seeded random sequence scaled to σ = d √BW; it is a model of white noise, not real chip data. The 65 µg/√Hz default and the 0.65 mg at 100 Hz are the ICM-42688-P’s (Table 2). A real filter has a gentle edge, so the effective noise bandwidth differs a little from the −3 dB setting.

A worked example with the gyroscope

The gyroscope's density is 0.0028 °/s/√Hz. At 100 Hz bandwidth the noise is 0.028 °/s. Now integrate that noise to get an angle. Each sample adds a small random step, and random steps add as a random walk: the angle error grows with the square root of time, not with time. With the convention of Chapter 6, the angle random walk coefficient is N = 0.0028/√2 = 0.00198 ° per root second. After one hour (3,600 s) the angle noise is 0.00198 × √3,600 = 0.00198 × 60 = 0.119°.

Compare that with the bias. A bias of 0.5 °/s gives 1,800° in the same hour. White noise alone would drift the angle by only 0.12°. The noise is small next to the bias. This is the right order of work: remove the bias first, then worry about the noise.

Averaging, and when it helps

Averaging N independent samples cuts the noise by √N. A mean of 100 samples has one tenth the noise of one sample. This only works if the noise is independent from sample to sample, which white noise is. It does not work on bias. A bias is the same in every sample, so the mean keeps all of it. That is exactly why this chapter and the last stand apart.

There is a catch. Samples are only independent if they are far enough apart in time. If you read at an output rate above the filter bandwidth, neighbouring samples share noise, and averaging them helps less than √N. The Kalibr project's IMU noise model states the converse: the discrete-time conversion σd = σc √rate assumes the signal was low-pass filtered to half the sample rate. We use that assumption throughout.

On real hardware. Lay a Nucleo with an IMU flat. Log 4,096 samples at a 100 Hz output rate. Compute the standard deviation of one axis. It should land near the datasheet figure, within a factor of about two for a hand-wired board. Then change the filter bandwidth and repeat. Plot sigma against the square root of bandwidth. The points should fall near a straight line.

A gyroscope has a noise density of 0.0028 °/s/√Hz. You raise the bandwidth from 25 Hz to 100 Hz. How does the RMS noise change?

Chapter 5

Output Rate and the Anti-Alias Filter

See how a fast vibration, sampled too slowly, turns into a slow wave that was never there

In a film, a car wheel sometimes seems to spin slowly backward while the car drives forward. The camera takes 24 pictures a second. The wheel turns almost one full turn between pictures. Each picture shows the spokes a little behind where they were, so your eye reads a slow backward turn.

No wheel ever turned backward. The film sampled too slowly for the motion. An IMU samples the world in exactly the same way, and it can fool your firmware in exactly the same way.

The output data rate

The output data rate (ODR) is how many samples per second the chip puts in its data registers and its FIFO. The ICM-42688-P lets you pick from 12.5 Hz to 32 kHz for the gyroscope and from 1.5625 Hz to 32 kHz for the accelerometer (Table 1 and Table 2). In the register map you choose it with four bits: in GYRO_CONFIG0 the value 0110 means 1 kHz, 0111 means 200 Hz, and 1000 means 100 Hz.

A higher rate shows faster events and costs more: more bus traffic, more power and more noise. Chapter 4 showed why. A lower rate saves all of that, but it brings in a danger.

Folding

The sampling theorem gives the limit. A sampler running at fs samples per second can only describe frequencies below fs/2. That limit is the Nyquist frequency. A real vibration above it does not vanish. It aliases: it folds back into the allowed range and shows up as a lower frequency that looks perfectly real.

falias
The frequency you will see in the samples, between 0 and half the sample rate.
f
The true frequency of the vibration, in hertz.
fs
The sample rate (the ODR), in hertz. Round to the nearest whole multiple.

f = 130 Hz, fs = 100 Hz: round(1.3) = 1, so falias = |130 − 100| = 30 Hz

Take a small motor spinning at 7,800 rpm. That is 130 turns per second, so it shakes the board at 130 Hz. You sample at 100 Hz. The samples show a clean 30 Hz wave. Your orientation filter now sees a 30 Hz wobble, a speed at which a hand or a robot arm could really move. It reacts. The wobble is a fake.

Why no code can fix it afterwards

Once the samples exist, the fake 30 Hz wave and a real 30 Hz wave look identical. Nothing in the numbers tells them apart. The cure must happen before sampling. We must remove the frequencies above half the sample rate while they are still frequencies, not yet samples. A circuit that does this is an anti-alias filter: a low-pass filter that lets slow signals through and stops fast ones.

The ICM-42688-P puts such a filter in the digital path. Its datasheet describes a programmable anti-alias filter for each of the gyroscope and the accelerometer, a second-order low-pass with a bandwidth you set from 42 Hz to 3,979 Hz (section 5.3). You write three numbers per sensor, called AAF_DELT, AAF_DELTSQR and AAF_BITSHIFT, taken from a table in the datasheet. For example, a 42 Hz cut needs 1, 1 and 15, and 84 Hz needs 2, 4 and 13. You can also switch the filter off with GYRO_AAF_DIS or ACCEL_AAF_DIS, and the datasheet notes that both the notch filter and the anti-alias filter work only in low-noise (LN) mode.

For output rates below 1 kHz, the datasheet lists the low-pass response as a user-set 5 to 500 Hz band instead (the Low Pass Filter Response row in Tables 1 and 2). The idea is the same. The chip measures at a high internal rate, filters, and then hands you every Nth sample. This is why a good IMU can offer a low ODR without aliasing the way a bare sampled voltage would.

Sample a vibration, catch an alias

Blue is the true vibration. Dots are the chip's samples and the warm line joins them. Drag the vibration above half the rate, then switch the filter on.

130 Hz

Model, not silicon. The filter is drawn as a second-order low-pass with its −3 dB point at 40% of the output rate, which is an illustrative choice; the real part’s bandwidth comes from the AAF table in section 5.3 of the datasheet. The alias formula is exact for ideal sampling.

Look at what the filter really does. The alias does not become zero. A second-order filter leaves a little of any tone beyond its cut, and a tone at 130 Hz against a 40 Hz cut is held to about 9 % of its size, not nothing. This is why we also want the rate well above the signal. If you only care about movement below 20 Hz, a rate of 100 Hz with a filter at 40 Hz gives the vibration a safe gap.

On real hardware. Clamp a small hobby motor next to the board on a Nucleo with an IMU. Set 100 Hz output with the anti-alias filter disabled, run the motor, and take an FFT of the Z axis. Find the strongest peak and compare it with the formula. Then enable the filter and repeat. The peak should shrink.

A fan shakes the board at 180 Hz. The IMU samples at 100 Hz with no anti-alias filter. Which frequency appears in the data?

Chapter 6

Leave It Still: The Allan Plot

Draw one curve from a still recording and read the noise, the wander and the drift of a sensor off its three regions

You want to know how steady a clock is. One way is to measure it for one second and see how much it gained. Then measure for ten seconds, a minute, an hour. For a good clock, longer measurements are more exact at first, because random errors average out. Later, slow drift takes over and longer measurements get worse.

The same test works for an IMU. You lay it still and record. You then ask: if I average the reading over a window of length τ, how much do two neighbouring windows differ? The answer, plotted against τ, is the Allan deviation. The curve is the one picture that shows every error of Chapters 3 and 4 at once.

How the curve is built

Take your still data and cut it into windows of length τ. Average each window. Look at the difference between each pair of neighbouring averages. Square the differences, average them, and halve the result. That is the Allan variance at τ. Its square root is the Allan deviation. Repeat for many window lengths, say 0.1 s, 0.2 s, 0.4 s and so on, and plot on log-log axes.

σ2(τ)
The Allan variance for windows of length τ. Its square root is the Allan deviation you plot.
E[…]
The average over every pair of neighbouring windows in the recording.
ȳk+1
The mean reading over the next window.
ȳk
The mean reading over the window before it.

Why use this and not the ordinary spread of the data? An ordinary standard deviation measures against the overall mean, and a slow drift makes that mean meaningless. Differences between neighbours ignore slow shifts and slow shifts only show up at long windows. IEEE Standard 952 for fibre-optic gyroscopes uses the same approach, and the technique comes from the study of clocks.

Reading the three regions

White noise comes first. Each sample has spread σs. A window average of m samples has spread σs/√m. The difference of two such averages has variance 2σs²/m, and halving gives σs²/m. So the Allan deviation falls as 1/√m: a straight line of slope −1/2 on the log-log plot. With a sample spread σs = d√(fs/2) and m = τfs, the line is

σ(τ) = d / √(2τ)   →   65 µg/√Hz gives 46 µg at 1 s and 14.5 µg at 10 s

The sample rate has vanished. This is why the noise density, and not the sample spread, is the honest number on a datasheet. Many references write this line as N/√τ and call N the angle random walk (for a gyroscope) or the velocity random walk (for an accelerometer). They read N off the line at τ = 1 s. Be careful with the factor: with a one-sided density d, N = d/√2.

Next comes the bottom. Averaging cannot remove a slow wander. At some window length the slow part of the signal grows as fast as the noise falls, and the curve turns flat. The lowest point of the curve is the bias instability, the best steadiness the sensor can offer. The usual convention says the flat level is about 0.664 times the bias instability coefficient B, so B is the floor divided by 0.664 (the MathWorks Allan variance guide gives this factor).

Last, at long windows the curve rises with slope +1/2. This is a random walk of the bias: the zero itself drifts like a drunk person's path, with no pull back. The Kalibr noise model reads it as K at τ = 3 s on the rising line. A drift like this means that waiting longer makes things worse. After that point you must re-zero, not average.

Build a sensor, read its curve

Three error sources feed one still recording. Turn each up and watch which part of the curve moves. Then change the length of the recording.

65 µg/√Hz
12 µg
0 µg per root second

Simulated at 10 samples per second. Errors: white noise with the density you set (bandwidth 5 Hz), a slow wander modelled as a first-order Gauss-Markov process with a 300 s memory, and an optional random walk. This is a model, not a measurement. The curve is the overlapping Allan deviation computed live in your browser. The 0.664 factor is the convention in the MathWorks guide; for this Gauss-Markov wander it is only a rough estimate.

Notice what the length of the recording does. With ten minutes of data, the long-window end has only a handful of windows and the curve is ragged and wrong. The Kalibr documentation advises ideally 15 to 24 hours of still data for a real sensor. Bias instability needs patience to measure.

On real hardware. Put an STM32 Nucleo with an IMU on a firm shelf away from fans and footsteps, powered for a quarter hour first so it warms up. Log at 100 Hz for an hour to a laptop over a serial link. Compute the Allan deviation of the gyroscope Z axis offline. Compare the line at 1 s with the datasheet density divided by the square root of two.

An Allan deviation curve falls with slope −1/2, bottoms out, then rises with slope +1/2. What does the rising part tell you?

Chapter 7

Turning the Knobs on a Real Chip

Set the range, the rate and the power mode with three register writes, and turn 14 bytes into units

You now know the knobs: range, output rate, filter, mode. Each one is a few bits in a register on the chip. This chapter shows the exact bytes for the ICM-42688-P, because the datasheet is where every firmware engineer ends up. The earlier lesson Read a Datasheet and Reference Manual showed how to find the page. Here we use it.

The conversation over SPI

The chip talks over SPI, a four-wire bus (the hardware interfacing lesson builds it from zero). Each transaction begins with an address byte. The first bit of that byte says read or write: 1 for a read, 0 for a write (section 9.6, the SPI interface). The other seven bits are the register address. After that come one or more data bytes, most significant bit first. The datasheet gives a maximum SPI clock of 24 MHz.

The first thing to read is WHO_AM_I at address 0x75. On this chip it must return 0x47. If it does not, your wiring, your SPI mode or your chip select is wrong, and no later read can be trusted.

Three registers set the personality

GYRO_CONFIG0 (address 0x4F) holds the gyroscope range in bits 7:5 and the output rate in bits 3:0. The range codes are 000 for ±2000 °/s, 001 for ±1000, 010 for ±500, 011 for ±250, and so on down to 111 for ±15.625. The rate codes are 0110 for 1 kHz (the reset default), 0111 for 200 Hz, 1000 for 100 Hz, and 1010 for 25 Hz. ACCEL_CONFIG0 (0x50) has the same layout: range in 7:5 (000 is ±16 g, 001 is ±8 g, 010 is ±4 g, 011 is ±2 g) and rate in 3:0. PWR_MGMT0 (0x4E) switches the sensors on: GYRO_MODE in bits 3:2 and ACCEL_MODE in bits 1:0, where 11 means low-noise mode. At reset both are 00, so both sensors are off.

Choosing ±250 °/s (011) and 100 Hz (1000) builds the byte 0110 1000, which is 0x68. Choosing ±4 g (010) and 100 Hz gives 0100 1000, which is 0x48. Try the builder, then see the code.

Build GYRO_CONFIG0

Pick a range and a rate and watch the byte change. Then drag a raw count and see what it means in the range you chose.

3276

Codes and sensitivities are from DS-000347 revision 1.6: GYRO_CONFIG0 at 0x4F (section 14.37) and the gyroscope sensitivity rows of Table 1 (131 LSB per °/s at ±250, 16.4 at ±2000). This is a model of the register, not a connection to a chip.

The code

Below is the whole setup and one burst read in C. The register addresses and values are from the datasheet; the spi_* and delay functions are yours to supply for your board (HAL, Zephyr or bare metal). This listing is a teaching sketch, not tested on hardware here.

c/* ICM-42688-P, SPI. Addresses and codes: DS-000347 rev 1.6 */
#define REG_TEMP_DATA1  0x1D   /* 14 bytes: temp, accel XYZ, gyro XYZ */
#define REG_PWR_MGMT0   0x4E
#define REG_GYRO_CFG0   0x4F
#define REG_ACCEL_CFG0  0x50
#define REG_WHO_AM_I   0x75   /* must read 0x47 */

static const float ACCEL_LSB_PER_G   = 8192.0f;  /* +-4 g   (Table 2) */
static const float GYRO_LSB_PER_DPS  = 131.0f;   /* +-250 dps (Table 1) */

int icm_init(void) {
    if (spi_read8(REG_WHO_AM_I) != 0x47) return -1;   /* wrong chip or wiring */
    spi_write8(REG_GYRO_CFG0,  (3u << 5) | 8u);  /* +-250 dps, 100 Hz = 0x68 */
    spi_write8(REG_ACCEL_CFG0, (2u << 5) | 8u);  /* +-4 g,     100 Hz = 0x48 */
    spi_write8(REG_PWR_MGMT0, (3u << 2) | 3u);   /* gyro + accel low-noise = 0x0F */
    delay_us(200);                                /* no writes for 200 us when leaving off */
    delay_ms(45);                                 /* gyro must stay on at least 45 ms */
    return 0;
}

typedef struct { float ax, ay, az, gx, gy, gz, temp_raw; } imu_sample_t;

imu_sample_t icm_read(void) {
    uint8_t b[14];
    spi_read(REG_TEMP_DATA1 | 0x80, b, 14);       /* bit 7 set = read */
    int16_t r[7];
    for (int i = 0; i < 7; i++)
        r[i] = (int16_t)((b[2*i] << 8) | b[2*i + 1]); /* high byte first */
    imu_sample_t s = {
        r[1] / ACCEL_LSB_PER_G, r[2] / ACCEL_LSB_PER_G, r[3] / ACCEL_LSB_PER_G,
        r[4] / GYRO_LSB_PER_DPS, r[5] / GYRO_LSB_PER_DPS, r[6] / GYRO_LSB_PER_DPS,
        (float)r[0]
    };
    return s;
}

Read the data path in order. The 14 bytes start at TEMP_DATA1 (0x1D). Temperature takes two bytes, then accelerometer X, Y and Z at 0x1F to 0x24, then gyroscope X, Y and Z at 0x25 to 0x2A, each as a high byte then a low byte. Joining the bytes and casting to a signed 16-bit integer gives the raw count. Dividing by the sensitivity gives g or degrees per second. The divisor must match the range you wrote, which is the bug from Chapter 2. A good driver keeps the range and the sensitivity in one place, so they cannot drift apart.

Connect the numbers to what you learned. At ±250 °/s and a bandwidth of 100 Hz, the gyroscope noise of 0.028 °/s is 0.028 × 131 = 3.7 counts. The bias tolerance of 0.5 °/s is 65 counts. A still gyroscope can read 65 counts away from zero and still be within the datasheet.

The anti-alias filter lives in other register banks. Its three numbers sit in bank 1 for the gyroscope and bank 2 for the accelerometer, and you reach a bank by first writing its number to REG_BANK_SEL at 0x76. We leave those writes to the next lessons, where the FIFO and timestamps (FIFO, watermark and timestamps) come in.

A worked example, byte by byte

Suppose the burst returns, for the gyroscope X axis, the two bytes 0x00 and 0x83. Join them: 0x0083 = 131. At ±250 °/s, 131 divided by 131 gives exactly 1.000 °/s. Now take 0xFF and 0x7D. Joined, that is 0xFF7D = 65,405 as an unsigned number. As a signed 16-bit number, it is 65,405 − 65,536 = −131, which is −1.000 °/s. This is the two's complement step. In C the cast to int16_t does it for you. If you forget the cast and store the value in an unsigned type, every negative reading becomes a huge positive one.

The byte order matters too. The datasheet puts the upper byte at the lower address (ACCEL_DATA_X1 holds bits 15 to 8 at 0x1F, ACCEL_DATA_X0 holds bits 7 to 0 at 0x20). The code shifts the first byte left by eight. If you swap them you get numbers that look like noise.

Why one burst

The code reads all 14 bytes in one SPI transaction. One reason is speed. Each transaction costs a chip-select edge and an address byte. A burst of 14 data bytes plus 1 address byte is 15 bytes, or 120 clock cycles. At the 24 MHz maximum that takes 5 µs; at a more common 8 MHz it takes 15 µs. A second reason is consistency. Reading the values in separate transactions could straddle a new sample, and then X would come from one instant and Z from the next. For a fast vibration that mismatch looks like noise.

The order of work in your init code is therefore: check identity, write the three configuration registers, wait the required times, then start reading. The next lesson, on the FIFO, replaces the polling read with a buffer in the chip, so that a late interrupt no longer loses samples.

On real hardware. On an STM32 Nucleo-F4 or nRF52840 DK, wire an ICM-42688-P breakout to SPI. Run icm_init and print the WHO_AM_I value. Then print 100 samples at rest and compare the Z mean with 1 g, as in Chapter 0. Change the range to ±2 g and fix the divisor to 16,384. If the printed Z still reads about 1 g, you changed both correctly.

You write ACCEL_CONFIG0 = 0x68. Which range and rate did you choose?

Chapter 8

Field Guide: The IMU on One Page

Review every number and term, run the checklist before you trust a reading, and find the next lesson

An IMU's reading is the truth plus a chain of small lies. You can now name each lie, find its size in a datasheet, and say what firmware does about it. This chapter gathers it all in one place. Come back here when you open a new datasheet.

The one-paragraph summary

An accelerometer is a proof mass on springs; it reads specific force, so a still chip reads +1 g and a falling chip reads zero. A gyroscope uses the Coriolis force on a shaking mass. An ADC turns both into signed integers. The full-scale range sets how many counts make one g, the sensitivity. Bias is a slow offset that integration turns into a walk. Noise density times the square root of the bandwidth gives the fast noise. The output rate must be paired with an anti-alias filter, or fast vibration folds into false slow motion. The Allan deviation of a still recording shows noise, wander and drift as three regions of one curve.

The numbers that matter

All values are for the TDK InvenSense ICM-42688-P, datasheet DS-000347 revision 1.6, unless a row says otherwise.

WhatNumberWhy it matters
ADC word, sensitivity16 bits; accel 16,384 LSB/g at ±2 g, 2,048 at ±16 g; gyro 131 LSB per °/s at ±250, 16.4 at ±2000Divide raw by the value for the range you set
Accelerometer zero-g offset±20 mg initial; ±0.15 mg/°CBias that integration turns into metres
Gyroscope zero-rate output±0.5 °/s initial; ±0.005 °/s per °C30 degrees a minute if left uncorrected
Noise densityaccel 65 (X, Y) and 70 (Z) µg/√Hz; gyro 0.0028 °/s/√HzMultiply by the root of the bandwidth
RMS noise at 100 Hzaccel 0.65 mg; gyro 0.028 °/sCheck: density × 10
Gain errorsscale factor ±0.5 %; nonlinearity ±0.1 %; cross-axis ±1 % (accel)5 mg at 1 g, bigger than the noise
Output data rategyro 12.5 Hz to 32 kHz; accel 1.5625 Hz to 32 kHzNyquist is half the rate
Anti-alias filter42 Hz to 3,979 Hz, second order, switchable; low-noise mode onlyTrades noise against latency
Start-upgyro 30 ms to ready, on for at least 45 ms; accel 10 msWait before trusting the first sample
Identity, registersWHO_AM_I 0x75 = 0x47; PWR_MGMT0 0x4E; GYRO_CONFIG0 0x4F; ACCEL_CONFIG0 0x50The three writes that configure it
White noise on the Allan plotd/√(2τ): 46 µg at 1 s for 65 µg/√HzSlope −1/2; verified in the browser model

The checklist before you trust a reading

  1. Read WHO_AM_I and confirm 0x47 before anything else.
  2. Write the range, the rate and the power mode, then wait 200 µs and 45 ms.
  3. Keep the sensitivity and the range register in one place in the code.
  4. Pick the smallest range that never clips in your worst real motion.
  5. Enable the anti-alias filter and set the rate at least twice the highest frequency you need.
  6. Compute expected noise from density times the root of bandwidth and compare it with a still log.
  7. Estimate bias while still, and plan to repeat it when the temperature moves.
  8. Never integrate a raw gyroscope or accelerometer for long without fusion or a reset.

The core, as code

c/* From datasheet numbers to the error you should expect on a still log */
float expected_rms(float density, float bandwidth_hz) {
    return density * sqrtf(bandwidth_hz);        /* 65 ug/rtHz * sqrt(100) = 650 ug */
}
float allan_white(float density, float tau_s) {
    return density / sqrtf(2.0f * tau_s);         /* 46 ug at 1 s */
}
float alias_hz(float f, float fs) {
    return fabsf(f - roundf(f / fs) * fs);         /* 130 Hz at 100 Hz -> 30 Hz */
}
float drift_m(float bias_mg, float t_s) {
    return 0.5f * (bias_mg * 1e-3f * 9.80665f) * t_s * t_s;  /* 8 mg, 60 s -> 141 m */
}

Where this sits

This lesson is the first of five in the IMU track of Firmware from Zero to Expertise. It builds on Read a Datasheet and Reference Manual. The next lessons cover the FIFO and its timestamps (lesson 2), the always-on sensor hub (lesson 3), calibrating on the chip (lesson 4) and orientation filters on a small processor (lesson 5). The same error model carries over to other MEMS parts such as pressure sensors and microphones, with different numbers.

Keep going

Sources

The takeaway. A datasheet is a list of promises about error. Range sets the counts per g, bias sets the walk, noise density times the root of the bandwidth sets the hiss, and the rate needs a filter in front of it. Know the number for each before you write a filter.
You log a still gyroscope at 100 Hz for an hour and the Allan curve rises after 100 s. What do you change in firmware?

Now press Present or Teach and explain from memory why a still IMU walks away, with the equation and the datasheet numbers. Then go back to the virtual IMU at the top and predict its Allan curve before you move a slider.

Firmware from Zero to Expertise, IMU 1: What an IMU Really Measures
ICM-42688-P (TDK InvenSense) · Kalibr IMU noise model · Allan variance (MathWorks) · Back to Gleams