A cheap motion sensor is wrong in four ways, and its compass can point nearly 50 degrees off. Turn it through every direction, fit the errors away, and save the answer where a power cut cannot lose it.
Learn how firmware on a small chip measures a sensor's own errors, removes them, and keeps the fix safe in flash.
Pick Hard iron removed, then Calibrated, and watch the squashed, shifted cloud of compass readings become a round ball around zero. Drag the two sliders to make the sensor worse. Then we build, piece by piece, the gyro bias, the accelerometer, the temperature fit, the ellipsoid, and the flash record.
You need a little C and the idea of a vector (three numbers: x, y and z). We build the rest from zero.
Part of the Engineermaxxing series Firmware from Zero to Expertise, IMU track. Built from the TDK ICM-42688-P datasheet (DS-000347 Rev 1.6), the Nordic nRF52840 Product Specification, the Zephyr NVS documentation, NOAA's World Magnetic Model page, and NXP application note AN4246. The Field Guide lists every source. The sensor in the hero is a model, not a real chip.
A model, not a chip. The blue sphere is a 45 µT Earth field, a value inside the 20 to 60 µT range NOAA gives for the main field. The hard-iron offset and soft-iron stretch are made up for the demo. Heading error is computed for a level sensor turning through a full circle, at an assumed 60 degree dip angle. Drag the picture to turn it.
Chapter 0
See how a tiny constant error in a gyroscope grows into a large angle, and why the chip must learn its own mistakes
A small drone sits on your desk. Nobody touches it. Its firmware reads the gyroscope 200 times a second, and the gyroscope says the drone is turning at 0.3 degrees per second. That is slower than the minute hand of a clock moves, so you would never see it.
But the firmware believes the number. After one minute it thinks the drone has turned 18 degrees. The drone has not moved at all. Now the pilot flips the switch to take off, and the flight controller tries to correct an angle that is not real.
An IMU (inertial measurement unit) is a small chip that measures motion. It usually holds two or three sensors. A gyroscope measures how fast the chip turns, in degrees per second (dps). An accelerometer measures the push on the chip, in units of g (one g is the pull of Earth's gravity, so a chip lying still reads 1 g straight down). A magnetometer measures the magnetic field, in microtesla (µT), and works as a compass.
The sensor does not hand your firmware degrees or g. It hands over integers. The TDK ICM-42688-P, a 6-axis IMU, reports each gyroscope axis as a 16-bit number. At its ±2000 dps range one step is 1/16.4 dps, so the datasheet lists a sensitivity of 16.4 LSB per dps. An LSB is the least significant bit: the smallest step the number can take. Your driver divides by that sensitivity to get dps.
To get an angle, firmware does one simple thing. Every sample, it multiplies the rate by the time step and adds the result to a running total. This is called integration. It is the same as watching a speedometer and adding up the distance.
Now give the rate a small constant error. Each step adds the same wrong amount. After 200 steps you are wrong by 200 times as much as after one step. A constant error in the rate becomes an error in the angle that grows in a straight line with time:
0.30 dps × 60 s = 18 degrees (the drone on the desk)
The ICM-42688-P datasheet gives the initial ZRO tolerance as ±0.5 dps, measured on a board at 25 °C (DS-000347 Rev 1.6, section 3.1). That is a good chip. A part straight from the reel can carry the full 0.5 dps, and 0.5 × 60 = 30 degrees after one minute. Try it below.
The warm line is the angle error of a sensor that does not move. Drag the bias, then switch on the correction and see what a measured bias leaves behind.
Model. The measured bias is assumed to be right to 0.02 dps (a made-up value; Chapter 2 shows how the real figure follows from sensor noise). The red dashed line marks 10 degrees.
A bias is only one error. A real IMU has four, and calibration means measuring each of them and cancelling it.
On top of these, the first three change when the chip gets warm. Chapter 3 deals with that. The magnetometer has its own two extra errors, caused by the board it sits on, in Chapters 5 and 6.
You might ask: why not fix all this once, in a lab, and be done? Three reasons. First, every board is different. The magnet in a speaker, the steel of a screw and the battery current all bend the magnetic field around the sensor, and they differ for each product. Second, the bias moves with temperature and over the years, so the lab number slowly goes stale. Third, the product is the only place that has the final board, the final case and the final battery.
So firmware does two jobs. In the factory, a fixture measures each unit once and writes the results into flash (the chip's non-volatile memory). In the field, the firmware keeps correcting the fast-moving part, such as the gyro bias, whenever the device holds still. Both jobs end the same way: a small set of numbers, the calibration coefficients, that the sensor driver applies to every sample.
This lesson walks through each error, from the one that costs the least to the one that needs the most care, and then asks how to keep the answer safe.
It builds on Non-Volatile Storage for the flash and MEMS Reality for bias, noise density and full-scale range.
Chapter 1
Write the sensor's mistakes as one small formula, read its size off the datasheet, and see which mistake matters at which speed
You open the datasheet of your new IMU and look for a number that says how good it is. There is no such number. There are twenty. Offset, scale, cross-axis, noise, temperature drift, each one with its own row, its own unit and its own test condition. Which of them will hurt your product?
The way out is to put them all into one formula. Then each row of the datasheet fills in one part of the formula, and you can see how they combine.
Take three numbers: the true rate of turn about x, y and z. Call them a vector x. The sensor does three things to it. It mixes and stretches the axes a little (scale and cross-axis). It adds a fixed amount (offset). And it adds random noise. The numbers your firmware reads are:
Calibration turns the formula around. If you know M and b, the firmware can recover the truth:
That is the whole job of the sensor driver's calibration step: three subtractions and nine multiplications per sample. The rest of this lesson is about finding M and b, for each sensor, on the chip.
The ICM-42688-P datasheet (DS-000347 Rev 1.6, section 3.1) gives these gyroscope numbers, for a board-level part at 25 °C:
These errors do not all grow the same way. The offset is the same at any speed. The scale and cross-axis errors are percentages, so they grow with the rate. Spin the sensor at 100 dps about z. The scale error can add 0.005 × 100 = 0.5 dps to the z reading. The cross-axis leak can add 0.0125 × 100 = 1.25 dps to the x and y readings, even though nothing turns about those axes.
Bars show the worst case from the datasheet at the turning rate you pick. Slide the rate from a slow pan to a fast spin and watch the bars cross.
Datasheet limits, not typical values: ZRO ±0.5 dps, scale ±0.5%, cross-axis ±1.25%, and noise as the 0.028 dps-rms figure at 100 Hz bandwidth (ICM-42688-P, DS-000347 Rev 1.6, section 3.1). The worst case rarely meets on one part; the bars show the ceiling.
The offset (0.5 dps) is the biggest error below 40 dps, because 1.25% of 40 dps is 0.5 dps. The cross-axis leak takes over above that. The scale error only matches the offset at 100 dps and then stays smaller than the leak. Noise is the smallest of all, and it averages away. So a slow-moving device, such as a handheld pointer, needs the offset first. A fast-spinning device, such as a drone flip, needs the cross-axis table too.
The accelerometer has the same formula, with its own sizes. The datasheet gives a zero-g level initial tolerance of ±20 mg at board level, and a change of ±0.15 mg per °C from −40 to +85 °C. A mg is one thousandth of a g.
Why does 20 mg matter? A level device should read 1 g on the z axis and 0 on x and y. If x reads 20 mg of nothing, firmware that estimates tilt from gravity sees an angle of arcsin(0.020) = 1.15 degrees. The device lies flat, and the tilt estimate says it leans by more than one degree. A self-levelling camera or a robot standing on a slope notices.
You have two places to put b. Some chips, including the ICM-42688-P, let you write a user offset into registers (OFFSET_USER0 to OFFSET_USER8 in bank 4), and the chip subtracts it before the data reaches the FIFO. Or your firmware subtracts it in software, after reading. Register offsets are fixed-point with a limited step, which Chapter 2 shows can cost you precision. Software gives full float precision but costs a few operations per sample. M almost always lives in software, because no register holds a 3 by 3 table.
On real hardware. Put an STM32 Nucleo or an nRF52840 DK on the desk with an IMU breakout board (any 6-axis part). Lay it flat and still, log ten seconds of raw gyro at 200 Hz, and compute the mean of each axis. Compare each mean with the datasheet's ZRO limit. Then tilt the board 90 degrees on its side and see how the accelerometer mean of each axis moves by 1 g.
Chapter 2
Measure the offset by averaging a still gyroscope, reject the moments when it was not still, and store the result without losing precision
The pilot plugs in the battery. For the next two seconds nothing happens: the pilot is carrying the drone to the launch spot and then puts it down. The gyroscope reports numbers the whole time. For about half a second at the end, the drone sits perfectly still.
That half second is a gift. If the drone does not turn, the true rate is zero. So whatever the gyroscope reports in that moment is not motion. It is the bias. The firmware only needs to catch the moment and average the numbers.
Each sample is the bias plus a random wobble. The wobble has a typical size, its standard deviation, written σ. Add up N samples and the wobbles partly cancel: some are positive and some are negative. The wobble of the average shrinks:
Take σ = 0.028 dps per sample and two seconds of data at 200 Hz, so N = 400. The square root of 400 is 20, and the average is good to 0.028 / 20 = 0.0014 dps. After a minute, that leftover error adds 0.0014 × 60 = 0.084 degrees. Compare that with the 18 degrees we started with. (This treats the samples as independent. Real gyroscopes also have slow drift, which Chapter 3 meets and which the Allan variance plot of the MEMS Reality lesson shows.)
The trouble is that the firmware cannot see "still". It only sees numbers. So it uses a test. A stillness detector looks at a short window of recent samples, say the last 50 at 200 Hz, a quarter of a second. If the samples spread out more than noise could explain, the device is moving, and the window is thrown away. A common rule is to demand that the standard deviation stays under a few times the noise, plus a second check that the accelerometer magnitude is close to 1 g.
The running average is easy to keep without storing the samples. Welford's method updates a mean and a spread with one pass: for each new sample x, the count n goes up by one, the mean moves by (x − mean) / n, and the spread measure moves by (x − old mean) × (x − new mean). It needs three variables per axis and no buffer, so it fits in a few bytes of RAM.
The warm trace is one gyro axis, 200 samples a second. Press Start to average. Press Bump to knock the device once. Try it with the stillness check on, and then off.
Model. True bias 0.30 dps and noise of 0.028 dps per sample (the datasheet's rms figure, treated as white noise). A bump is a 0.5 s swing of about 30 dps. The check rejects a sample when the last 40 samples spread by more than 0.2 dps (a made-up threshold, about seven times the noise; 40 quiet samples span roughly four to five times it).
Watch the purple line. It starts wild and settles onto the blue line as N grows. When you bump the device with the check off, a few hundred wrong samples pull the average far from the truth, and it takes thousands of good ones to wash that out. With the check on, the bump is skipped and the estimate does not move.
Here is the failure written the way you meet it in the field. Symptom: the heading drifts by one or two degrees after some start-ups and not others. Measurement: log the bias estimate at the end of each boot. Most boots give 0.30 dps. A few give 0.9 dps, and those are the ones where the drone was still in someone's hand. Fix: accept an estimate only after the stillness check has held for a full window, refuse any estimate larger than a sane limit (for example, twice the datasheet ZRO, 1.0 dps), and keep the last good value from flash when the check never passes.
c/* Welford running mean of one gyro axis, gated by a stillness check. Called once per sample; returns true when the estimate is ready. */ typedef struct { uint32_t n; float mean, m2; } welford_t; static void welford_add(welford_t *w, float x) { w->n++; float d = x - w->mean; w->mean += d / (float)w->n; w->m2 += d * (x - w->mean); /* variance = m2 / (n-1) */ } bool gyro_bias_step(const float g[3], float accel_mag_g) { static welford_t win[3]; /* the long average */ static float lo[3], hi[3]; static uint16_t k; /* min/max of the last window */ for (int a = 0; a < 3; a++) { if (k == 0 || g[a] < lo[a]) lo[a] = g[a]; if (k == 0 || g[a] > hi[a]) hi[a] = g[a]; } if (++k < 40) return false; /* 40 samples = 0.2 s at 200 Hz */ k = 0; bool still = (accel_mag_g > 0.98f && accel_mag_g < 1.02f); for (int a = 0; a < 3; a++) still &= (hi[a] - lo[a]) < 0.2f; if (!still) { for (int a = 0; a < 3; a++) win[a] = (welford_t){0}; return false; } /* the 40 samples were quiet: fold their centre into the average */ for (int a = 0; a < 3; a++) welford_add(&win[a], 0.5f * (lo[a] + hi[a])); return win[0].n >= 10; /* 10 quiet windows = 2 s */ }
The sketch is intentionally simple. It averages the middle of each quiet window instead of every sample, which keeps the arithmetic small; a production version would add every sample once the window passes. The shape is what matters: gate, accumulate, and give up cleanly when the gate never opens.
The ICM-42688-P can subtract the offset itself. You write it into the GYRO_X_OFFUSER, GYRO_Y_OFFUSER and GYRO_Z_OFFUSER fields (registers OFFSET_USER0 to OFFSET_USER4). Each is a 12-bit signed value with a maximum of ±64 dps and a resolution of 1/32 dps. That is a step of 0.03125 dps.
Our bias is 0.30 dps. In steps of 1/32 that is 9.6, so the register takes 10, which is 0.3125 dps. The leftover is 0.0125 dps. In the worst case, the true value lies halfway between two steps, so the leftover is half a step: 1/64 = 0.0156 dps. Over one minute that is 0.0156 × 60 = 0.94 degrees. Compare that with the 0.084 degrees our averaging earned. The coarse register throws away more than ten times the precision we worked for.
The fix costs nothing: put the whole-step part in the register if you want the chip to handle large offsets, and keep the fractional remainder in a float that the driver subtracts. Or leave the register at zero and subtract everything in software.
On real hardware. On an STM32 Nucleo or nRF52840 DK with an ICM-42688-P breakout, boot the board ten times flat on the table. Log the bias estimate (all three axes) after each boot. The spread between boots shows the true repeatability. Then lift the board by hand during one boot and watch the stillness check reject that boot.
Chapter 3
Fit a short polynomial to bias against temperature so that the correction follows the chip as it warms up
The drone starts the day in a cold garage at 10 °C. At boot, the firmware measures the bias and stores it. Twenty minutes later the electronics inside the case have warmed to 55 °C, and the heading starts to slide again. Nothing moved. The bias moved.
A MEMS gyroscope is a tiny vibrating structure on silicon. Heat changes the stiffness of the silicon, the shape of the parts and the electronics beside them. So the zero-rate output changes with temperature. The datasheet quantifies it.
For the ICM-42688-P, ZRO variation versus temperature is ±0.005 dps per °C, over 0 to +70 °C (DS-000347 Rev 1.6, section 3.1; the table marks it as derived from characterization, not tested on every part). Move the chip from 25 °C to 65 °C, a rise of 40 °C, and the bias can move by 40 × 0.005 = 0.2 dps. Left alone, that adds 0.2 × 60 = 12 degrees per minute of error on a device that sits still.
The accelerometer drifts too: ±0.15 mg per °C from −40 to +85 °C. Over the same 40 °C step that is 6 mg, or arcsin(0.006) = 0.34 degrees of apparent tilt.
Where does the firmware get the temperature? From the sensor itself. The chip has an on-die temperature sensor, and its reading converts as T = TEMP_DATA / 132.48 + 25 in °C (for the register value; the FIFO copy uses 2.07 LSB per °C). The datasheet lists a room-temperature offset of ±5 °C, so the absolute number may be off. That does not matter here. We fit the bias against that same reading. Any constant error in the reading shifts the curve sideways and the fit absorbs it.
Plot bias against temperature. The points make a smooth, gentle curve. We want a formula that gives the bias at any temperature, cheap enough to run at every sample. A polynomial does it. Let ΔT be the chip temperature minus a reference of 25 °C:
To find c0, c1 and c2, collect pairs of (temperature, measured bias) and pick the three numbers that make the curve pass as close as possible to all the pairs. This is least squares: minimise the sum of the squared gaps. Written out, it becomes a small set of three equations in three unknowns, which a few lines of Gaussian elimination solve. The factory can do it offline. Firmware can also do it on the chip, which Chapter 6 shows in a bigger version.
You collect the pairs in one of two ways. In the factory, an oven steps through temperatures (for example 0, 25, 50 and 70 °C), waits for each to settle, and measures the bias with the unit still. In the field, every time the stillness detector from Chapter 2 passes, the firmware logs the chip temperature and the new bias. A device that warms from 10 to 55 °C in use draws its own curve.
Try it below. The blue curve is the true bias of a made-up sensor. The warm dots are measurements with a little noise. Pick how many terms the polynomial gets, and where you measured.
Choose where the 15 measurements were taken, then the degree of the curve. Degree 0 is a flat line, 1 a slope, 2 a slope and a bend. Check the error across the whole 0 to 70 °C range.
Model. The true curve is 0.30 + 0.004 ΔT + 0.00002 ΔT2 dps (slope inside the datasheet's ±0.005 dps per °C), the 15 points carry 0.015 dps of noise each, and the same random draw is used on every visit. The error is measured against the true curve at every whole degree from 0 to 70 °C. The fit runs live in your browser.
Three lessons come out of that picture. First, degree 0, a single number, is what you get by measuring once at boot. It leaves a large error across the range. Second, a slope alone (degree 1) removes most of the error, and the bend (degree 2) trims what is left. Third, the data range is the real limit. Measured only between 20 and 30 °C, a bend term has nothing to hold it down, and the curve swings far off once you leave that band. Degree 5 shows the worst of this: it threads every dot and then explodes outside them.
So the rule is: use the lowest degree that fits, and never trust the curve outside the range of the data. Most gyroscopes need degree 1 or 2.
At each sample the driver reads the temperature, computes ΔT, evaluates the polynomial with Horner's rule (c0 + ΔT × (c1 + ΔT × c2)), and subtracts the result. That is two multiplies and two adds for each axis. Clamp ΔT to the range you measured, so that a freak reading cannot send the polynomial into the wild region.
ctypedef struct { float c0[3], c1[3], c2[3]; /* per axis: dps, dps/degC, dps/degC^2 */ float t_lo, t_hi; /* the range the data covered, degC */ } gyro_tc_t; static inline float gyro_bias_at(const gyro_tc_t *k, int axis, float t_c) { float t = t_c < k->t_lo ? k->t_lo : (t_c > k->t_hi ? k->t_hi : t_c); float dt = t - 25.0f; return k->c0[axis] + dt * (k->c1[axis] + dt * k->c2[axis]); /* Horner */ } /* per sample: omega[a] = raw[a] * dps_per_lsb - gyro_bias_at(&cal, a, die_temp_c); */
On a core without a floating-point unit, many designers use fixed-point numbers instead. The idea is to store the coefficient as an integer and remember where the binary point sits. A slope of 0.004 dps per °C stored in Q15 (a signed 16-bit integer meaning value / 32768) is 131, which decodes to 0.003998. The error from the rounding is far below the noise. The Q-format lesson in the audio track, Real-Time DSP on Cortex-M, works through the overflow rules.
The failure: a heading that drifts only in the first ten minutes after a cold start. Measure it by logging chip temperature and the still-bias together for twenty minutes: a straight line with a slope near 0.004 dps per °C shows the cause. Fix it with the slope term, and keep updating the curve in the field, because a part ages and the slope shifts.
On real hardware. Start a Nucleo or nRF52840 DK board with an IMU breakout cold, on a desk. Every 30 seconds, hold the board still for one second and log die temperature and the gyro mean. Do it for twenty minutes while the board warms from its own current. Plot the pairs. The slope you see is your part's c1. Compare it with ±0.005 dps per °C.
Chapter 4
Turn the device onto each of its six faces and use the one force you know exactly, gravity, to find offset and scale on every axis
In Chapter 2, stillness was the free ruler for the gyroscope: the true rate is zero, so the reading is the bias. An accelerometer has a similar free gift, and it is bigger. Gravity pulls on the chip all the time, with a force we know very well: one g.
Put the device flat on a table. The z axis points up. The accelerometer sits still, yet it reads +1 g on z, because the table pushes up on it to stop it falling. The x and y axes read zero. Turn the device onto its side and the +1 g moves to another axis. We know the right answer in every position. So we can find where the sensor is wrong.
Look at one axis, say x. Its reading follows our formula from Chapter 1, simplified for one axis: reading = s × true + b. Here s is the scale (close to 1) and b is the offset in g. Now place the device with x pointing straight up: the true value is +1. Then flip it so x points straight down: the true value is −1.
Work one example with the numbers a real part could give. Put x up and the sensor reads 1.023 g. Put x down and it reads −0.987 g. Then:
b = (1.023 + (−0.987)) / 2 = 0.018 g s = (1.023 − (−0.987)) / 2 = 1.005
The offset is 18 mg, inside the ±20 mg zero-g limit that the ICM-42688-P datasheet gives at board level. The scale is 0.5% high, the same size as the datasheet's ±0.5% scale tolerance. Now correct a reading with (reading − b) / s. For the first one: (1.023 − 0.018) / 1.005 = 1.000. For the second: (−0.987 − 0.018) / 1.005 = −1.000. Both come out exactly right, as they must.
Do this for all three axes and you need six placements, one for each face of the device. This is called six-position calibration.
A fair worry: a person holds the device against a book. It will not be exactly level. Suppose the x axis is tilted 1 degree away from straight up. Gravity now has a component of sin(1°) = 0.0175 g, which is 17.5 mg, on a neighbouring axis. That is as large as the offset we want to find! If we used the neighbouring axis's reading to estimate its offset, the tilt would wreck it.
That is why the method uses only the pair of faces for each axis. On the axis pointing up, the tilt costs only a factor of cos(1°) = 0.99985, a loss of 0.015%. Even at 3 degrees the loss is 0.14%. The tilt enters through a cosine, which is nearly flat near zero. The same factor hits both faces equally, so the offset (the sum) is untouched, and only the scale (the difference) gets a tiny error.
Press each face button to place the virtual device on that face and capture a reading, or press Capture all six. The dots below show the length of the gravity vector in 26 held orientations: before in warm, after in purple. The ideal is 1.000 g.
Model. The virtual sensor has offsets of +18, −12 and +15 mg and scales of 1.005, 0.995 and 1.004 (values inside the datasheet's ±20 mg and ±0.5% limits, chosen for the demo), plus 2 mg of noise per reading. The placement error tilts each face away from vertical by the angle you set, in a random direction. The 26 orientations are every direction that points along an axis, a face diagonal or a corner of a cube.
Capture the six faces with the slider at 2 degrees and the dots in the lower strip collapse onto the 1.000 line. Push the tilt to 5 degrees and they spread a little, but they stay far tighter than the raw dots. The method is forgiving, which is why it works on a factory floor with a cheap jig.
This simple version finds offset and scale only. It does not find cross-axis leak (the off-diagonal numbers of M), because those need the neighbouring-axis readings, and the tilt wrecks them. To get the full 3 by 3 table, you solve all twelve unknowns (nine in M, three in b) together by least squares from the same six placements, or more, and you need a jig with an accurate right angle. ST's application note AN4508, Parameters and calibration of a low-g 3-axis accelerometer, describes this with a misalignment matrix. Many consumer products stop at offset and scale, because the cross-axis error of a good part is a fraction of a percent.
The failure: a robot standing on flat ground reports that it leans 1.1 degrees. Measure by holding the device still and printing the length of the gravity vector from raw readings. A good part gives 1.000 g in every orientation. A 1.019 g in one orientation and 0.988 g in another is the offset and scale at work. Fix it with the six-position table, and keep a runtime check: when the device is still, the length of the corrected vector should be within a few mg of 1 g.
c/* r[face][axis]: the mean reading (g) on each face, faces ordered +X,-X,+Y,-Y,+Z,-Z up */ void accel_six_pos(const float r[6][3], float b[3], float s[3]) { for (int a = 0; a < 3; a++) { float rp = r[2*a][a], rm = r[2*a + 1][a]; /* axis a up, then axis a down */ b[a] = 0.5f * (rp + rm); s[a] = 0.5f * (rp - rm); } } /* per sample: g_cal[a] = (raw[a] - b[a]) / s[a]; (store 1/s[a] to avoid the divide) */
On real hardware. Tape an IMU breakout, wired to an STM32 Nucleo or an nRF52840 DK, to a small box with square sides. Rest the box on each of its six faces for two seconds, and log the mean of each axis. Run the code above. Then roll the box onto an edge and check that the length of the corrected vector is within a few mg of 1 g.
Chapter 5
See why turning a magnetometer in a circle draws a shifted, squashed shape, and why that shape turns into a large heading error
You solder a magnetometer onto your board, next to the speaker and the battery. You lay the board flat and turn it slowly through one full circle, as a hiker turns with a compass. A good compass would show north moving all the way round. Yours says north is stuck near the north-east for a quarter of the turn, then jumps.
The magnetometer is fine. The board around it is the problem. To see why, start with what a good reading looks like.
The Earth's magnetic field is a vector with a fixed strength where you stand. NOAA gives the strength of the main field as typically 20,000 to 60,000 nanotesla, which is 20 to 60 µT. Our toy uses 45 µT. Now turn the sensor in any direction. The field does not change. The sensor's own axes change. So the three numbers it reports change, but the length of that vector stays at 45 µT.
Plot the readings from many orientations as dots in 3D. Every dot is 45 µT from the origin. The dots lie on a sphere centred on zero. That is the picture of a clean magnetometer, and it is the blue sphere in the hero at the top of the page.
Hard iron is anything on the board that makes its own steady magnetic field: a speaker magnet, a magnetised steel screw, a current through a wire that stays the same. It is fixed to the board, so it turns with the sensor. The sensor always sees the same extra vector, whatever the orientation. Call it V. Every dot shifts by V, and the whole sphere moves off-centre without changing shape.
The heading, in a level device, comes from the two horizontal numbers: heading = atan2(−y, x) in this lesson's axis convention. Turn the device through a full circle and the horizontal readings should trace a circle around zero. With a hard-iron shift they trace a circle around some other point. Seen from zero, the direction to a point on that circle is wrong, and the amount it is wrong depends on where you are on the circle.
You can compute the worst case. The horizontal part of the Earth field is the radius of the circle, say Bh = 22.5 µT (45 µT with a 60 degree dip angle, a toy value). The horizontal shift is h. The largest angle you can be fooled by is where the line from zero just touches the circle:
h = 10 µT gives arcsin(10 / 22.5) = 26.4 degrees h = 5 µT gives 12.8 degrees
A shift of only 10 µT, smaller than the Earth field itself, makes a compass wrong by 26 degrees. Notice that the Earth's horizontal field is small, so a modest magnet matters a lot.
Soft iron is magnetically soft metal: steel brackets, a nickel-plated shield, an iron case. It makes no field of its own. Instead it bends the Earth's field as it passes through, a bit like a lens bending light. How much it bends depends on the direction of the field relative to the metal. The field is stretched along some directions and squeezed along others.
That is a linear change, so a 3 by 3 table W describes it, the same kind of table as M in Chapter 1. The sphere becomes an ellipsoid: a ball squashed or stretched along three perpendicular directions. With both effects together:
NXP's application note AN4246 (Ozyagcilar) develops this same model with a soft-iron matrix and shows how a compass is calibrated in the presence of both effects. To undo the damage, run the equation backwards. First subtract V, then multiply by the inverse of W:
B = W−1 ( m − V )
The order is the same as for the gyroscope and accelerometer: subtract the offset first, then undo the stretch. Chapter 6 finds V and W from data. First, feel what they do to a compass.
Left: the horizontal readings as the board turns once. Right: the heading error at each true heading. Drag the sliders, then switch the two corrections on one at a time.
Model, level board only. The horizontal Earth field is 22.5 µT (a toy 45 µT field at a 60 degree dip). The shift points along a fixed direction, and the soft-iron stretch is along an axis 30 degrees from x, with the same amount of squeeze on the perpendicular axis. The corrections use the exact values, which is what Chapter 6 tries to reach by fitting.
Set soft iron to zero and look at the error curve with hard iron alone. It is one smooth wave per turn: the error swings positive, then negative, once. Now bring in soft iron with hard iron off. The error makes two waves per turn, because a stretch looks the same from opposite sides. Real boards show both at once, so the curve is a mix of the two. That is a useful diagnostic: count the waves.
Symptom: the compass heading is fine on the bench and wrong in the product case, and two units from the same batch disagree. Measurement: turn each unit slowly through a full circle and log the horizontal readings. A clean unit makes a circle at the origin. Yours makes a shifted or squashed one. Fix: calibrate every unit in its final case with the battery, speaker and cables as they will be used, because V and W belong to the assembly and not to the chip.
On real hardware. Lay an STM32 Nucleo or nRF52840 DK with a magnetometer breakout (a part such as the one inside a 9-axis IMU) flat on a table, away from steel. Turn it slowly through one circle and log x and y. Plot them. Now place a screwdriver or a small speaker next to the board and repeat. Watch the circle move.
Chapter 6
Collect compass readings while the device turns, solve for the centre with a few sums and a tiny equation system, and refuse to trust directions you never visited
The product is a hand-held tool. The first time you switch it on, the screen says: "Wave the device in a figure eight." You wave. A few seconds later the screen says: "Compass ready." In those few seconds the chip took about a thousand compass readings, found V and the stretch, and kept them. How does it do that in a few hundred bytes of RAM?
We want the centre V and radius r of a sphere that passes near the readings m. A point m is on a sphere of centre V and radius r when its distance from V is r: |m − V|2 = r2. This is a curved problem, and V is buried inside a square. Expand the square and move things around:
Look at what happened. The equation is now a straight (linear) one in four unknowns: Vx, Vy, Vz and k. Each reading gives one such equation. With hundreds of readings we have far more equations than unknowns, so we pick the four numbers that fit them all best, by least squares, just as in Chapter 3.
Try it on three points of a flat circle, so the arithmetic fits on a line. The points are (7, 1), (−3, 1) and (2, 6). Their squared lengths are 50, 10 and 40. Each point gives 2mxVx + 2myVy + k = |m|2:
The centre is (2, 1) and the radius is 5. The three points do lie on that circle. In 3D, you need at least four points that do not lie on a common plane, and you want hundreds.
With a thousand readings you do not have to store them. For each reading, form a row a = [2mx, 2my, 2mz, 1] and the number y = |m|2. The least-squares solution needs only two things: the sums of every pairwise product of a's entries (a 4 by 4 table, symmetric, so 10 numbers) and the sums of a times y (4 numbers). So 14 floating-point accumulators, 56 bytes, and no buffer. At the end, solve one 4 by 4 system by Gaussian elimination. The work per reading is a few dozen multiplies, easy at the rate a human can wave a device.
Now the catch. The fit can only place the sphere using the readings it has. If every reading lies on a flat circle (the device was only spun flat on a table), then infinitely many spheres pass through that circle, with centres sliding up and down the circle's axis. The x and y of the centre come out right. The z does not. Try it:
Each button adds 60 readings from one kind of motion. The three panels look at the cloud from three sides. The blue ring is the true field sphere, the purple dashed ring is your fit. Start with the flat spin.
Model. The made-up board has a hard-iron vector of (14, −9, 11) µT and a soft-iron table with 10%, −5% and +3% stretch on the axes plus a small cross term. Readings carry 0.5 µT of noise. The fit is the 4-unknown linear sphere fit described above, with a tiny ridge term so a flat cloud returns an answer. The stretch uses the half-range of each centred axis. Field 45 µT, dip 60 degrees.
After Spin flat on a table, the first two numbers of the centre are close and the third is far off. The side views show why: the cloud is a thin flat ring, seen edge-on from two sides. Then press Tumble in every direction. All three numbers snap into place and the dashed ring sits on the blue one. Wave the device through directions, not just angles.
The chip cannot see the true sphere, so it needs a test it can run on its own data. A simple one: track the minimum and maximum of each axis. A device that has been waved well has a similar span on all three axes, close to twice the field strength. If the smallest span is under about half the largest, say "keep waving" and do not save. A second test: after the fit, check that the radius falls in a believable range (the Earth field is 20 to 60 µT), and that the readings sit close to the sphere (their distances from V vary by a few percent at most). These two limits are made up for this lesson; tune them on your own hardware.
Soft iron needs more than a centre. The full job fits an ellipsoid, a quadratic surface with 9 or 10 unknowns, and then undoes it with W−1. That requires either a larger solve or an eigenvalue step on a 3 by 3 table, heavier but still possible on a Cortex-M4F. A lighter choice, shown by the toggle above, fits only the stretch along each axis: scale each centred reading by (r / half-range of that axis). It fixes the main squash and misses any rotation of the ellipsoid. The remaining error shows up in the read-out.
c/* Sphere fit by linear least squares: 14 accumulators, no sample buffer. */ typedef struct { float aa[4][4], ay[4]; uint16_t n; float lo[3], hi[3]; } sphere_fit_t; void fit_add(sphere_fit_t *f, const float m[3]) { float a[4] = { 2*m[0], 2*m[1], 2*m[2], 1.0f }; float y = m[0]*m[0] + m[1]*m[1] + m[2]*m[2]; for (int i = 0; i < 4; i++) { f->ay[i] += a[i]*y; for (int j = 0; j < 4; j++) f->aa[i][j] += a[i]*a[j]; } for (int k = 0; k < 3; k++) { if (f->n == 0 || m[k] < f->lo[k]) f->lo[k] = m[k]; if (f->n == 0 || m[k] > f->hi[k]) f->hi[k] = m[k]; } f->n++; } bool fit_solve(const sphere_fit_t *f, float V[3], float *r) { float s_min = 1e9f, s_max = 0; /* coverage guard */ for (int k = 0; k < 3; k++) { float s = f->hi[k] - f->lo[k]; s_min = fminf(s_min, s); s_max = fmaxf(s_max, s); } if (f->n < 200 || s_min < 0.5f * s_max) return false; /* keep waving */ float A[4][5]; /* copy aa | ay, then Gaussian elimination with pivoting (omitted) */ /* ... x[0..2] = V, x[3] = k ... */ /* *r = sqrtf(x[3] + V[0]*V[0] + V[1]*V[1] + V[2]*V[2]); accept only if 20 <= *r <= 60 uT */ return true; }
The failure: the compass is perfect while the device is flat, and wrong as soon as the user tilts it. Measure by checking the saved centre: its z value looks odd, and the span of the z readings during the wave was tiny. Fix it with the coverage guard, and tell the user to tumble the device, not only spin it.
On real hardware. On an STM32 Nucleo or nRF52840 DK with a 9-axis IMU board, stream raw magnetometer values over the serial port, wave the board in a figure eight for ten seconds, and log them. Fit the sphere on your laptop and compare V with what the chip computes. Repeat after a flat-only spin and see the z centre go wrong.
Chapter 7
Store 96 bytes of calibration so that pulling the battery at any moment leaves either the old numbers or the new ones, never garbage
The calibration is done. The compass works. The firmware writes the 21 numbers into flash, and in the same instant the user pulls the battery out to swap it. At the next power-up the compass spins like a top, then reports "not a number". The bias, the offsets and the field centre are all gone. The unit looks broken, and nothing is wrong with the sensor.
This chapter is about that one moment. It builds on Non-Volatile Storage: Flash Pages, Wear Levelling, LittleFS and the Write That Lost Power, which explains the flash physics in more depth. Here we apply it to a calibration record.
Flash is the non-volatile memory that keeps its contents with the power off. It has a strict rule. The Nordic nRF52840 Product Specification states it plainly: the memory controller "is only able to write 0 to bits in flash memory that are erased (set to 1)". So a bit goes from 1 to 0 by a write, and back to 1 only by an erase, which clears a whole page at once.
The same chapter of the specification gives the costs. Erasing one page takes 85 ms (tERASEPAGE, with the crystal clock running). Writing one 32-bit word takes 41 µs (tWRITE). A word may be written twice between erases (nWRITE = 2). Each page survives 10,000 erase cycles (nENDURANCE). Other chips differ, so read your own datasheet, but the shape is always the same: erasing is slow and wears the page, writing is fast.
First, decide what one saved record looks like. Our 21 calibration floats (gyro bias and temperature terms, accelerometer offset and scale, magnetometer centre and stretch) need 21 words. We add a header and a check:
0xCA11B007 that says "this is a calibration record".That is 24 words, 96 bytes. Writing them takes 24 × 41 µs = 0.98 ms. Erasing takes 85 ms. So if you erase a page and then write the record, 98.9% of the time (85 of 86 ms) is spent erasing. A power cut at a random moment almost always lands in the erase. That is the dangerous part.
The order of writing matters too. Write the payload words first and the CRC last. A record without its CRC is incomplete, and the check fails. The CRC word is the commit: until it lands, the record does not count. The Zephyr NVS documentation uses the same idea: "A write of data to nvs always starts with writing the data, followed by a write of the metadata", and data written without metadata is ignored when the store starts.
A single slot has a deadly flaw. You must erase it before you write the new record, so from the first millisecond of the erase the old calibration is gone. If power fails now, you have neither. The cure is two slots, A and B, in two different pages. You always write the new record into the slot that does not hold the newest valid one. The old one stays untouched while the new one is built.
At boot the firmware reads both slots, checks each one (magic number correct, CRC correct), and uses the valid one with the higher sequence number. If the power failed during the write, the half-built slot fails its check, and the other slot wins.
The save erases a page (85 ms) and then writes 24 words (0.98 ms). Pick a scheme, drag the cut time, and read what the next boot loads. Slot A holds record 7 and slot B holds record 6 before the save.
Model. Timings are the nRF52840 values: 85 ms page erase, 41 µs per 32-bit word. The CRC is a real CRC-32 (reflected, polynomial 0xEDB88320) computed live over the record bytes, and the coefficients are decoded as 32-bit floats. An interrupted erase is modelled as a page cleared from the start; real parts can leave bits half-erased, which is one more reason to trust only a record that passes its CRC.
Try the one-slot scheme first. Almost any cut time between 0 and 85 ms hits the erase, and the next boot reads blank words (all 1s, which decode as "not a number"), or a mix of new numbers and blank ones. Nothing raises an error, because nothing checks. Now switch to two slots. Drag across the whole range. The boot always finds a record that passes its check, and the only question is whether it is the old one or the new one.
A good CRC proves the bytes are the bytes that were written. It does not prove they are sensible. A bug, or a unit calibrated while someone carried it, can store a gyro bias of 40 dps with a perfect CRC. So after the CRC, check each coefficient against a limit from the datasheet: an offset beyond a few times the ZRO limit (±0.5 dps, so say 2 dps), a scale far from 1, a field radius outside 20 to 60 µT. A record that fails goes in the bin, and the firmware falls back to the next best: the other slot, then the factory record, then the datasheet defaults with an "uncalibrated" flag so the application knows.
Many products keep two layers. The factory record is written once on the production line into its own page, with the temperature fit and the six-position results. The field record holds what the device learns in use (a new gyro bias, a magnetometer centre) in the rotating A/B pair. At boot, load the factory record first, then overwrite with the field record if it is valid.
Wear sets how often you may save. Two slots with 10,000 erases each give 20,000 saves in all. Save once per minute and they are gone in 20,000 / 1,440 = 13.9 days. Save once per boot at ten boots a day and they last about 5.5 years. So save only when the value changed enough to matter, for example a bias that moved by more than 0.02 dps. A log-structured store, such as Zephyr's NVS, spreads writes over many sectors and keeps one sector free to copy into, and its documentation gives the lifetime formula (sectors × sector size × page erases, divided by writes per minute times the record size plus 8 bytes of metadata).
c#define CAL_MAGIC 0xCA11B007u typedef struct { uint32_t magic, seq; float v[21]; uint32_t crc; } cal_rec_t; /* 96 bytes */ static bool rec_ok(const cal_rec_t *r) { return r->magic == CAL_MAGIC && r->crc == crc32((const uint8_t *)r, sizeof(*r) - 4) && sane(r->v); } bool cal_load(cal_rec_t *out) { const cal_rec_t *a = (const cal_rec_t *)SLOT_A, *b = (const cal_rec_t *)SLOT_B; bool ga = rec_ok(a), gb = rec_ok(b); if (!ga && !gb) return false; /* fall back to factory / defaults */ *out = (ga && (!gb || a->seq > b->seq)) ? *a : *b; return true; } void cal_save(const float v[21]) { cal_rec_t cur; bool have = cal_load(&cur); const void *dst = (have && (const void *)slot_of(&cur) == SLOT_A) ? SLOT_B : SLOT_A; /* the OTHER slot */ cal_rec_t n = { .magic = CAL_MAGIC, .seq = have ? cur.seq + 1 : 1 }; memcpy(n.v, v, sizeof n.v); n.crc = crc32((const uint8_t *)&n, sizeof(n) - 4); flash_erase_page(dst); /* 85 ms: old record in the other slot is safe */ flash_write_words(dst, &n, 23); /* header + payload first ... */ flash_write_words((uint8_t *)dst + 92, &n.crc, 1); /* ... the CRC last: the commit */ }
One more guard: do not save while the supply is falling. Check the battery or supply voltage first, and refuse to start an 85 ms erase when it is low. Then the cut that matters becomes far less likely.
The failure: one unit in a few hundred "loses its calibration" after a battery swap. Measure it by cutting power at random times, a hundred times, with a relay on the supply, and counting boots that load the wrong record. Fix it with the two slots, the commit-last order and the sanity limits above.
On real hardware. On an nRF52840 DK, toggle a GPIO pin high at the start of cal_save and low at the end. Watch it on a logic analyzer: the high time should be close to 86 ms. Then switch the board's supply with a relay at random delays after that edge, repeat 100 times, and print which sequence number loads each time. Every boot must print either 7 or 8, never a failure.
Chapter 8
Keep the numbers, the terms, the checklist and the core code in one place, and find where to go next
A motion sensor reports y = M x + b + n. Calibration finds M and b and applies x = M−1(y − b) on the chip. The gyroscope bias comes from stillness and moves with temperature. The accelerometer gets its offset and scale from six faces and gravity. The magnetometer gets its centre and stretch from a figure-eight wave and a least-squares fit. Then a two-slot, CRC-checked record keeps it all safe from a power cut.
| Quantity | Value | Where it comes from |
|---|---|---|
| Gyro initial ZRO | ±0.5 dps, board level, 25 °C | ICM-42688-P datasheet DS-000347 Rev 1.6, section 3.1 |
| Gyro ZRO versus temperature | ±0.005 dps per °C, 0 to 70 °C | same table (derived from characterization) |
| Gyro scale and cross-axis | ±0.5% initial, ±1.25% cross-axis | same table |
| Gyro noise | 0.028 dps-rms at 100 Hz bandwidth; 0.0028 dps per √Hz at 10 Hz | same table |
| Accel zero-g and drift | ±20 mg initial; ±0.15 mg per °C from −40 to +85 °C | accelerometer table, same datasheet |
| On-die temperature | T = TEMP_DATA / 132.48 + 25 (°C); room offset ±5 °C | same datasheet |
| User offset registers | gyro ±64 dps in 1/32 dps steps; accel ±1 g in 0.5 mg steps (OFFSET_USER0 to 8) | same datasheet, section 5.4 (user programmable offset) |
| Earth field strength | typically 20 to 60 µT (20,000 to 60,000 nT) | NOAA World Magnetic Model page |
| Flash timing and wear | erase 85 ms per page, write 41 µs per word, 10,000 erases per page, 2 writes per word | nRF52840 Product Specification, NVMC |
| Record | 24 words = 96 bytes; write time 0.98 ms; erase is 98.9% of a save | this lesson, from the two rows above |
| Term | Plain meaning |
|---|---|
| Bias, offset, ZRO | What the sensor reads when the true value is zero. |
| Scale error | A fixed percentage by which every reading is too big or too small. |
| Cross-axis | A turn about one axis leaking into the readings of the others. |
| Hard iron | A steady magnetic field fixed to the board. It shifts the compass cloud. |
| Soft iron | Metal that bends the Earth field. It stretches the compass cloud into an ellipsoid. |
| Least squares | Pick the numbers that make the sum of squared gaps smallest. |
| Coverage | How many different directions the fit data came from. |
| CRC-32, commit, sequence number | A checksum, the last word that makes a record count, and the counter that says which record is newest. |
The ICM-42688-P datasheet describes a separate self-test. The chip actuates the sensing structure, and firmware compares the output with the self-test off and on. The datasheet defines the response as "sensor output with self-test enabled minus sensor output with self-test disabled", and the part passes when the response is within the specified limits. It checks that the mechanical and electrical parts work. It does not find your bias or your scale. Run it on the production line to catch broken parts, and run calibration to correct good ones.
c/* The whole runtime side of calibration: three corrections per sample. */ typedef struct { float g_c0[3], g_c1[3], g_c2[3]; /* gyro bias polynomial in (T - 25), dps */ float a_b[3], a_inv_s[3]; /* accel offset (g) and 1/scale */ float m_v[3], m_k[3]; /* mag centre (uT) and per-axis stretch */ } cal_t; /* 21 floats: the record payload */ void imu_correct(const cal_t *c, float t_c, float g[3], float a[3], float m[3]) { float dt = t_c - 25.0f; for (int i = 0; i < 3; i++) { g[i] -= c->g_c0[i] + dt * (c->g_c1[i] + dt * c->g_c2[i]); /* Chapters 2 and 3 */ a[i] = (a[i] - c->a_b[i]) * c->a_inv_s[i]; /* Chapter 4 */ m[i] = (m[i] - c->m_v[i]) * c->m_k[i]; /* Chapters 5 and 6 */ } }
Calibration is the layer between the raw sensor and the orientation filter. A clean, calibrated stream is what a complementary or Kalman filter expects. Keep going:
Now press Present or Teach and explain, from memory, how the chip finds the gyro bias, why a flat spin cannot place the compass sphere, and how the two-slot record survives a power cut. Then go back to the compass cloud at the top and straighten it again.