Complementary Filters and AHRS

A gyroscope is fast but drifts. An accelerometer never drifts but shakes. Take 98% of the gyro's guess and 2% of the accelerometer's each tick, and the tilt estimate is smooth and stays anchored.

Pick an estimator and watch it race the true tilt. Then add a shove and see who gets fooled. Then we build it piece by piece: the gyro, the accelerometer, the one-line filter, a compass for heading, and the filters drones run.

You need basic arithmetic and the idea of an angle. We build the rest from zero.

Lesson 6 of 22 in Sensor Fusion: Classical to Modern. It follows The Kalman Filter and leads to The Extended Kalman Filter.

Hold the board's tilt

0 m/s²

Illustrative toy at 100 Hz. The board sways ±25°; gyro bias 1.5 °/s; accelerometer noise 0.5 m/s²; alpha 0.98. The shove is a sideways push for 0.8 s in every 4 s. Gyro only resets when it drifts past 45°.

Chapter 0

Which Way Is Up?

See why a drone needs two motion sensors to know its tilt, and why neither one works alone

A quadcopter hovers in your living room. Hundreds of times a second it asks which way is up, measures how far it leans, and pushes back with its motors. If its answer is off by five degrees, it slides sideways and hits the floor.

The answer is its attitude: how the body is tilted and turned in space. It comes from one small chip, the IMU (inertial measurement unit). An IMU holds two sensors:

Each sensor almost answers the question. The gyro reports turn rate, so you add up the turns to get the angle. A tiny constant error in the rate, called a bias, adds up too. The accelerometer sees gravity directly, so it never drifts. But any push on the body looks like gravity to it, so its tilt reading shakes.

Run the clock on a biased gyro

The drone sits level. Its gyro reads a small rate even at rest. Drag the clock and watch the horizon the drone believes in tilt away from the real one.

0.5 °/s
60 s

Illustrative. A bias of 0.5 °/s is a common size for a cheap uncalibrated MEMS gyro.

Time runningTilt error at 0.5 °/sWhat it means
1 s0.5°nobody notices
10 s5°the drone leans and slides
60 s30°the horizon is badly wrong
5 min150°up is nearly sideways

The two sensors fail in opposite ways. The gyro is right over a fraction of a second and wrong over a minute. The accelerometer is wrong over a fraction of a second and right over a minute. A complementary filter takes the fast part from the gyro and the slow part from the accelerometer.

The failure to avoid: a gyro-only estimate. Symptom: the attitude leans further every second with no motion. Measure: leave the device still and plot the angle; a straight ramp is bias. Fix: add an absolute reference, the accelerometer.

The road

  1. The gyroscope: add up the turn rate, and watch the bias pile up.
  2. The accelerometer: read tilt from gravity, and see a shove fool it.
  3. The complementary filter: one line that blends the two.
  4. Why the drift stops: the time constant and the bounded error.
  5. Heading: gravity cannot see north, so add a magnetometer.
  6. Mahony and Madgwick: the 3-D filters, and learning the bias.
  7. Showcase: tune alpha and shove the board until it breaks.
  8. Tuning: calibrate, pick the gain, and gate the accelerometer.
  9. Five failures: the symptom and the test for each.
  10. Field guide: the numbers, the code and where to go next.
Why can a drone not use its gyroscope alone to know its tilt?

Chapter 1

The Gyroscope Drifts

Turn a rate into an angle by adding it up, and watch a tiny bias grow into a large error

Turn a phone at a steady 90 degrees per second. Its gyro reads 90 the whole time, and 0 when you stop. That reading is the angular rate. It reacts at once and has little noise, so the gyro carries the fast part of any tilt estimate.

To get an angle, add up the turns. Call the angle after tick k θk, the gyro reading at that tick ωk, and the time between readings Δt.

Say it aloud

theta-k equals theta-k-minus-one, plus omega-k times delta-t.

θk
theta-k the angle after this tick, in degrees.
θk−1
theta-k-minus-one the angle after the last tick.
ωk
omega-k the gyro reading at this tick, in degrees per second.
Δt
delta-t the time between two readings: 0.01 s for a 100 Hz gyro.
In plain words

Multiply the gyro reading omega-k by the tick time delta-t to get this tick's turn. Add that turn to the old angle. The sum is the new angle theta-k.

With numbers

With made-up numbers: the old angle is 10.0°, the gyro reads 20 °/s, and delta-t is 0.01 s. The turn is 20 × 0.01 = 0.2°, so theta-k = 10.2°.

Now give the gyro a bias b of 0.5 °/s: it reads 0.5 even at rest. Each tick adds 0.5 × 0.01 = 0.005° of false turn. After t seconds the error is b times t:

error after t seconds = b · t = 0.5 °/s × 60 s = 30°

Integrate a still gyro for a minute

The device does not move, so the true angle is the dashed zero line. Drag the bias and the noise. Then switch on bias removal, as if you had measured the bias at start-up.

0.50 °/s
0.30 °/s

Illustrative toy: 6,000 ticks at 100 Hz, seeded noise. Bias removal subtracts the true bias exactly, which a real start-up average cannot do exactly.

The bias makes a straight ramp. The noise adds a slow random wander on top. It grows like the square root of time, so the bias dominates. Subtract the bias and only the wander is left.

The bias hides inside real motion. A device turns at 10 °/s for 3 s, then stops. The gyro reads 10.5 during the turn and 0.5 after. During the turn it is off by only 1.5°. After 57 still seconds it is off by 30°: it reports 60° for a 30° turn.

The failure: an uncalibrated bias. Symptom: the estimate leans more each second while the device sits still. Measure: hold the device still for 2 s and average the gyro; the average is the bias. Fix: subtract it from every reading.

A still device has a gyro bias of 0.5 °/s. What does the gyro-only angle read after 60 s?

Chapter 2

The Accelerometer Feels Gravity

Read the tilt straight from gravity, then watch a sideways push fake a tilt

A phone lies still on a table. Its accelerometer reads 9.8 m/s² upward. The table pushes up on the phone to stop it falling, and the sensor feels that push. At rest, the reading points straight away from the ground.

Tilt the phone and that fixed push spreads over its axes. Call the reading along the phone's long axis ax and the reading through its face az. At a tilt θ, ax = g sin θ and az = g cos θ, where g is 9.8 m/s². The ratio cancels g.

Say it aloud

theta-a equals a-tan-two of a-x and a-z.

θa
theta-a the tilt the accelerometer reports, in degrees.
atan2
a-tan-two the angle whose tangent is a-x over a-z. It handles every quadrant and a zero a-z.
ax
a-x the reading along the long axis, in m/s².
az
a-z the reading through the face, in m/s².
In plain words

Divide a-x by a-z and find the angle with that tangent. That angle is the tilt theta-a. One reading is enough: there is no running total, so there is no drift.

With numbers

The sensor reads a-x = 4.9 and a-z = 8.49 m/s². The ratio is 0.577, so theta-a = 30°. The length is √(4.9² + 8.49²) = 9.8 m/s², exactly 1 g.

The length of the reading is the honesty test. With only gravity acting, it is 1 g at every tilt. Tilting only moves gravity from one axis to the other.

Shove a tilted phone

The dashed line is the true down. The blue arrow is the down the accelerometer reports. Set a tilt, then push the phone sideways.

0°
4.0 m/s²

Exact geometry for a push along the world horizontal; no sensor noise.

The accelerometer cannot tell gravity from a push. A flat phone pushed sideways at 4 m/s² reads ax = 4 and az = 9.8. It reports atan2(4, 9.8) = 22° of tilt for a phone that is flat. The length gives it away: 10.58 m/s², or 1.08 g.

The failure: hard braking. A phone mounted level on a dashboard sees 7 m/s² of braking. Symptom: it reports 35.5° of nose-down tilt. Measure: the length is 12.0 m/s², or 1.23 g. Fix: trust the accelerometer only when the length is near 1 g (Chapter 8).

A flat phone is pushed sideways at 4 m/s². Its accelerometer reports a tilt of about 22°. Why?

Chapter 3

The Complementary Filter

Predict with the gyro, then pull the prediction a small step toward the accelerometer

You walk in fog and count your steps. Now and then you see a landmark and correct yourself. The step count carries you between landmarks. The landmarks stop the count from wandering off. The filter does the same with the two sensors.

Each tick has three numbers: the old estimate θk−1, the gyro rate ωk, and the accelerometer tilt θa,k. Pick a trust weight α (alpha) between 0 and 1 for the gyro.

Say it aloud

theta-k equals alpha times, theta-k-minus-one plus omega-k delta-t, plus one minus alpha, times theta-a-k.

θk
theta-k the fused tilt after this tick.
α
alpha the gyro's share of trust, between 0 and 1; 0.98 is a common value.
θk−1 + ωkΔt
theta-k-minus-one plus omega-k delta-t the gyro's prediction: the old estimate plus this tick's turn (Chapter 1).
1 − α
one minus alpha the accelerometer's share. The two shares add to 1.
θa,k
theta-a-k the accelerometer's tilt at this tick (Chapter 2).
In plain words

Add this tick's gyro turn to the old estimate to get a prediction. Take alpha of the prediction and one minus alpha of the accelerometer tilt theta-a-k. Add them to get theta-k.

With numbers

With made-up numbers: old estimate 10.0°, gyro 20 °/s, delta-t 0.01 s, accelerometer 9.0°, alpha 0.98. The prediction is 10.2°. Then 0.98 × 10.2 + 0.02 × 9.0 = 9.996 + 0.18 = 10.176°. The estimate follows the gyro and moves 0.024° toward the accelerometer.

That small pull happens 100 times a second. Over many ticks it cancels the gyro's slow drift. Because each accelerometer reading gets only 2% of the say, its shake averages out.

Turn the trust dial alpha

Warm is gyro-only, faint blue is the accelerometer, teal is the filter, dashed is the truth. Drag alpha to its ends and back.

0.980

Illustrative toy: 12 s at 100 Hz, the board sways ±25° at 0.25 Hz, gyro bias 0.8 °/s, accelerometer tilt noise ±4°. The slider runs alpha from 0.5 to 0.999.

Both ends fail. Near 1, almost no accelerometer leaks in and the gyro's drift survives. Near 0.5, half of each shaky reading passes through. Between them the error is smallest.

The failure: initialising at zero. Symptom: for the first second the estimate climbs slowly toward the true tilt. Measure: start the device at a known 20° tilt and log the first second. Fix: set the first estimate from the accelerometer's first reading.

Old estimate 10.0°, gyro 20 °/s, delta-t 0.01 s, accelerometer 9.0°, alpha 0.98. What is the new estimate?

Chapter 4

Why the Drift Stops

Turn alpha into a time constant, and find the small error the bias leaves behind

A gyro-only estimate drifts forever. The filter's estimate drifts a little and then stops. Why does it stop, and where?

Alpha alone means little, because the pull happens once per tick. A 1,000 Hz loop pulls ten times as often as a 100 Hz loop. A better knob is time. Call the filter's time constant τ (tau): about how long the accelerometer takes to pull out an old error.

Say it aloud

tau equals alpha times delta-t, over one minus alpha.

τ
tau the time constant, in seconds. Motions faster than tau come from the gyro; slower ones from the accelerometer.
α
alpha the gyro's share of trust.
Δt
delta-t the tick time, in seconds.
1 − α
one minus alpha the accelerometer's share: the fraction of the gap it closes each tick.
In plain words

Multiply alpha by the tick time delta-t. Divide by the accelerometer's share, one minus alpha. The result tau is the hand-over time between the two sensors.

With numbers

At 100 Hz with alpha 0.98: tau = 0.98 × 0.01 / 0.02 = 0.49 s. The crossover frequency is 1/(2πτ) = 0.32 Hz. To keep tau at 0.49 s in a 1,000 Hz loop, alpha must be 0.998.

Now the bound. Hold the device still with a gyro bias b. Each tick the gyro pushes the estimate up by bΔt. The accelerometer pulls it back by the share 1 − α of the gap. The estimate stops where push and pull balance. Call that error ess, the steady-state error.

Say it aloud

e-s-s equals b times tau.

ess
e-s-s the steady-state error: where the filter's estimate settles on a still device, in degrees.
b
b the gyro bias, in degrees per second.
τ
tau the time constant, in seconds.
In plain words

Multiply the bias b by the time constant tau. That is the error e-s-s where the estimate stops. A gyro alone would keep going.

With numbers

A calibrated gyro with b = 0.5 °/s and tau = 0.49 s settles at 0.245°. An uncalibrated one with b = 5 °/s settles at 2.45°. A gyro alone with b = 5 would be 300° off after a minute.

Watch the error level off

A still device, a biased gyro. Press Play. Warm climbs forever. Teal climbs, then sits on the purple line at b times tau. Drag alpha and the bias.

0.980
5.0 °/s

Exact recursion at 100 Hz on a still device with a noise-free accelerometer; 3 seconds shown.

Seen as frequencies, the gyro path keeps fast changes and drops slow ones: a high-pass filter. The accelerometer path keeps slow ones and drops fast ones: a low-pass filter. Their two responses add to exactly 1 at every frequency. That is why the name is complementary.

The failure: alpha copied from a forum. Symptom: the filter behaves differently after you raise the loop rate. Measure: compute tau from alpha and your real delta-t. Fix: choose tau in seconds and compute alpha = τ / (τ + Δt).

A still device has a gyro bias of 2 °/s and a filter with tau = 0.5 s. Where does the filter's error settle?

Chapter 5

Heading Needs a Compass

See why gravity cannot fix heading, and anchor it to magnetic north instead

Spin a level phone on a table like a turntable. Gravity still points straight through its face. The accelerometer reads the same facing north or south. So it can fix pitch and roll, the two tilts, but not yaw, the heading. Yaw rides on the gyro alone and drifts.

Every drifting axis needs an absolute anchor. For heading, the anchor is Earth's magnetic field, read by a magnetometer. A gyro, an accelerometer and a magnetometer fused into full orientation make an AHRS (attitude and heading reference system).

Part of orientationAnchorReference direction
Pitch and rollaccelerometergravity, straight down
Yaw (heading)magnetometermagnetic north, horizontal

Hold the device level. Call the field along its nose mx and the field out its right side my. Call the heading ψ (psi), measured clockwise from magnetic north.

Say it aloud

psi equals a-tan-two of minus m-y and m-x.

ψ
psi the heading: degrees clockwise from magnetic north to the nose.
atan2
a-tan-two the angle of a direction from its two parts.
−my
minus m-y the field out the right side, with its sign flipped. North off to the left gives a negative m-y.
mx
m-x the field along the nose, in microtesla.
In plain words

Flip the sign of the side reading m-y. Find the angle of the direction made of minus m-y and m-x. That angle is the heading psi.

With numbers

With made-up numbers: m-x = 22 µT and m-y = −12.7 µT, so north is off to the left. Then psi = atan2(12.7, 22) = 30°. The nose points 30° east of magnetic north.

The heading filter is a second copy of the Chapter 3 line: predict yaw with the gyro, pull it toward psi with 1 − α. The filter needs two corrections first. Earth's field dips steeply into the ground, so a tilted device must rotate its reading level with the accelerometer's pitch and roll. And magnetic north differs from true north by the local declination, a fixed offset.

Anchor the heading, then bring in a motor

The device turns 90° and back. Warm is gyro-only, pink is the magnetometer, teal is the fused heading. Drag the interference: it starts at 10 s, like a motor spinning up.

0°

Illustrative toy: gyro yaw bias 1 °/s, magnetometer heading noise ±2°, alpha 0.98. The interference adds a fixed false bearing.

The failure: a magnetic field near the sensor. Earth's field is weak, about 25 to 65 µT. Motor currents and steel overpower it. Symptom: the heading is fine on the bench and wrong at high throttle. Measure: log the field's length; it should stay constant. Fix: mount the magnetometer away from power wires, calibrate it, and skip its correction when the length jumps.

Why can the accelerometer not correct heading drift?

Chapter 6

Mahony and Madgwick

Lift the filter into 3-D with quaternions, and let it learn the gyro's bias as it runs

A real drone turns about three axes at once. Three stacked angles break: pitch the nose straight up and the roll and yaw axes line up. One degree of freedom is lost and the maths divides by zero. This is gimbal lock.

Both modern filters hold orientation as a quaternion: four numbers that store a rotation axis and an angle. One multiplication applies a small turn, and no orientation breaks it. The gyro still rotates the quaternion each tick. Gravity and north still correct it.

FilterHow it correctsTrust knobLearns the bias?
Complementary (Ch 3)weighted average of one anglealphano
Mahony (2008)feedback: a proportional plus integral termk-P, k-Iyes
Madgwick (2011)one gradient-descent step toward the orientation that best fits gravity and northbetain a variant

Mahony's proportional term is the Chapter 3 pull: kP Δt plays the role of 1 − α. Its new part is the integral term. If the correction keeps pushing the same way, the gyro has a bias. So the filter keeps a running bias estimate b̂ (b-hat) and subtracts it from every gyro reading. Here is the one-axis form. Call the tilt error εk = θa,k − θk: the accelerometer's tilt minus the estimate.

Say it aloud

b-hat-k equals b-hat-k-minus-one, minus k-I times epsilon-k times delta-t.

b̂k
b-hat-k the bias estimate after this tick, in degrees per second. The filter subtracts it from the gyro.
b̂k−1
b-hat-k-minus-one the bias estimate after the last tick.
kI
k-I the integral gain, per second squared: how fast the estimate learns.
εk
epsilon-k the tilt error: the accelerometer's tilt minus the estimate, in degrees.
Δt
delta-t the tick time.
In plain words

If the estimate sits above the accelerometer, epsilon-k is negative, so b-hat grows. Each tick adds k-I times the error times delta-t. When b-hat equals the true bias, the error is zero and b-hat stops.

With numbers

With made-up numbers: the estimate sits 0.2° above the accelerometer, so epsilon-k = −0.2°. With k-I = 0.5 and delta-t = 0.01 s, b-hat rises by 0.5 × 0.2 × 0.01 = 0.001 °/s each tick. That is 0.1 °/s per second while the error lasts.

Let the filter learn the bias

A still device with a 0.5 °/s gyro bias. Top: tilt error of the plain filter (grey) and Mahony (teal). Bottom: the bias estimate (purple). Drag k-I.

0.50

Exact one-axis Mahony recursion at 100 Hz with k-P = 2 per second (the same pull as alpha 0.98) and a noise-free accelerometer.

With k-I = 0.5, b-hat reaches 0.47 °/s in 10 s and the error goes to zero. The plain filter parks at 0.245° forever. Madgwick gets the same behaviour as an optimiser. Each tick it steps the quaternion downhill on the mismatch between predicted and measured gravity and north. Its step size is beta.

The failure: k-I set too high. Symptom: the bias estimate swings past the true value and the attitude wobbles slowly. Measure: log b-hat on a still device; it should rise and settle, not ring. Fix: lower k-I, and freeze the bias update while the accelerometer is not trusted.

What does Mahony's integral term add over the plain complementary filter?

Chapter 7

Showcase: Break the Estimator

Run all three estimators on one board, then push alpha and the shove until each one fails

Everything so far runs in one instrument. The board sways. A gyro and an accelerometer read it. Three estimates race the dashed truth. You hold the two knobs that decide whether the filter works.

Tune alpha, shove the board

Left: the board at its true tilt with the teal needle of the filter. Right: gyro-only (warm), accelerometer (blue), filter (teal). Try the presets, then the shove.

0.980
0 m/s²

Illustrative toy at 100 Hz: board ±25° at 0.2 Hz, gyro bias 1.5 °/s, accelerometer noise 0.5 m/s². The shove lasts 0.8 s in every 4 s. Alpha runs from 0.5 to 0.999. Gyro only resets when it drifts past 45°.

Five steps to try

  1. Press Good. Teal follows the truth: smooth like the gyro, anchored like the accelerometer.
  2. Press Alpha too high. Teal goes smooth and slowly leaves the truth. Tau is 10 s, so b times tau is 15°.
  3. Press Alpha too low. Teal stops drifting and starts to shake. 40% of each noisy reading gets through.
  4. Back at 0.98, raise the shove to 6. Blue jumps on each push, and teal wobbles a little with it.
  5. Keep the shove at 6 and lower alpha. The error grows: you now trust the sensor that is lying.

Steps 2 and 3 fail in opposite ways. Step 5 shows that the best alpha depends on the motion. Trust the accelerometer more when the device is still and less when it is pushed. Chapter 8 turns that into a rule.

Chapter 8

Tune It and Gate the Accelerometer

Calibrate first, pick tau, then listen to the accelerometer only when it feels 1 g

A filter that should work often fails because the raw sensors are off. Do these three calibrations before you tune anything:

  1. Gyro bias. Hold still for 2 s, average 200 readings, subtract the average forever. An average of 0.48 °/s against a true 0.5 leaves 0.02 °/s: 1.2° per minute, 25 times less drift.
  2. Accelerometer scale and offset. Point each axis up and down. Fix each axis so 1 g reads 1 g.
  3. Magnetometer hard and soft iron. Turn the device through every orientation. Fit the warped ellipsoid of readings back to a centred sphere.

Then pick tau. Set it below your real motions, so the gyro carries the moves, and long enough to average the accelerometer's shake. For handheld and flying devices, 0.5 to 1 s is the usual start: alpha 0.98 to 0.99 at 100 Hz.

The last step fixes the shove. Call the length of the accelerometer reading ‖a‖. At rest it equals g. Pick a tolerance δ (delta). Use the accelerometer only when this holds:

Say it aloud

the size of, the norm of a minus g, is less than delta.

| … |
the size of the absolute value: drop the sign.
‖a‖
the norm of a the length of the reading: √(ax² + az²) on one axis pair, in m/s².
g
g gravity, 9.81 m/s².
δ
delta the tolerance, such as 0.5 m/s², about 5% of g.
In plain words

Find the length of the reading. Subtract g and drop the sign. If the result is under delta, run the normal update. If not, something pushes the device: use the gyro prediction alone this tick.

With numbers

With made-up numbers: a reading of (1.70, 9.66) has length 9.81, so the gap is 0.00 and the filter uses it. A reading of (7.5, 9.66) during a hard turn has length 12.23, a gap of 2.42, over delta = 0.5. The filter skips it, and does not pull toward its false 37.8°.

Gate the accelerometer through a maneuver

The board holds 10° while three pushes hit it. Top: grey is the fixed filter, teal is the gated one. Bottom: the reading's length (blue) and the trust band (purple). Drag delta.

0.5 m/s²

Illustrative toy: pushes of 4, 6 and 8 m/s² for 0.6 s each, gyro bias 0.5 °/s, accelerometer noise 0.15 m/s², alpha 0.95.

The failure: a delta that is too tight. Symptom: on a vibrating drone the accelerometer never passes, so the estimate drifts like a gyro. Measure: log the fraction of ticks that pass the gate. Fix: widen delta, or lower the accelerometer's share smoothly as the gap grows.

What is the simplest test that the accelerometer is being fooled by a push right now?

Chapter 9

Five Ways an AHRS Fails

Match each quiet failure to its symptom and to the one log that exposes it

An attitude filter rarely crashes. It leans, shakes, or jumps once and recovers, and the symptom seldom names the cause. Each failure below has a symptom, a test and a fix.

Pick a fault, read the log

Top: the estimate (teal) against the dashed truth. Bottom: the log that names the fault. Pick each fault in turn.

Illustrative toys at 100 Hz. Wrong delta-t: the code assumes 0.01 s but the loop runs at 90 Hz.

FailureSymptomTestFix
Linear pushthe horizon leans into hard turnslog ‖a‖; error spikes when it leaves 1 ggate the accelerometer (Chapter 8)
Magnetic interferenceheading jumps with throttle or near steellog the field length against throttlemove and calibrate the magnetometer; gate it
Alpha mistunedslow lean (too high) or shake (too low)still test for drift, shake test for jitterset tau after calibrating the bias
Quaternion decay or sign flipslow skew, or a sudden 360° jump in logslog the quaternion's length and signnormalise every tick; keep the scalar part positive
Wrong delta-ta 90° turn reads 81° or 99°turn by a known angle; log real timestampsmeasure delta-t each tick; check units

Wrong delta-t, worked: the code assumes 0.01 s, but the loop runs at 90 Hz, so each tick lasts 0.0111 s. Every tick credits only 0.01 s of turn, so every turn shrinks by the same ratio. A true 90° turn reads 90 × 0.01 / 0.0111 = 81°.

Most failures are one of three kinds. An anchor lies: the accelerometer is pushed or the magnetometer sits near metal. The trust dial is wrong. Or the bookkeeping breaks: an unnormalised quaternion or a bad delta-t. So log the two lengths, run the still and shake tests, and check the bookkeeping.

A drone's horizon is right in gentle flight but leans into every hard turn, then recovers. What is it, and what is the fix?

Chapter 10

Field Guide

Keep the numbers, the checklist and the code in one place, then go on to the next filter

Predict with the fast sensor, correct with the stable one. The gyro carries the motion. The accelerometer pulls tilt toward gravity, and the magnetometer pulls heading toward north. The weights add to one. The leftover error is the bias times tau, and Mahony removes even that.

TermMeaningTypical number
Gyro biasrate the gyro reads at rest0.5 °/s uncalibrated MEMS
Driftbias times time, gyro alone30° per minute at 0.5 °/s
Alphathe gyro's share each tick0.98 to 0.99 at 100 Hz
Taualpha Δt / (1 − alpha)0.5 to 1 s
Steady errorbias times tau0.245° at 0.5 °/s, tau 0.49 s
Gateuse the accelerometer only near 1 gdelta about 0.5 m/s²
Earth's fieldwhat the magnetometer readsabout 25 to 65 µT

Checklist

  1. Calibrate the gyro bias, the accelerometer and the magnetometer.
  2. Start the estimate from the first accelerometer reading.
  3. Choose tau in seconds; compute alpha from the real delta-t.
  4. Gate the accelerometer on its length; gate the magnetometer on its length.
  5. In 3-D: use a quaternion, normalise it every tick, and learn the bias.
  6. Log both lengths, the quaternion's length and delta-t.
pythonimport math

def tilt_step(theta, w, ax, az, dt, tau=0.5, g=9.81, tol=0.5):
    alpha = tau / (tau + dt)                      # same filter at any loop rate
    pred = theta + w * dt                          # gyro prediction, always
    if abs(math.hypot(ax, az) - g) >= tol:          # pushed: the accel is lying
        return pred                                 # coast on the gyro
    theta_a = math.degrees(math.atan2(ax, az))     # tilt from gravity
    return alpha * pred + (1 - alpha) * theta_a

tilt_step(10.0, 20.0, 1.70, 9.66, 0.01)   # length 9.81: trusted -> about 10.20
tilt_step(10.0, 20.0, 7.50, 9.66, 0.01)   # length 12.23: skipped -> 10.2

Where it runs

ProductWhy this filter
Racing drone flight controllera few multiplies per axis fits a loop of thousands of hertz on a small microcontroller
Open autopilotsArduPilot's DCM estimator is a complementary filter with bias correction, in the Mahony style
VR headsetthe gyro gives head turns with almost no lag; cameras correct the slow drift on top
Phone and watchscreen rotation must not flicker, and the filter must run all day on a small battery

The Kalman filter is the same predict and correct loop. It computes the trust split each tick from the noise statistics and tracks its own uncertainty. Higgins (1975) compares the two and shows the link. Reach for the complementary filter first; move to a Kalman filter when you need the uncertainty or more accuracy.

Keep going

References

The takeaway. The gyro is right over a second; the accelerometer is right over a minute. Blend them with weights that add to one, and the drift stops at bias times tau.
A colleague says: our drone fuses a gyro and an accelerometer, so its heading will never drift. What is the correction?

Now press Present or Teach and rebuild it from memory. Cover the drift ramp, the tilt from gravity, the one-line filter, tau, the compass and the learned bias. Then go back to the board and say why the shove fools one estimator and not the others.

Credit

Lesson 6 of 22 in Sensor Fusion: Classical to Modern on Engineermaxxing. The filters follow Mahony et al. (2008), Madgwick (2011) and Higgins (1975). Every toy number on this page carries the word illustrative.

Sensor Fusion: Classical to Modern · Lesson 6: Complementary Filters and AHRS
Previous: The Kalman Filter · Next: The Extended Kalman Filter · Back to Gleams