The Complementary Filter: One Truth from Two Liars
Four lines of code that keep drones level: trust the gyro for this instant, let gravity pull the estimate home over seconds — and one knob, alpha, to split the trust.
Builds on: 2.2 The IMU: Two Flawed Witnesses
Split the trust by timescale
Last lesson ended with two witnesses whose flaws live at opposite ends of the clock: accelerometer wrong in the moment, gyro wrong over the minutes. So assign trust by timescale — believe the gyro about change, believe gravity about where home is:
Read it as a recipe: advance the estimate with the gyro (smooth, instant), then blend in a pinch — 2% — of the accelerometer’s opinion. Each tick, that pinch tugs the estimate toward gravity’s drift-free “down”. Noise, arriving fresh and different every tick, gets multiplied by 0.02 and never accumulates. Drift, which needs the sum to build up, gets bled away faster than it grows. Both vices treated, with one another’s virtues.
Alpha is a timescale dial
α sets where “fast” ends and “slow” begins. At α = 0.98 and a 100 Hz loop, disturbances shorter than a couple of seconds are ruled by the gyro; anything steadier belongs to gravity. Push α to 0.999 and the filter trusts the gyro for minutes — drift creeps back in. Drop α to 0.5 and vibration floods through. The right value is a property of your robot: how buzzy its motors, how lazy its gyro.
The idea, not the trick
What you just built is sensor fusion — the general craft of merging differently-flawed measurements into one estimate better than any of them. The famous grown-up version is the Kalman filter, which does the same blend but recomputes the trust split every tick from how uncertain each source currently is — α, made self-adjusting, with proofs. Under the mathematics, the same soul: fast witness for the moment, steady witness for the long run.
The complementary filter is unreasonably effective for its size, and engineers write it with a slightly guilty grin. Start here, always. Graduate to Kalman when you can name the failure — not because the fancier filter must be better, but because you have measured why the simple one isn’t enough.
⚗️ Lab — The Fusion Desk
The drift bench again — but now a third trace: the fused estimate, with the α knob under your thumb.
- Set α = 0.98: the fused line hugs the truth through tilts, shrugs off vibration, and never drifts. Enjoy the moment.
- Slide α to 1.0 — you have unplugged gravity. Watch drift return. Slide toward 0.5 — hello vibration.
- Max the vibration knob, then find the α that best hides it. Notice you paid for it with sluggish response.