Three Filters, One Motion

Three ways to turn gyro and accelerometer readings into a tilt cost from 113 to 894 cycles a sample on a Cortex-M4F. Run all three on one motion, then squeeze them into fixed point.

An orientation filter is the small program on a sensor chip that answers one question, many times a second: which way is up? You will build the answer three ways and count what each one costs.

Press All three, then drag the gyro bias and the shake. Watch which filter drifts, which one is fooled, and what each costs in cycles. Then we build every piece from zero, down to the bits of a Q31 number.

You need a feel for what a sensor reading is and a little C. We build quaternions, filters and fixed-point numbers from zero.

Part of the Firmware from Zero to Expertise series, IMU track. Built from primary sources, not slides: the Madgwick and Mahony filter code and papers, the Arm Cortex-M4 manual, the RP2040 datasheet and CMSIS-DSP. Full list in the Field Guide.

Run the filters

0.020
0.50

A synthetic 20 s recording at 100 Hz with a known true tilt: still, roll, pitch, yaw, a shake that adds linear acceleration, a fast flick, still. Gyro bias is in rad/s, shake in g. Cycle counts are an arithmetic floor from the operation counts in Chapter 5 and the Cortex-M4 TRM, not a measurement. Filter settings are the defaults of Chapters 2 to 4.

Chapter 0

Ten Milliseconds, a Small Core and a Tilt

See why a filter that costs a few hundred cycles still decides how long a battery lasts

A fitness band sits on your wrist. Every 10 milliseconds its motion chip hands the small processor beside it six fresh numbers: three from a gyroscope (a sensor that reports how fast the band is turning) and three from an accelerometer (a sensor that reports which way gravity pulls). From those six numbers the processor must answer one question: which way is up? It answers again 10 ms later, and again, all day.

The program that answers is an orientation filter. It takes six numbers in and gives four out: a quaternion, a set of four numbers that says how the band is turned (Chapter 1 builds it from zero). The six inputs are three floats of rate in radians per second and three floats of acceleration in g. The four outputs are one unit quaternion. That is 24 bytes in and 16 bytes out, every sample.

This lesson builds three such filters and puts each on a real kind of chip. Two are cheap and clever: Mahony and Madgwick. One is the textbook heavyweight: an extended Kalman filter (EKF). For each one we ask three questions a firmware engineer must answer. How many cycles does it take? How many bytes does it keep? What range of numbers must it handle without breaking?

A cycle is the unit of time on the chip

A processor does its work in tiny steps set by a clock. One tick of that clock is one cycle. An STM32F411 board runs its core at up to 100 MHz (Zephyr's board page for the Nucleo F411RE says "100 MHz max CPU frequency", with 512 KB of flash and 128 KB of SRAM). That is 100 million cycles every second. A simple add or multiply takes about one cycle. So one sample period at 100 Hz holds 100,000,000 / 100 = 1,000,000 cycles. Think of it as a budget of one million coins per sample.

Now see what the filters spend. Press the buttons below and read the bars.

Spend the cycle budget

Each bar is the share of the core one filter uses, on a log scale from 0.01% to 100%. Pick a chip, then drag the sample rate up. The dashed line is the whole core.

100 Hz
×1.0

Cycle counts are an arithmetic floor from the operation counts in Chapter 5 (Cortex-M4 TRM: add and multiply 1 cycle, divide and square root 14). The RP2040 has no floating-point unit, so its bars use a toy soft-float cost of 30 cycles per add or multiply and 100 per divide or root: illustrative, not measured. The 8 MHz hub clock is illustrative. The real-code factor stands for loads, stores and stalls that the floor leaves out.

On real hardware. Board: STM32 Nucleo-F411RE. Turn on the Data Watchpoint and Trace cycle counter: set TRCENA (bit 24) in DEMCR at 0xE000EDFC, then CYCCNTENA (bit 0) in DWT_CTRL at 0xE0001000. Read CYCCNT at 0xE0001004 before and after one filter call, and print the difference. Repeat it a thousand times and keep the maximum, not the average. Compare it with the floor in the device. The RP2040 datasheet lists no DWT, so on a Pico use its 24-bit SysTick or its 64-bit microsecond timer.

On the F411 at 100 Hz the biggest filter, the EKF, spends 894 of its 1,000,000 cycles: about 0.09%. The core sleeps the rest of the time. So the time budget is not the problem on this chip. If cycles were only about meeting a deadline, this lesson could stop here.

Three reasons cycles still matter

First, some chips have no floating-point unit (FPU), the block of silicon that does decimal-point arithmetic in hardware. The RP2040 has two Cortex-M0+ cores with a single-cycle 32-bit multiplier and no FPU. Its boot ROM holds a "fast floating point library" in software (RP2040 datasheet, section 2.8.3.2). Every float add becomes a function call. Switch the device to the RP2040 and drag the rate up: the same C code now eats a visible share of the core.

Second, energy. A chip that does 894 cycles of work and then sleeps spends energy in proportion to the cycles it ran. The sensor hub chip of the next-door lesson (fw-imu-03) runs slowly on purpose, so the share of the core is large even though the work is small. Pick the 8 MHz hub in the device and push the rate to 1,600 Hz.

Third, numbers. A filter must keep its values inside what the number format can hold. On a float that range is huge. In fixed point, where every number is a whole count of tiny steps, the range is small and fixed. Chapters 7 and 8 show that the three filters need very different ranges, and that the EKF is the one that breaks first.

One more cost sits behind these three: the sample period itself. If the filter thinks 10 ms passed and the truth is 11 ms, the tilt is wrong by more than any cycle count can fix. Chapter 6 measures that.

The road

  1. Two imperfect sensors: why the gyro drifts, why the accelerometer lies, and what a quaternion is.
  2. Mahony: a feedback controller with a proportional and an integral term.
  3. Madgwick: one gradient step per sample, and the single number that tunes it.
  4. The EKF: a covariance that tracks how sure the filter is.
  5. Cycles and bytes: how to count them, how to measure them with the DWT.
  6. The clock: what a wrong dt does to the tilt.
  7. Fixed point: Qm.n numbers, multiplies that widen, saturation and wraparound.
  8. Overflow: run each filter in a fixed word and find its integer bits.
  9. Field guide: the numbers, a checklist, the core code and the sources.

This lesson leans on four others. fw-imu-01 explains where the sensor noise and bias come from, and fw-imu-04 explains how a chip removes bias before the filter sees it. The Kalman filter lesson and complementary filters and AHRS derive the maths we only use. fw-aud-04 introduced fixed-point DSP; we meet it again in Chapter 7.

An EKF takes 894 cycles a sample on a 100 MHz Cortex-M4F at 100 Hz. Which statement is true?

Chapter 1

Two Imperfect Sensors, One Good Tilt

Meet the recording, the quaternion and the one idea behind all three filters

Lay a phone flat on a table and tip one edge up by a few degrees. The phone knows it tipped. It knows from two small sensors that disagree about almost everything, so the chip has to listen to each of them for what it does well.

The gyroscope reports how fast the phone turns, in radians per second. It is smooth and quick. To get an angle from it, the chip adds up the rate times the sample period, sample after sample. This is called integration: the angle is an odometer for turning. But every gyro has a small constant offset called bias. A bias of 0.02 rad/s looks tiny. Added up for 20 seconds, it is a large angle.

The accelerometer reports the pull on a small mass inside it, in units of g. At rest the table pushes the phone up, and the sensor reads exactly that push: one g, pointing up. So its direction gives the tilt, with no drift. But it is noisy, and it cannot tell gravity from a shove. Swing the phone sideways and the reading is gravity plus your shove. The tilt it reports is wrong for as long as you shake.

So one sensor is smooth but drifts, and the other is true on average but noisy and fooled by motion. Drag the sliders and see both failures on a recorded motion.

Play each sensor alone

Blue solid: add up the gyro only. Blue dashed: read the tilt from the accelerometer only. Teal: Mahony fuses both. Drag the bias and the shake, then compare where each line goes.

0.020
0.50

Synthetic recording at 100 Hz, seeded, with a known true tilt. Gyro noise 0.004 rad/s and accelerometer noise 0.02 g are illustrative values, not a specific part's datasheet (see fw-imu-01 for real noise densities). Error is the angle between the estimated and the true gravity direction.

On real hardware. Board: micro:bit v2 or an STM32 Nucleo with an IMU shield. Leave the board flat and still for 20 seconds and log the raw gyro. The mean of each axis is that axis's bias; the spread is its noise. Add up the rate times dt in a loop and see how far the angle walks. That walk is the gyro-only line above, measured on your own part.

With the default bias, the gyro alone is 13.0° off after 10 seconds and 22.3° off at the end. The accelerometer alone never drifts. But it is up to 4.4° off even when the phone is still, and 31.7° off in the shake. The fused Mahony line stays under 3°. Fusing is the whole job.

A quaternion is the cheap way to hold a rotation

Before the filters, one tool. A rotation in 3D can be stored as a turn by an angle θ about an axis n (a direction of length 1). A quaternion stores it as four numbers: q = (w, x, y, z) = (cos θ/2, sin θ/2 · n). Its length is always 1. Doing nothing is q = (1, 0, 0, 0). Think of it as a compass needle for 3D: four numbers, one rule, no trig on the way.

Why not three angles? Angles hide a trap called gimbal lock, where two axes line up and one angle becomes meaningless, and updating them needs sines and cosines every sample. A quaternion updates with plain multiplies and adds. That is why every filter in this lesson keeps one.

The gyro's rate turns into a quaternion update with one line of algebra:

q̇
How fast the four numbers of q change, per second.
½
The half comes from the half-angle in cos θ/2 and sin θ/2.
q ⊗ (0, ω)
Quaternion product of the current orientation with the measured rate ω (three numbers, in rad/s) written as a quaternion with a zero first part.

Worked example, one sample. The band turns at 90° per second about x, so ωx = 1.5708 rad/s, and dt = 0.01 s. Start at q = (1, 0, 0, 0). The update adds ½ · qw · ωx · dt = 0.5 · 1 · 1.5708 · 0.01 = 0.007854 to x. Now q = (1, 0.007854, 0, 0). Its length is 1.0000308, a hair over 1, so we divide each part by it: q = (0.99997, 0.007854, 0, 0). A rotation of 0.9° should have sin(0.45°) = 0.007854 in x. It does.

The accelerometer's job is to tell us where gravity points in the sensor's own frame. From a quaternion the filter predicts it: v = (2(xz − wy), 2(wx + yz), w² − x² − y² + z²). For our q this gives v = (0, 0.015708, 0.999877): tilted 0.9° from straight up. The filter compares that predicted v with the measured accelerometer direction. The gap between them is the error. Everything that follows is about what each filter does with that gap.

The shared shape of the three filters

All three do the same two steps each sample. Predict: integrate the gyro, as above. Correct: measure the gap between predicted and measured gravity, and nudge the quaternion to shrink it. The filters differ only in how big the nudge is. Mahony makes it proportional to the gap, plus a running total of the gap. Madgwick steps downhill on the gap. The EKF sizes it from how sure it is. The idea that the fast sensor predicts and the slow sensor corrects is the complementary filter, derived in sf-06; sf-13 adds what happens when you also integrate position.

One limit applies to all three. Gravity points down whichever way you face, so the accelerometer cannot see yaw, a turn about the vertical. Yaw drifts with the gyro bias and nothing in this lesson corrects it. A magnetometer fixes that. All our errors are tilt errors only.

The gyro alone is 22° off after 20 s even though it is smooth and quiet. What is the cause?

Chapter 2

Mahony: A Thermostat for Drift

Correct the gyro with a proportional and an integral term, and watch the bias get learned

A room is too cold. A thermostat measures the gap between the target and the real temperature and turns on the heater by an amount that grows with the gap. If the gap stays, because a window leaks, the thermostat also adds up the gap over time and turns the heater up more. The gap shrinks. A Mahony filter is exactly that thermostat, with the orientation as the room and gravity as the thermometer.

Robert Mahony and his coauthors published it as a "nonlinear complementary filter" on the group of rotations (IEEE Transactions on Automatic Control, 2008). The code most firmware uses is Sebastian Madgwick's C port of it, which is the version we read here. The filter works in four steps each sample.

  1. Normalise the accelerometer. Divide (ax, ay, az) by its length, so it becomes a pure direction. The code uses invSqrt here.
  2. Predict gravity. From the current quaternion, compute the direction gravity should have in the sensor frame (Chapter 1).
  3. Take the cross product. Measured direction crossed with predicted direction gives a vector e. It points along the axis you must turn about to close the gap, and its length is sin of the gap angle.
  4. Correct the gyro. Add a share of e to the measured rate, then integrate the corrected rate as in Chapter 1.

The share has two parts. The proportional term adds Kp · e: a bigger gap gives a bigger push. The integral term keeps a running total of e, scaled by Ki, and adds that too. The proportional term fights the gap right now. The integral term learns the slow, constant part of the gap, which is exactly what a gyro bias looks like.

c// Mahony IMU update, condensed from Madgwick's C port of the 2008 paper.
// State: q0..q3 (the quaternion), ix, iy, iz (the integral term). Tuning: twoKp = 2*Kp, twoKi = 2*Ki.
void mahony_update(float gx, float gy, float gz, float ax, float ay, float az, float dt)
{
    float r = invSqrt(ax*ax + ay*ay + az*az);        // 1. normalise the accelerometer
    ax *= r; ay *= r; az *= r;
    float vx = q1*q3 - q0*q2;                         // 2. half the predicted gravity direction
    float vy = q0*q1 + q2*q3;
    float vz = q0*q0 - 0.5f + q3*q3;
    float ex = ay*vz - az*vy;                        // 3. error = measured x predicted (half size)
    float ey = az*vx - ax*vz;
    float ez = ax*vy - ay*vx;
    ix += twoKi*ex*dt; iy += twoKi*ey*dt; iz += twoKi*ez*dt;   // the integral term learns the bias
    gx += ix + twoKp*ex;  gy += iy + twoKp*ey;  gz += iz + twoKp*ez; // 4. corrected rate
    gx *= 0.5f*dt; gy *= 0.5f*dt; gz *= 0.5f*dt;
    float qa = q0, qb = q1, qc = q2;                    // integrate: q += q (x) (0, g)
    q0 += (-qb*gx - qc*gy - q3*gz);  q1 += (qa*gx + qc*gz - q3*gy);
    q2 += (qa*gy - qb*gz + q3*gx);  q3 += (qa*gz + qb*gy - qc*gx);
    r = invSqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);     // keep |q| = 1
    q0 *= r; q1 *= r; q2 *= r; q3 *= r;
}

The code works with half the predicted vector (so vz has the - 0.5f), which is why the gains carry a factor of two. The source file defaults are twoKp = 2 · 0.5 and twoKi = 0. We use Kp = 0.5 and Ki = 0.1.

One step by hand

The sensor sits at q = (1, 0, 0, 0), but the accelerometer says it is rolled 10°: a = (0, 0.1736, 0.9848). The predicted half-gravity is v = (0, 0, 0.5). The error is ex = ay·vz − az·vy = 0.1736 · 0.5 − 0 = 0.0868; ey = ez = 0. With Kp = 0.5, twoKp = 1.0, so the gyro rate gets +0.0868 rad/s (5°/s) about x. Over dt = 0.01 s that turns the quaternion 0.05° toward the truth.

Generally the push is Kp · sin(gap) rad/s. The gap therefore shrinks like a cooling cup of tea, with time constant 1/Kp seconds: 2 s at Kp = 0.5. A big Kp trusts the accelerometer and follows it, noise and shakes included. A small Kp trusts the gyro and lets bias creep in.

Why the integral term is there

Now put a constant bias b on the gyro. The proportional term settles where Kp · sin(gap) = b. So a gap remains. Only the part of the bias that tilts the sensor counts, and here that is about 0.0224 rad/s. The gap is 0.0224 / 0.5 = 0.045 rad, or 2.6°, forever. This is the thermostat with a leaking window. Add Ki and the running total keeps growing until it cancels the bias exactly. Then the gap goes to zero. Drag Ki in the device and watch the lower trace: it climbs to the true bias size and the tilt error falls.

Tune the thermostat

Top: tilt error of Mahony. Bottom: the size of the integral term (teal) against the true gyro bias (blue dashed). Start with Ki at 0, then raise it.

0.50
0.10

Synthetic recording (gyro bias vector (0.020, −0.010, 0.006) rad/s, size 0.0232 rad/s; shake 0.5 g). The Mahony code is the one printed above, run in this page in double precision. Kp and Ki are the paper's gains; the C variables are twice these.

On real hardware. Board: nRF52840 DK with an IMU on I2C, or an STM32 Nucleo with the sensor on SPI. Run the printed update at your sensor's rate. Rest the board still for 20 seconds, print the integral term (ix, iy, iz), and check it settles near the mean you measured in Chapter 1. Then tap the board and see how far the tilt jumps for how long.

There is a tidy rule for the pair. Linearise for small gaps and the gap obeys θ″ + Kp θ′ + Ki θ = 0, the equation of a spring with damping. The ratio ζ = Kp / (2√Ki) says how it settles. At ζ = 1 (Kp² = 4Ki) the gap returns with no overshoot; for Kp = 0.5 that is Ki = 0.0625. Our Ki = 0.1 gives ζ = 0.79, a touch underdamped, and the learned bias overshoots slightly. Pick Kp first from how long a shake lasts, then Ki from this ratio.

Two traps remain. A large Ki can wind up: during the shake the error is wrong for a second, the integral term learns a false bias, and it takes seconds to unlearn. And a large Kp makes the filter follow the shake. The best setting depends on how often the accelerometer lies, not on any formula. Chapter 5 shows that this filter, at 56 multiplies and 33 adds, is the cheapest of the three.

With Ki = 0 and a constant gyro bias, what does a Mahony filter do?

Chapter 3

Madgwick: One Downhill Step per Sample

Replace the controller with a single gradient step and one number to tune

You are a hiker in thick fog. You cannot see the valley, but you can feel the slope under your boots. So you take a short step straight downhill, feel the slope again, and step again. You never plan a route. You just keep stepping down. After enough steps you reach the bottom.

That is the Madgwick filter. The valley is the orientation where the gravity direction predicted from the quaternion equals the gravity direction the accelerometer measures. The hillside height is how badly the two disagree. Sebastian Madgwick and his coauthors described it in a 2011 paper at the ICORR rehabilitation robotics conference. The abstract claims a low computational load and the ability to run at small sampling rates. It also claims accuracy that matches a commercial Kalman-based orientation sensor: below 0.8° static and 1.7° dynamic RMS error in the paper's test.

The slope, in three numbers

Define the gap as a list of three numbers: f(q) = (predicted gravity from q) − (measured gravity). When the filter is right, f is zero. The "height" is half the squared length of f. A gradient is the direction of steepest climb of that height with respect to the four numbers of q. It is a list of four numbers. We get it from the Jacobian J, a 3×4 table of how each part of f changes when each part of q changes: gradient = Jᵗ f.

Shapes: f is 3×1, J is 3×4, the gradient is 4×1. The firmware never builds J. Madgwick multiplied Jᵗ f out by hand, so the C code is four long lines, s0 to s3, each a sum of products of q and a.

c// Madgwick IMU update, condensed from the x-io open-source C (arduino-libraries/MadgwickAHRS).
// State: q0..q3. Tuning: beta. a is normalised first. s0..s3 = J-transpose times f, multiplied out.
qDot1 = 0.5f * (-q1*gx - q2*gy - q3*gz);          // the gyro prediction, as in Chapter 1
qDot2 = 0.5f * ( q0*gx + q2*gz - q3*gy);
qDot3 = 0.5f * ( q0*gy - q1*gz + q3*gx);
qDot4 = 0.5f * ( q0*gz + q1*gy - q2*gx);

s0 = _4q0*q2q2 + _2q2*ax + _4q0*q1q1 - _2q1*ay;           // the gradient, four numbers
s1 = _4q1*q3q3 - _2q3*ax + 4.0f*q0q0*q1 - _2q0*ay - _4q1 + _8q1*q1q1 + _8q1*q2q2 + _4q1*az;
s2 = 4.0f*q0q0*q2 + _2q0*ax + _4q2*q3q3 - _2q3*ay - _4q2 + _8q2*q1q1 + _8q2*q2q2 + _4q2*az;
s3 = 4.0f*q1q1*q3 - _2q1*ax + 4.0f*q2q2*q3 - _2q2*ay;
r  = invSqrt(s0*s0 + s1*s1 + s2*s2 + s3*s3);       // make the step exactly 1 long
s0 *= r; s1 *= r; s2 *= r; s3 *= r;

qDot1 -= beta * s0;  qDot2 -= beta * s1;                // step downhill by beta
qDot3 -= beta * s2;  qDot4 -= beta * s3;
q0 += qDot1 * dt;  q1 += qDot2 * dt;  q2 += qDot3 * dt;  q3 += qDot4 * dt;   // then normalise q as before

Read the middle of the listing. The gradient is scaled to length 1, and then multiplied by β (beta). So the correction always has the same size, β, whether the gap is 10° or 0.1°. A Mahony push shrinks as the gap closes. A Madgwick push does not. Beta is the only knob. The paper defines it as the size of the gyro's measurement error, as a rate of change of the quaternion, and gives β = √(3/4) · ω̃max for the largest axis error ω̃max in rad/s. The paper's best values were 0.041 for the IMU form and 0.033 with a magnetometer. The Arduino library defaults to 0.1.

One step by hand

Use the case from Chapter 2: q = (1, 0, 0, 0) and a = (0, 0.1736, 0.9848), a 10° roll. The predicted gravity is (0, 0, 1), so f = (0, 0 − 0.1736, 1 − 0.9848) = (0, −0.1736, 0.0152). At the identity only two entries of J are non-zero for this f, and the gradient comes out as (0, −0.3472, 0, 0). Its length is 0.3472, so the unit step is (0, −1, 0, 0). Then qDot2 -= beta * (-1) adds β to the x rate of change. With β = 0.1 that is qx += 0.1 · 0.01 = 0.001 per sample, a turn of 2 × 0.001 rad = 0.115° toward the truth. The step would be just as big if the gap were 1°. That is the price of the single knob.

The trick inside invSqrt

Three times a sample the code needs 1/√x, the length of a vector. A true square root plus a divide costs 14 + 14 = 28 cycles on a Cortex-M4F (Chapter 5 has the table). The code uses a famous shortcut instead. It reinterprets the float's bits as an integer, subtracts half of it from the constant 0x5f3759df, reinterprets it back, and then polishes the guess twice with Newton's method, y = y*(1.5f - halfx*y*y). That is 7 multiplies, 2 subtracts and a few integer moves, about 12 cycles. It is a good guess and two corrections, accurate enough for a unit-length step.

Find the right step size

Top: tilt error of Madgwick at your beta. Bottom: the root mean square error for every beta, with a marker where you are. Slide beta left and the filter cannot keep up with the bias. Slide it right and it chases noise and the shake.

0.100
0.020

Same synthetic recording (shake 0.5 g). The filter is the C above run in double precision. The sweep runs the whole recording at 24 values of beta from 0.005 to 2. The best beta is a property of this recording's noise and bias, not a constant of nature.

On real hardware. Board: STM32 Nucleo-F411RE, or any M4F board with an IMU. Log the raw gyro and accelerometer to a file at the sensor rate while you rotate the board by hand, and run the same Madgwick code on a PC at several beta values. Pick the beta with the lowest error against a known pose, such as the board flat on a table at the end. Then flash that value. Repeat after a 30 minute warm-up: bias moves with temperature, and so does the best beta.

The sweep is the lesson. With the default bias the best beta sits between 0.04 and 0.1, where the root mean square error is 0.86° and 0.76°. At 0.01 the filter cannot correct as fast as the bias grows and the error climbs to 4.0°. At 2 it follows the shake and noise and the error is 3.6°. Raise the bias to 0.1 rad/s and the useful beta must rise with it: at 0.041 the filter loses (21.2° RMS), and at 0.2 it holds (1.5°). With zero bias, the smallest beta wins. The rule: the maximum correction rate is 2β rad/s, so it must beat the largest bias you expect. The rule from the paper gives β = 0.017 for a 0.02 rad/s error. The sweep shows a few times that does better here, so treat the formula as a floor.

The gyro bias on a new board is five times larger than on the old one. What happens to a Madgwick filter that keeps the old beta?

Chapter 4

The EKF: A Filter That Knows How Sure It Is

Add a covariance, and see why the filter that listens best can also stop listening

Two friends give you directions. One is usually right, the other often wrong, and you know which is which. You do not average them. You weigh each by how much you trust it, and you update your trust as the walk goes on. A Kalman filter does exactly this, with numbers. It keeps a best guess and a second number that says how sure it is. The full story is in the Kalman filter lesson and sf-05; here we use it and count its cost.

Our guess is the quaternion q, four numbers. Our sureness is a 4×4 table P called the covariance. The diagonal of P says how unsure we are about each of the four numbers. The other entries say how the errors move together. The filter runs in two beats, like the others: predict with the gyro, then correct with the accelerometer. The correction is where the new idea sits.

F
The 4×4 gyro step. It is the identity plus ½ dt times the gyro numbers placed as in Chapter 1: row 0 is (1, −h·gx, −h·gy, −h·gz) with h = dt/2.
q⁻
The predicted quaternion, before the accelerometer is used.
P⁻
The covariance after prediction. Uncertainty grows when we only integrate.
Q
Process noise: how much we distrust the gyro step. We use a single number qn on the diagonal.
H
The 3×4 Jacobian: how the predicted gravity changes when each part of q changes. Its entries are twice a part of q.
R
Measurement noise: how much we distrust the accelerometer. A single number r on the diagonal.
S
The 3×3 innovation covariance: the total doubt about the gap between measured and predicted gravity.
K
The Kalman gain, 4×3. It turns the 3-number gap into a 4-number nudge. Big P and small R make it big.

The shapes tell you the cost. P and F are 4×4, H is 3×4, S is 3×3 and K is 4×3. Every line is a matrix product, plus one 3×3 inverse. A 4×4 times 4×4 product takes 64 multiplies. The filter does two of them to predict P and six more, of mixed sizes, to update it.

Why the gain is the whole idea

Take one number instead of a matrix. Say P = 0.1 (very unsure) and R = 0.004 (a good sensor). The gain is K = P / (P + R) = 0.96: trust the sensor almost completely. After a minute of agreement P falls to 0.0001 and K = 0.0001 / 0.0041 = 0.024. The filter now listens 2.4% to the sensor. This is not a bug. It is the point: the more sure we are, the less new data should move us. In our run the size of K goes from 0.857 at the first sample to 0.014 at 19 seconds, about 60 times less. That is also the trap. A filter that is sure of itself reacts slowly when the sensor suddenly tells the truth about a real change, and also when the sensor lies, as it does in a shake.

The tuning is Q against R. Q says "the gyro step may be wrong by this much". R says "the accelerometer may be wrong by this much". Their ratio sets the gain, not either alone. Try it.

Set the trust ratio

Top: tilt error of the EKF. Bottom: the size of the Kalman gain K on a log scale. Raise Q to trust the gyro less, raise R to trust the accelerometer less, and watch the gain and the shake error move.

1e-7
0.004

Same synthetic recording (bias 0.02 rad/s, shake 0.5 g). The EKF is the 4-state quaternion filter of this chapter, run in double precision here. A 0.02 g accelerometer noise would suggest r near 0.0004; the default r = 0.004 is inflated on purpose to forgive the shake. This filter has no bias state.

On real hardware. Board: nRF52840 DK (a Cortex-M4F, so arm_mat_mult_f32 runs on the FPU). Wrap the whole update in the DWT cycle counter from Chapter 0 and print the cycles, plus the largest and smallest entry on the diagonal of P every second. Float rounding can make P slightly non-symmetric after hours of running, so many implementations replace P by (P + Pᵗ)/2 each step. Check on your board that the diagonal stays positive.

Read the sweep honestly. With the defaults (qn = 1e-7, r = 0.004) the EKF has 1.45° RMS error and peaks at 4.6° in the shake. Make the gyro step less trusted, qn = 1e-5, and the shake drives it 16.0° off. Make it far more trusted, qn = 1e-9, and it can no longer follow the bias: it ends 8.0° off. Make the accelerometer trusted too little, r = 0.1, and the error ends 5.1° off. Between the extremes there is a wide, flat region that works. And because this EKF holds no bias estimate, it has no tool like Mahony's integral term. Adding three bias states makes P 7×7 and each product 343 multiplies instead of 64.

Now the failure itself. The symptom is a tilt that kicks and then recovers slowly after a shake. The measurement is the shake-window peak and the gain curve. The fix is to raise R while the accelerometer length is not near 1 g, so the gain drops exactly when the sensor lies. Real attitude code usually also uses a smaller 3-state error-state form that avoids the unobservable fourth direction. We keep the 4-state form because the matrices are easier to read.

An EKF has run still for a minute and its covariance P has shrunk. A sudden real tilt arrives. What does the small P do?

Chapter 5

Counting Cycles and Bytes

Turn operation counts into cycles, joules and bytes, and learn to measure the real figure

You have a filter in C and a question: will it fit? The answer has two parts, time and space. Time is cycles per sample. Space is bytes of RAM. Both can be counted before you flash anything, and then checked on the board.

Step 1: count the operations

Take the C code in Chapters 2 and 3 and count the operators. Each * is a multiply, each + or - is an add. We counted them with a short script over the real source files, leaving the body of invSqrt aside and counting each call once. Mahony with its integral term has 56 multiplies, 33 adds and 2 inverse square roots. Madgwick has 88 multiplies, 44 adds and 3 inverse square roots. The EKF has no single C file, so we count from the matrix sizes: a product of an n×k by a k×m table costs n·k·m multiplies and n·m·(k−1) adds. Summing every product in Chapter 4 gives 485 multiplies, 371 adds, 1 divide (the 3×3 inverse) and 2 inverse square roots.

Step 2: price each operation

The Arm Cortex-M4 manual gives the price list. In its FPU instruction table: VADD.F32, VSUB.F32 and VMUL.F32 take 1 cycle. A multiply-accumulate (VMLA.F32 or the fused VFMA.F32) takes 3. VDIV.F32 and VSQRT.F32 take 14 each. A float load or store (VLDR.32, VSTR.32) takes 2. The notes add two traps. An arithmetic instruction takes one extra cycle if the next instruction uses its result. And a divide or square root takes only one cycle if no further floating-point instruction runs behind it. The integer side of the instruction summary is: MUL, MLA, SMULL, SMLAL and SMLAD take 1 cycle, SSAT and QADD take 1, and SDIV takes 2 to 12.

Now price one invSqrt. The exact way, 1.0f / sqrtf(x), costs a VSQRT and a VDIV: 14 + 14 = 28 cycles. The fast way from Chapter 3 costs 7 multiplies and 2 subtracts plus a few integer moves: about 12. We charge each operation once, and add:

cycles
An arithmetic floor for one filter update on a Cortex-M4F with the fast invSqrt.
Nmul
Number of float multiplies in the update. Each costs 1 cycle.
Nadd
Number of float adds and subtracts. Each costs 1 cycle.
Ndiv
Number of float divides. Each costs 14 cycles.
Nisq
Number of inverse square roots. We charge the fast version 12 cycles; the exact one costs 28.

Worked example, Mahony: 56 + 33 + 2 · 12 = 113 cycles. Madgwick: 88 + 44 + 3 · 12 = 168. EKF: 485 + 371 + 14 + 2 · 12 = 894. These are the three numbers in the page's first sentence. Choose the core below to see how they move.

Price the filters

Top: cycles per sample, stacked by kind of operation. Bottom: bytes of RAM, persistent state plus the worst-case stack of temporaries. Switch the core, turn the fast invSqrt off, and switch the word size.

Operation counts: from the C source in Chapters 2 and 3 and the matrix sizes of Chapter 4. Prices for the M4F: Cortex-M4 TRM, FPU table 7-1 (r0p0) and instruction table 3-1 (r0p1). The M4 Q31 row charges 2 cycles per multiply (SMULL plus a shift), 12 for a divide and 16 for an integer inverse root: an illustrative model, not a measurement. The M0+ row charges 30 cycles per add or multiply and 100 per divide or root: a toy figure, because the RP2040 datasheet gives no soft-float timings. All rows leave out loads, stores and stalls.

On real hardware. Board: STM32 Nucleo-F411RE. Put the filter call between two reads of DWT->CYCCNT (the counter from Chapter 0), run it a thousand times on recorded data, and keep the maximum. Compare it with the floor above, then check three things if it is much higher: the build must use -mfpu=fpv4-sp-d16 -mfloat-abi=hard, every literal must carry the f suffix, and the optimiser must be on. Read RAM use from the map file (see fw-core-06 for stack measurement).

Step 3: count the bytes

Mahony keeps the quaternion (4 floats) and the integral term (3 floats): 7 × 4 = 28 bytes. Madgwick keeps the quaternion: 16 bytes. The EKF keeps the quaternion and the 4×4 covariance: 20 floats, 80 bytes. All three also create temporaries. Counting every local variable in the C as if it lived on the stack gives 10 floats (40 bytes) for Mahony and 22 floats (88 bytes) for Madgwick. The EKF's matrix helpers need F, three more 4×4 scratch tables, H and its transpose, and the 3×3 and 4×3 tables: 158 floats, or 632 bytes. Add them up: 68, 104 and 712 bytes. The STM32F411 has 128 KB of SRAM, so even the EKF is 0.5% of it. RAM is not the limit for these filters. Halving every word to 16 bits (Q15) halves the bytes, and Chapter 8 shows why you may not be able to.

What the floor leaves out, and what to do

The floor charges only arithmetic. A real compiled function also loads the six inputs, stores the four outputs, spills when more than the FPU's 32 single registers are live, and pays the one-cycle penalty whenever one result feeds the next instruction. Madgwick's update has 22 live temporaries plus the state, so spills are likely. The way to know is to measure. The symptom is a measured count that is two or three times the floor. The measurement is the DWT counter. The fix, in order, has three parts. Turn on the hardware float ABI. End every literal with f: the FPU is single precision only, and the TRM table lists arithmetic only for .F32, so a stray 0.5 becomes a double and a library call. Then reuse temporaries.

One more cost hides outside the update. Madgwick's source converts the quaternion to angles with atan2f and asinf. Those are library functions you pay for only when you ask for angles. Keep the quaternion inside the firmware and convert only when something needs to display or send an angle.

A Madgwick update measures 520 cycles on your Cortex-M4F, but the arithmetic floor says 168. What do you check first?

Chapter 6

The Clock Under the Filter: dt

Find out how a wrong or jittery sample period leaks straight into the tilt

Run an old film reel at 10% too fast. Every walk looks hurried, and the longer the scene, the more the clock and the picture disagree. An orientation filter has the same weakness. Its prediction step multiplies every gyro reading by a time step, dt. If dt is wrong, every turn is scaled by the same wrong factor.

See it with numbers. A band turns 90° in 1 second at a steady 1.571 rad/s. The sensor makes 100 samples in that second. The filter should add 1.571 × 0.010 = 0.01571 rad each time, and 100 of them make 1.571 rad, or 90°. Now the code believes dt is 0.011 s, 10% too long. Each sample adds 1.571 × 0.011 = 0.01728 rad. A hundred of them make 1.728 rad, or 99.0°. The filter is 9° off after one turn, and the gyro was perfect.

The accelerometer then drags the estimate back, but only at the filter's correction speed. A fast, long motion outruns the correction. So a wrong dt hurts most exactly when the motion is large.

Where a wrong dt comes from

There are three common sources. The first is a rate mismatch: the code assumes 100 Hz but the sensor's output data rate (ODR) is a little off, because its own clock is a small, cheap oscillator. The second is jitter: the code reads the sensor from a timer tick or a thread, and the read happens at 10.0 ms, then 10.7, then 9.4 ms after the last one, while the sensor sampled every 10.0 ms exactly. The third is batching: a sensor with a FIFO (a hardware queue of samples) delivers 32 samples at once. Reading time says nothing about when each was taken. fw-imu-02 covers the FIFO and its timestamps.

The fix for all three is the same: do not assume dt, measure it, using a clock close to the sensor. Two good clocks exist. A hardware timer in input-capture mode can stamp the edge of the sensor's data-ready line, so the stamp is made by silicon, not by software that may be late. Or the sensor itself can count and report its own time, as many FIFOs allow. Then dt is the difference between two stamps.

c// dt from a free-running cycle counter (Cortex-M4: DWT CYCCNT), clamped before use.
static uint32_t t_prev;
float next_dt(void)
{
    uint32_t t = DWT->CYCCNT;                        // stamp in the data-ready interrupt, not in a thread
    float dt = (float)(t - t_prev) * (1.0f / SYSCLK_HZ);  // unsigned subtract survives wraparound
    t_prev = t;
    if (dt < 0.5f * DT_NOMINAL || dt > 2.0f * DT_NOMINAL)   // a missed sample or a glitch:
        dt = DT_NOMINAL;                                // do not let it blow up the integration
    return dt;
}
// Mahony (Adafruit port) takes dt as an argument: updateIMU(gx,gy,gz, ax,ay,az, dt).
// Madgwick's library fixes it once with begin(sampleFrequency), so you must call begin() with the true rate.

Both published C ports differ here, and the difference matters. The Adafruit Mahony code has an updateIMU overload that takes dt on every call. The Arduino Madgwick library stores invSampleFreq once, from begin(sampleFrequency) (the file defaults to 512 Hz). If your real rate is 104 Hz and you left the default, you have an almost 5-fold dt error from the first line.

Break the clock

The sensor really samples every 10 ms. Tell the filters a wrong dt (rate mismatch) or a random one (jitter) and watch each tilt error. The error is largest in the flick, where the rotation is biggest.

+10%
±0%

Synthetic recording, sampled uniformly at 100 Hz. The filters are told dt = 10 ms × (1 + dt error) × (1 + jitter × a random number between −1 and 1), a new draw each sample, seeded. The jitter here is in the dt the filter believes; the data itself is not shifted.

On real hardware. Board: STM32 Nucleo-F411RE with the IMU's data-ready pin wired to an EXTI line. Toggle a spare GPIO in the interrupt and put a logic analyser on both the data-ready pin and that GPIO. Log DWT->CYCCNT deltas for 10,000 samples and print the minimum, mean and maximum. If the maximum is more than a few percent off the mean, move the read into the interrupt. If the mean is off the nominal, use the measured mean as dt.

Read the numbers. With a perfect clock, tilt RMS error is 1.16° for Mahony, 0.76° for Madgwick and 1.45° for the EKF. Now tell them dt is 10% too long. Mahony climbs to 4.17°, Madgwick to 2.18°, and the EKF to 3.44°. A dt 10% too short does nearly the same: 3.99°, 1.53° and 2.90°. At 20% too long all three reach 6.1° to 7.6°. Pure random jitter of ±50% on a correct average hurts less: 2.22°, 1.30° and 2.19°, because the errors cancel on average and only add noise. A bias in dt is worse than random noise in dt. That is the failure: symptom, a tilt that overshoots in big moves and settles slowly. Measurement, the logic analyser and the cycle-counter deltas. Fix, hardware stamps and a clamp.

Two more details close the loop. First, clamp dt. A missed interrupt gives a dt of 20 ms, and one bad sample then integrates a whole extra step of rotation. The clamp in the code above replaces any value outside half to double the nominal with the nominal. Second, remember the size of the number you are about to multiply. The rotation added per sample is the rate times dt over two: for a steady 1.571 rad/s that is 1.571 × 0.01 / 2 = 0.0079. In a 16-bit fixed-point word the step of the grid is 0.000031, so that single increment is only about 260 grid steps. Slower turns give far fewer. Chapter 7 shows what that does.

Your filter assumes dt = 10.0 ms, but the sensor's clock makes the true period 10.8 ms. What is the most likely symptom?

Chapter 7

Fixed Point: Numbers With a Built-In Range

Learn what a Qm.n number can hold, how a multiply widens, and what overflow does

A shop prices a sandwich at $12.34. Its till stores the whole number 1234, and everyone agrees the last two digits are cents. The till never stores a decimal point. The point lives in the agreement. That is fixed-point arithmetic: whole numbers, with a point you fixed in your head.

A chip does the same in binary. A Qm.n number is a whole number stored in a word, plus the agreement that the last n bits are a fraction. The first m bits, counting the sign bit, are the whole part. The stored integer I stands for the value I / 2n. So a 16-bit word in Q1.15 (often just "Q15") has 1 sign bit and 15 fraction bits. The integer 16384 stands for 16384 / 32768 = 0.5. The integer 5689 stands for 0.17361, which is our 10° roll value 0.1736 rounded to the nearest grid step.

One detail of the word itself. Computers store negative whole numbers in two's complement. In 16 bits, the top bit is the sign and the range is −32768 to 32767. Add 1 to 32767 and the word does not stop. It wraps around to −32768, like a car odometer rolling over, and the sign flips. Keep that picture; it is the whole danger of this chapter.

Range against step size

A word has a fixed number of bits, so m and n trade off. More whole-part bits give a larger range. More fraction bits give a finer step. Q1.15 holds −1 up to 0.99997 in steps of 2−15 = 0.0000305. Q1.31 in 32 bits holds the same range in steps of 4.7 × 10−10. Q2.30 holds −2 up to just under 2. Q8.24 holds −128 up to just under 128, in steps of 6 × 10−8.

Notice what Q1.15 cannot hold: the number 1.0. The largest value is 32767 / 32768 = 0.99997. A quaternion of identity, q = (1, 0, 0, 0), does not fit in Q1.15 or Q1.31. This is the first surprise in a fixed-point filter.

Multiplying widens, adding can overflow

Adding two numbers in the same format is just adding the integers. If the sum leaves the range, you get overflow. Multiplying is different. Two Q1.15 numbers have 15 + 15 = 30 fraction bits in the product, so the raw result is in Q2.30 and needs 32 bits. To return to Q1.15 you shift right by 15. Check with 0.5 × 0.25: 16384 × 8192 = 134,217,728; divided by 230 that is 0.125; shifted right by 15 it is 4096, which is 0.125 in Q15. On a Cortex-M4 the widening multiply SMULL takes 1 cycle and gives a 64-bit result for 32-bit inputs; the shift is one more.

Now the trap. Multiply −1 by −1 in Q15: (−32768) × (−32768) = 230. After the shift the answer is 32768, one more than the largest word. It overflows. If you wrap, the result becomes −32768: the answer is −1 instead of +1, with the wrong sign. If you saturate, it clamps to 32767: the answer is 0.99997, almost right. The Arm CMSIS-DSP library chose saturation: its arm_mult_q15 "uses saturating arithmetic. Results outside of the allowable Q15 range [0x8000 0x7FFF] are saturated." The M4 has one-cycle instructions for it: QADD for a saturating add and SSAT to clamp to a chosen width.

ctypedef int16_t q15_t;                                  /* Q1.15: value = x / 32768 */
static inline q15_t q15_mul(q15_t a, q15_t b)
{
    int32_t p = (int32_t)a * b;                          /* 15+15 fraction bits: Q2.30 */
    p = (p + (1 << 14)) >> 15;                      /* round, then back to Q1.15 */
    return (q15_t)__SSAT(p, 16);                       /* saturate: (-1)*(-1) gives 32767, not -32768 */
}
static inline int32_t q31_add(int32_t a, int32_t b) { return __QADD(a, b); }  /* one QADD, saturating */

Play with the format. Pick a format and mode, then push a and b past the range.

Store and multiply in Qm.n

Each row is the word that holds a number: the sign bit, the whole-part bits and the fraction bits. Choose a format, drag a and b, and switch between wrap and saturate when a number does not fit.

-1.00
-1.00

The quantiser is the one the later chapters use: round to the nearest step, then saturate or wrap as a two's-complement word of 16 or 32 bits. Stored products are formed from the stored (already rounded) a and b. Cell colours: sign bit, whole-part bits, fraction bits. A red outline marks a number that did not fit.

On real hardware. Board: STM32 Nucleo-F411RE. Write q15_mul as above and compare it with CMSIS-DSP's arm_mult_q15 on a few thousand random pairs, including −32768 × −32768. Read the disassembly to confirm that __SSAT and __QADD became one instruction each. Time a loop of a thousand multiplies with the DWT counter from Chapter 0. The M4 also has SMLAD, which does two 16-bit multiply-accumulates in one cycle, so Q15 vector code can beat float per byte as well as per word.

Set the device to Q1.15 and wrap, and drag a to 1.5. The word stores −0.5 because 1.5 minus 2 is −0.5: the whole number line is a ring of length 2. Switch to saturate and it stores 0.99997. Neither is correct. The only fix is a format with another whole-part bit. That is the design rule for the rest of the lesson: find the largest value each variable can ever hold, take its base-2 logarithm, round up, add the sign bit. That is m. Give everything else to n. fw-aud-04 used the same rule for audio filters, and tinyml-05 uses it for neural network weights.

In Q1.15 with wraparound, what does (−1) × (−1) produce?

Chapter 8

Overflow: When the Filter Meets Its Limits

Run all three filters in a fixed word and find the integer bits each one needs

A drone does a flip. The gyro reports 2,000 degrees per second, the top of a common full-scale setting. In radians that is 34.9 rad/s. Your fixed-point filter stores the rate in Q2.30, a word that holds numbers up to just under 2. The rate does not fit. With saturation it is clamped to 2. With wraparound it flips sign. Either way the quaternion integrates a rotation that never happened, and the horizon on the screen lurches.

This is the hardest part of fixed point, and no formula replaces measuring. The method has three steps. First, run the filter in floating point on a recording that includes your worst motion. Second, record the largest absolute value of every variable. Third, give each variable the integer bits it needs: the base-2 logarithm of the maximum, rounded up, plus the sign bit. This is called range finding. The device below does it for you, and shows what happens when you choose fewer bits.

Mahony: only the gyro range matters

The Mahony update (Chapter 2) multiplies things that are all at most about 1: the normalised accelerometer, the quaternion, the error vector. The one large number is the gyro rate itself, plus the small corrections added to it. On the 180°/s recording the largest rate is 3.17 rad/s. That needs 3 integer bits: range −4 to 4. In Q2.30 (range ±2), the rate saturates 353 times in the flick and the tilt error peaks at 23.2°; with wraparound it overflows 179 times and the peak is 133.4°. At Q3.29 nothing overflows, and the result matches floating point. Raise the peak rate to 500°/s (8.7 rad/s) and you need 5 integer bits; at 2,000°/s (34.9 rad/s) you need 7. The full-scale range of the gyro sets the integer bits of the whole filter.

Madgwick: the step is the problem

Madgwick looks like Mahony, but the range finder gives a different answer: its largest intermediate is 447, which needs 10 integer bits. The cause is on the line that normalises the gradient. The code computes s0² + s1² + s2² + s3² (Chapter 3) before the inverse square root. The s terms are sums of several products and reach about 10, so their squares add up to hundreds. A Q2.30 word cannot hold that: the filter overflows 1,886 times and the tilt error peaks at 18.4°, with saturation. Two fixes are standard. Shift the s terms right by a few bits before squaring, which is a power-of-two scale you undo after. Or accept a few clamps at the peaks, because the vector is normalised again right away, so a clamped length hurts little. At Q8.24 the code has only 20 overflows and tracks floating point closely.

The EKF: three kinds of number, no single format

The EKF has the worst problem, and it is a different kind. Its variables fall into three families with very different sizes. The quaternion, the gyro numbers and the state vector need 3 integer bits at 180°/s. The covariance P and its helper matrices stay near 1 and need 2 bits (the identity matrix inside I − K H contains 1.0, which does not fit in a single sign-plus-fraction word). But S⁻¹, the inverse of the accelerometer doubt, is about 1 / r = 1 / 0.004 = 250. It reaches 247.5 in the run, and needs 9 integer bits.

Try one format for everything. With fewer than 9 integer bits, S⁻¹ overflows and the gain collapses. At exactly 9 (Q9.23) the filter works: its worst tilt error is 4.7° against 4.6° in floating point. But look at the other side. The grid step of Q9.23 is 1.2 × 10−7, barely finer than the process noise of 10−7 we add to P each step. One more integer bit (Q10.22) and the step grows past it, the added noise rounds away, and the worst error jumps to 125°. At Q12.20 it is 176°. The window is one bit wide. Lower r to 0.0004 and S⁻¹ climbs to about 2,500, which needs 13 bits and a grid of 1.9 × 10−6: the window is gone. The numbers span roughly 10−7 to 103, more decades than one 32-bit grid covers comfortably. The cure is to give each family its own format: Q3.29 for the state, Q2.30 for the covariance, Q9.23 for S and its inverse. Every product then shifts between formats. With these three, the fixed-point EKF matches the floating-point one on this recording. Turn on the per-variable switch to see it.

Run in a fixed word

The trace is the filter running in a 32-bit fixed-point word; the dashed line is the same filter in floating point. Red ticks mark overflows. Pick a filter, give it integer bits, then press Give each variable what it needs. Raise the peak rate to see the bits climb.

Q2.30
180 °/s

Everything is emulated: each intermediate result is rounded to the Qm.n grid of a 32-bit word and saturated or wrapped, as in Chapter 7. The inverse square roots are computed exactly and then rounded, standing in for a Newton loop. The EKF with per-variable formats uses the bits the range finder reports for the state, the covariance and the wide family (S, its inverse, K). The recording is the synthetic one of earlier chapters; its peak rate is the slider.

On real hardware. Board: nRF52840 DK or STM32 Nucleo-F411RE. Run the float version on the board over a recorded log, and add a tiny macro that keeps the running maximum of the absolute value of each named variable. Print the maxima at the end. Then compile the fixed-point version with its overflow counter turned on (count every saturation) and rerun the same log. The log must include your worst real motion: a drop, a shake, the top gyro full-scale setting.

Count the cost of the fix. The illustrative integer model of Chapter 5 puts Mahony at 177 cycles, Madgwick at 268 and the EKF at 1,385, against 113, 168 and 894 for floating point on an M4F. Fixed point did not save time here. What it saves is silicon, or it makes the code possible at all on a core without an FPU. And the work moves to you: you now own every scale factor. The symptom of a miss is a sudden tilt error of tens of degrees right at the peak of a fast motion, then a slow return. The measurement is an overflow counter that must read zero over a recording that includes your worst motion. The fix is more integer bits for that one variable, a scale before the squaring, saturation instead of wraparound, or floating point.

Your fixed-point EKF works in a single Q12.20 format but the tilt is wrong by tens of degrees, with no overflow counted. What is the most likely cause?

Chapter 9

Field Guide

Keep the numbers, the checklist, the core code and the sources

You can now build the three filters, price them, and break them on purpose. Here is the lesson on one page.

The one-paragraph summary

An orientation filter turns six sensor numbers into a quaternion every sample. The gyro predicts and drifts; the accelerometer corrects and is fooled by motion. Mahony feeds the cross-product error back to the gyro with a proportional and an integral gain; the integral term learns the bias. Madgwick takes one normalised gradient step of length β each sample; β must beat the bias rate. The EKF carries a covariance and weighs the correction by Q against R; it costs 5 to 8 times the cycles and gains a measure of its own doubt. On a Cortex-M4F all three fit in under 900 cycles and 712 bytes. The real limits are a wrong dt, a missing FPU, energy, and numeric range in fixed point. There the gyro full-scale sets the integer bits for Mahony, the squared gradient sets them for Madgwick, and the EKF needs one format per family of variable.

The numbers that matter

WhatNumberWhy it matters
Test recording20 s at 100 Hz; bias 0.02 rad/s on x; shake 0.5 gIllustrative and seeded; all error figures below come from it
Gyro alone / accelerometer alone22.3° off at 20 s / 31.7° off in the shakeWhy we fuse
Mahony, Kp 0.5, Ki 0.1RMS 1.16°, worst 2.9°; 56 mul, 33 add, 2 invSqrt = 113 cycles; 28 B stateCheapest; Ki learns the bias
Madgwick, beta 0.1RMS 0.76°, worst 2.5°; 88 mul, 44 add, 3 invSqrt = 168 cycles; 16 B stateOne knob; beta must beat the bias (max correction 2 beta rad/s)
EKF, qn 1e-7, r 0.004RMS 1.45°, worst 4.6°; 485 mul, 371 add, 1 div, 2 invSqrt = 894 cycles; 80 B state, 632 B scratchQ against R sets the gain; |K| falls 0.857 to 0.014
Madgwick's paperbeta 0.041 (IMU), 0.033 (MARG); under 0.8° static, 1.7° dynamic RMSOne adjustable parameter; matches a commercial Kalman sensor
Cortex-M4F, floatadd, sub, mul 1 cycle; MLA, FMA 3; DIV, SQRT 14; load, store 2Cortex-M4 TRM, FPU table; +1 if the next instruction uses the result
Cortex-M4, integerMUL, SMULL, SMLAL, SMLAD, SSAT, QADD 1 cycle; SDIV 2 to 12Fixed point is cheap per op, but each multiply needs a shift
invSqrtabout 12 cycles fast; 28 exact (VSQRT 14 + VDIV 14)Three per Madgwick update
STM32F411100 MHz; 512 KB flash; 128 KB SRAM; 1,000,000 cycles per sample at 100 HzEKF uses 0.09% of the core
RP20402 x Cortex-M0+ at 133 MHz; no FPU, float in boot ROM; 1-cycle multiplier; 8-cycle SIO divider; 264 kB SRAMEvery float op is a library call
dt wrong by +10%RMS 4.17° Mahony, 2.18° Madgwick, 3.44° EKFA biased dt is worse than random jitter
Q1.15, Q1.31step 3.05e-5 and 4.7e-10; largest value just under 1The identity quaternion (1.0) does not fit
Integer bits neededMahony 3, 5, 7 at 180, 500, 2000 °/s; Madgwick 10; EKF 3 / 2 / 9Range-find on your worst motion

The checklist

The core, as code

These few lines carry most of the lesson: the cycle counter, the range finder and the widening multiply. The filters themselves are the listings in Chapters 2 and 3.

c/* 1. Measure: DWT cycle counter on a Cortex-M4 (registers verified in CMSIS core_cm4.h). */
static inline void cyc_init(void) {
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;     /* DEMCR at 0xE000EDFC, bit 24 */
    DWT->CYCCNT = 0;                                 /* CYCCNT at 0xE0001004 */
    DWT->CTRL  |= DWT_CTRL_CYCCNTENA_Msk;               /* DWT_CTRL at 0xE0001000, bit 0 */
}
uint32_t t0 = DWT->CYCCNT;  mahony_update(gx,gy,gz, ax,ay,az, dt);  uint32_t cyc = DWT->CYCCNT - t0;

/* 2. Range-find: in the float build, wrap each variable you worry about. */
static float rng_max[32];
#define RANGE(i, x)  (rng_max[i] = fmaxf(rng_max[i], fabsf(x)), (x))
/* integer bits (sign included) = floor(log2(max)) + 2 for max >= 1, else 1 */

/* 3. Fixed point: a Qm.n multiply widens, shifts back, saturates. */
static inline int32_t qmul(int32_t a, int32_t b, int n)   /* all three in Qm.n, same n */
{
    int64_t p = ((int64_t)a * b) + ((int64_t)1 << (n - 1)); /* SMULL, then round */
    p >>= n;
    if (p >  INT32_MAX) { ovf++; p =  INT32_MAX; }          /* count every clamp */
    if (p <  INT32_MIN) { ovf++; p =  INT32_MIN; }
    return (int32_t)p;
}

Where this sits

This lesson is the filter end of the IMU track. fw-imu-01 explains the sensor errors we modelled as bias and noise. fw-imu-02 explains how samples and stamps arrive. fw-imu-03 shows why a small always-on core runs this filter, and why cycles become battery. fw-imu-04 removes bias first. For the maths of the filters themselves, read sf-05, sf-07, sf-06 and, for what happens when you integrate position as well, sf-13. Fixed-point practice continues in fw-aud-04, quantization noise and tinyml-06.

Keep going

Sources

No course slides exist for this lesson. Everything was checked against primary sources opened while writing it. Items marked "not opened" are named for the reader and were not read in full.

The takeaway. The three filters differ less than their reputations. On clean data they land within about a degree of each other. What decides a real design is the cost you can measure (cycles, bytes, joules), the clock you give the filter, and the range of numbers it must survive. Count first, measure second, and make the overflow counter read zero on your worst motion.
You must port the orientation filter to a Cortex-M0+ with no FPU and a tight energy budget. Which plan follows the lesson?

Now press Present or Teach and explain, from memory, how each filter turns a gap between predicted and measured gravity into a correction, what each costs in cycles and bytes, and which variable overflows first in fixed point. Then go back to the three traces at the top, set the gyro bias to 0.08, and say out loud which filter you would ship on a 100 MHz Cortex-M4F and which on a chip with no FPU.

Firmware from Zero to Expertise: Orientation Filters on an MCU
Field Guide and sources · Complementary filters and AHRS · Back to the Gleams hub