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.
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
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.
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.
Illustrative. A bias of 0.5 °/s is a common size for a cheap uncalibrated MEMS gyro.
| Time running | Tilt error at 0.5 °/s | What it means |
|---|---|---|
| 1 s | 0.5° | nobody notices |
| 10 s | 5° | the drone leans and slides |
| 60 s | 30° | the horizon is badly wrong |
| 5 min | 150° | 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.
Chapter 1
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.
theta-k equals theta-k-minus-one, plus omega-k times delta-t.
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 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°
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.
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.
Chapter 2
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.
theta-a equals a-tan-two of a-x and a-z.
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.
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.
The dashed line is the true down. The blue arrow is the down the accelerometer reports. Set a tilt, then push the phone sideways.
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).
Chapter 3
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.
theta-k equals alpha times, theta-k-minus-one plus omega-k delta-t, plus one minus alpha, times theta-a-k.
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 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.
Warm is gyro-only, faint blue is the accelerometer, teal is the filter, dashed is the truth. Drag alpha to its ends and back.
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.
Chapter 4
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.
tau equals alpha times delta-t, over one minus alpha.
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.
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.
e-s-s equals b times tau.
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.
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.
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.
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).
Chapter 5
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 orientation | Anchor | Reference direction |
|---|---|---|
| Pitch and roll | accelerometer | gravity, straight down |
| Yaw (heading) | magnetometer | magnetic 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.
psi equals a-tan-two of minus m-y and m-x.
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 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.
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.
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.
Chapter 6
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.
| Filter | How it corrects | Trust knob | Learns the bias? |
|---|---|---|---|
| Complementary (Ch 3) | weighted average of one angle | alpha | no |
| Mahony (2008) | feedback: a proportional plus integral term | k-P, k-I | yes |
| Madgwick (2011) | one gradient-descent step toward the orientation that best fits gravity and north | beta | in 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.
b-hat-k equals b-hat-k-minus-one, minus k-I times epsilon-k times delta-t.
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 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.
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.
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.
Chapter 7
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.
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.
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°.
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
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:
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:
the size of, the norm of a minus g, is less than delta.
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 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°.
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.
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.
Chapter 9
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.
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.
| Failure | Symptom | Test | Fix |
|---|---|---|---|
| Linear push | the horizon leans into hard turns | log ‖a‖; error spikes when it leaves 1 g | gate the accelerometer (Chapter 8) |
| Magnetic interference | heading jumps with throttle or near steel | log the field length against throttle | move and calibrate the magnetometer; gate it |
| Alpha mistuned | slow lean (too high) or shake (too low) | still test for drift, shake test for jitter | set tau after calibrating the bias |
| Quaternion decay or sign flip | slow skew, or a sudden 360° jump in logs | log the quaternion's length and sign | normalise every tick; keep the scalar part positive |
| Wrong delta-t | a 90° turn reads 81° or 99° | turn by a known angle; log real timestamps | measure 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.
Chapter 10
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.
| Term | Meaning | Typical number |
|---|---|---|
| Gyro bias | rate the gyro reads at rest | 0.5 °/s uncalibrated MEMS |
| Drift | bias times time, gyro alone | 30° per minute at 0.5 °/s |
| Alpha | the gyro's share each tick | 0.98 to 0.99 at 100 Hz |
| Tau | alpha Δt / (1 − alpha) | 0.5 to 1 s |
| Steady error | bias times tau | 0.245° at 0.5 °/s, tau 0.49 s |
| Gate | use the accelerometer only near 1 g | delta about 0.5 m/s² |
| Earth's field | what the magnetometer reads | about 25 to 65 µ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
| Product | Why this filter |
|---|---|
| Racing drone flight controller | a few multiplies per axis fits a loop of thousands of hertz on a small microcontroller |
| Open autopilots | ArduPilot's DCM estimator is a complementary filter with bias correction, in the Mahony style |
| VR headset | the gyro gives head turns with almost no lag; cameras correct the slow drift on top |
| Phone and watch | screen 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.
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.
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.