20  Complementary Filters and IMU Fusion

analytics-ml
data
fusion
complementary

20.1 Start With the Story

Picture an IoT team using the ideas in Complementary Filters and IMU Fusion during a live operations review. A device has produced messy evidence, an analytic step is about to change an alert or control decision, and someone has to explain why the result should be trusted.

Read this page as that path from sensor evidence to accountable action. Start with what the system observes, keep the model or data treatment visible, and finish with the check that would convince an operator, maintainer, or auditor to act.

20.2 Complementary Filter Trust

A complementary filter is a lightweight IMU fusion method that combines gyroscope integration with an accelerometer gravity reference. The gyroscope is responsive over short intervals, but bias and noise accumulate into drift when angular rate is integrated. The accelerometer gives an absolute roll and pitch reference from gravity when the device is not accelerating hard, but it is noisy during vibration and linear motion.

The filter works because those errors are complementary. It trusts the gyroscope for fast changes and uses a small accelerometer correction to pull the estimate back toward the gravity reference over time. In signal terms, the gyroscope path behaves like a high-pass contribution and the accelerometer path behaves like a low-pass correction.

For three-dimensional orientation, name the axis convention before naming the filter. In the usual aircraft convention, roll is rotation about the forward x-axis, pitch is rotation about the lateral y-axis, and yaw is rotation about the vertical z-axis. Wearable systems also need the body-plane mapping: sagittal, coronal, and transverse planes must be tied to the sensor mounting frame. Store that transform with the data; otherwise a correct filter can publish inverted or swapped roll, pitch, and yaw.

Use a complementary filter when you need a simple, reviewable roll/pitch estimator on constrained hardware. Do not treat it as a full state estimator: a 6-DOF accelerometer-plus-gyroscope IMU does not observe yaw drift without another reference such as a magnetometer, visual landmark, wheel odometry, or external heading source.

Phoebe the physics guide

Phoebe’s Why

An IMU does not measure attitude directly. The gyroscope measures angular rate, so attitude appears only after integration, and any small bias is integrated too. The accelerometer measures specific force; when gravity dominates, its direction gives a roll and pitch reference, but motion and vibration contaminate that reference. A complementary filter is the ledger that keeps both pieces honest: gyro evidence carries the fast step, and accelerometer gravity evidence pays down the slow drift.

The Derivation

Gyro rate is the time derivative of angle:

\[\omega = \frac{d\theta}{dt}\]

Over one sample interval:

\[\theta_g[k] = \theta[k-1] + \omega[k]\Delta t\]

Accelerometer tilt comes from the gravity vector when linear acceleration is small:

\[\phi_a = \operatorname{atan2}(a_y, a_z)\]

\[\theta_a = \operatorname{atan2}(-a_x, \sqrt{a_y^2+a_z^2})\]

The one-axis complementary update is:

\[\theta[k] = \alpha\theta_g[k] + (1-\alpha)\theta_a[k]\]

The error left after \(N\) equal samples is:

\[e_N = \alpha^N e_0\]

For a continuous-time comparison:

\[\tau = \frac{-\Delta t}{\ln\alpha}\]

Worked Numbers: This Chapter’s Roll Update

  • Gyro prediction: \(8.00 + 12.0\times0.01 = 8.12^\circ\).
  • Complementary blend: \(0.98\times8.12 + 0.02\times6.00 = 7.9576 + 0.1200 = 8.08^\circ\) to 3 s.f.
  • Correction size: the output moves \(8.12 - 8.0776 = 0.0424^\circ\) back toward the accelerometer reference in this 10 ms step.
  • Exact time constant: \(\tau = -0.01/\ln(0.98) = 0.495\) s, which matches the chapter’s rounded \(0.50\) s rule.
  • Crossover frequency: \(f_c = 1/(2\pi\tau) = 1/(2\pi \times 0.495) \approx 0.32\) Hz – below this the accelerometer’s slow, drift-free view dominates; above it the gyro’s fast view does. The \(\alpha\) knob is this crossover point in disguise.
  • Five-degree drift check: after 50 samples, \(5.0\times0.98^{50} = 1.82^\circ\) remains; the chapter’s continuous approximation gives \(5.0e^{-1}=1.84^\circ\).

The physical lesson is that alpha is not a confidence score by itself. It only makes sense with the measured sample period, bias calibration, gravity gate, axis convention, and a clear label that yaw is unobservable without another heading reference.

IMU fusion architecture with gyroscope, accelerometer, and magnetometer evidence feeding calibration and fusion logic for roll, pitch, and yaw outputs.
For complementary IMU fusion, the gyro-plus-accelerometer path estimates roll and pitch; yaw must be backed by magnetometer or external heading evidence, or labeled as drifting.

Gyroscope

Measures angular rate. Integration gives smooth short-term attitude changes but accumulates bias drift.

Accelerometer

Measures gravity plus linear acceleration. It can correct roll and pitch when gravity is the dominant acceleration.

Alpha

The blend coefficient. Higher alpha trusts gyro prediction longer; lower alpha applies faster accelerometer correction.

Evidence

Outputs should carry sample period, axis convention, alpha, calibration state, and degraded labels when gravity is unreliable.

Input
Useful Evidence
Weak Assumption
Control
Gyroscope
Bias estimate, temperature range, saturation flags, and angular-rate units.
Assuming integration drift stays small over long periods.
Calibrate bias, track elapsed integration time, and reset or correct with references.
Accelerometer
Gravity magnitude check, vibration level, clipping flags, and mounting orientation.
Treating all acceleration as gravity.
Gate correction during strong linear acceleration or high vibration.
Clock
Actual sample interval, missed samples, timestamp source, and filter update rate.
Using a nominal dt when the loop is jittery.
Use measured dt and publish stale or skipped updates.

Overview Knowledge Check

20.3 Tune Alpha by Motion and Rate

The common one-axis complementary update predicts attitude from the gyroscope, then blends that prediction with the accelerometer-derived attitude. The same idea can be applied to roll and pitch separately, or implemented in quaternion form for a full orientation pipeline.

The alpha value is not a universal constant. It should be chosen from the update period, expected vibration, allowed drift, and how often the accelerometer is a valid gravity reference. A higher alpha makes the output smoother during vibration but slower to correct gyro drift. A lower alpha corrects drift faster but can inject acceleration and vibration into the attitude estimate.

Keep raw and calibrated IMU traces separate during review. A stationary calibrated gyroscope should sit near zero angular rate, while the calibrated accelerometer should show two axes near 0 g and the gravity-facing axis near +1 g or -1 g depending on mounting. Magnetometer channels should be stable in the local field but still need hard-iron and soft-iron checks before they are trusted for heading.

Gyroscope angle is obtained by integrating angular rate, commonly with a rectangle or trapezoidal numerical rule. That integration also accumulates bias and white noise: a class trace can show tens of degrees of apparent angle drift over about 30 seconds even though the gyroscope itself is unaffected by earth gravity. Accelerometer tilt estimates avoid long-term drift but are noisy and sluggish when filtered, so they are best treated as roll and pitch correction evidence rather than a complete attitude solution.

Common accelerometer tilt estimates
pitch = atan2(-ax, sqrt(ay^2 + az^2))
roll  = atan2( ay, az )

Axis signs vary by board and mounting. Record the coordinate frame,
unit conversion, and body transform before comparing values across devices.
Worked example: one roll update at 100 Hz
previous roll estimate: 8.00 deg
gyro roll rate: 12.0 deg/s
sample interval dt: 0.01 s
accelerometer roll estimate: 6.00 deg
alpha: 0.98

gyro prediction:
roll_gyro = 8.00 + 12.0 * 0.01 = 8.12 deg

complementary update:
roll_new = alpha * roll_gyro + (1 - alpha) * roll_accel
roll_new = 0.98 * 8.12 + 0.02 * 6.00
roll_new = 7.9576 + 0.1200
roll_new = 8.0776 deg

Interpretation:
The estimate follows the gyro's fast motion but is nudged 0.0424 deg toward
the accelerometer gravity estimate during this 10 ms update.
Condition
Alpha Direction
Reason
Validation Check
High vibration
Increase alpha or gate correction.
Accelerometer samples include vibration and may not represent only gravity.
Compare attitude noise during motor-on and motor-off tests.
Visible drift
Decrease alpha after checking gyro bias.
The gravity correction is too slow for the observed bias and update rate.
Run stationary drift tests over the expected operating temperature range.
Loop jitter
Use measured dt before retuning alpha.
A wrong sample interval corrupts the gyro prediction term.
Log dt distribution and skipped samples under CPU load.
Fast linear motion
Hold or reduce accelerometer correction temporarily.
The accelerometer includes non-gravity acceleration during maneuvers.
Gate correction when acceleration magnitude is far from 1 g.
Correction time-scale example
sample interval dt: 0.01 s
alpha: 0.98

approximate time constant:
tau = dt / (1 - alpha)
tau = 0.01 / 0.02 = 0.50 s

If gyro integration starts 5.0 deg away from the gravity reference:
after 0.50 s, remaining error is about 5.0 * exp(-1) = 1.84 deg
after 1.00 s, remaining error is about 5.0 * exp(-2) = 0.68 deg
after 2.50 s, remaining error is about 5.0 * exp(-5) = 0.03 deg

Interpretation:
At 100 Hz and alpha 0.98, drift correction is visible within seconds,
but each individual update still heavily favors the gyro prediction.

Practitioner Knowledge Check

20.4 Validity Gates Beat Formula

The formula is simple, but production IMU fusion is mostly about knowing when the assumptions are valid. The accelerometer should correct roll and pitch only when gravity dominates the measurement. Gyroscope integration should be trusted only when bias, saturation, timestamp, and axis calibration are under control. The output should expose those checks instead of publishing a single attitude value with no evidence.

For three-dimensional orientation, many systems move from Euler-angle roll/pitch updates to quaternion-based filters such as Madgwick or Mahony. Quaternions avoid Euler singularities and support full 3D attitude composition. Madgwick-style filters use a correction gain, often called beta, to pull the quaternion estimate toward accelerometer and magnetometer references. The same evidence rule still applies: magnetometers can be corrupted by nearby metal or electronics, and a 9-DOF heading should be labeled degraded when magnetic calibration or field consistency fails.

Gravity Gate

Check whether acceleration magnitude and stability are compatible with gravity before applying strong correction.

Axis Convention

Record coordinate frame, sign convention, sensor mounting, and unit conversion so roll, pitch, and yaw are reviewable.

Quaternion Path

Use quaternion filters when full 3D attitude, continuous rotations, or gimbal-lock avoidance matter.

Degraded Output

Publish stale, saturated, high-vibration, magnetic-interference, and yaw-unobservable labels with the attitude estimate.

Failure Mode
Symptom
Likely Cause
Mitigation
Tilt error in motion
Roll or pitch jumps during acceleration, braking, or vibration.
Accelerometer correction treated non-gravity acceleration as gravity.
Gate correction with acceleration magnitude and vibration checks.
Slow drift
Attitude gradually walks away during stationary tests.
Gyro bias, temperature shift, or alpha correction too slow.
Calibrate bias, log temperature, and retune with stationary evidence.
Yaw drift
Heading changes while roll and pitch remain stable.
6-DOF IMU has no absolute yaw reference.
Add a validated magnetometer or external heading reference and label heading quality.
Frame mismatch
Correct motions appear inverted or swapped between axes.
Wrong mounting matrix, sign convention, or units.
Run known-orientation tests and store the axis transform with the filter config.
Review checklist for an IMU fusion output
state:
roll, pitch, yaw or quaternion
timing:
measured dt, update rate, stale-sample flag
configuration:
alpha or beta, coordinate frame, axis transform, units
calibration:
gyro bias, accelerometer scale/offset, magnetometer calibration if used
validity:
acceleration magnitude gate, saturation flag, vibration label
degraded modes:
yaw-unobservable, magnetic interference, stale data, clipped sensor, fallback state

Interpretation:
The attitude value alone is not enough for downstream control, alerting, or
review. The filter should publish the evidence needed to decide whether the
orientation estimate is suitable for the current action.

Under-the-Hood Knowledge Check

20.5 Summary

Complementary filters fuse gyroscope and accelerometer evidence by splitting trust across time scales. The gyro prediction carries fast motion, while a small accelerometer gravity correction limits roll and pitch drift when the accelerometer is valid. Practical IMU fusion depends on measured dt, calibrated axes, alpha or beta tuning, gravity gates, saturation checks, vibration labels, and honest yaw-quality reporting. Quaternion filters such as Madgwick or Mahony extend the same evidence discipline to full 3D attitude.

Key Takeaway

A complementary IMU filter is reliable only when the attitude estimate is published with timing, calibration, axis, tuning, validity-gate, and degraded-mode evidence.

20.6 See Also

Kalman Filters

Compare fixed-blend correction with covariance-based state and measurement updates.

Particle Filters

Contrast lightweight IMU fusion with sampling-based tracking for nonlinear or multimodal states.

Fusion Best Practices

Use calibration, timestamp alignment, gates, and degraded labels around sensor-fusion outputs.

Fusion Applications

Place IMU attitude fusion inside robotics, wearables, mobile sensing, and motion-control workflows.