22  Complementary Filters and IMU Fusion

In 60 Seconds

Complementary filters combine gyroscope data (accurate short-term but drifts) with accelerometer data (noisy short-term but stable long-term) to produce drift-free orientation estimates. With a single tuning parameter (alpha, typically 0.98), they run on even the smallest microcontrollers and achieve roughly 90% of Kalman filter accuracy at a fraction of the computational cost.

Learning Objectives

After completing this chapter, you will be able to:

  • Explain complementary filter principles
  • Implement IMU sensor fusion for 3D orientation
  • Apply Madgwick filter for quaternion-based orientation
  • Choose between Kalman and complementary filters
  • Design practical IMU fusion for drones and wearables

Key Concepts

  • Complementary filter: A sensor fusion technique that combines the high-frequency response of a gyroscope with the low-frequency accuracy of an accelerometer using a simple weighted blend, achieving stable orientation estimation without the complexity of a Kalman filter.
  • Gyroscope drift: The gradual accumulation of error in gyroscope-integrated orientation over time due to sensor noise and temperature sensitivity; corrected by reference sensors (accelerometer, magnetometer) in fusion.
  • Accelerometer tilt estimation: Computing roll and pitch angles from accelerometer gravity measurements when the device is stationary or moving slowly; accurate over time but noisy during dynamic motion.
  • IMU (Inertial Measurement Unit): A device combining accelerometers and gyroscopes (and optionally magnetometers) to measure linear acceleration, angular velocity, and magnetic heading.
  • Filter coefficient (alpha): The weighting factor in a complementary filter controlling the balance between gyroscope data (high alpha) and accelerometer correction (low alpha); higher alpha gives smoother but slower-correcting orientation.
  • Quaternion: A four-component mathematical representation of 3D orientation that avoids the gimbal lock singularity of Euler angles; preferred for continuous rotation tracking in IMU fusion.

Complementary sensor fusion combines sensors that each excel at different things. Think of using both your eyes and ears to cross a street – your eyes judge distance while your ears detect approaching cars. Similarly, an accelerometer measures quick movements while a gyroscope tracks rotation. Together they provide accurate motion tracking that neither could achieve alone.

22.1 Complementary Filter Principle

Complementary filters combine high-frequency data from one sensor with low-frequency data from another. Inertial Measurement Units (IMUs) – ubiquitous in drones, wearables, robotics, and AR/VR – are the most common application.

22.1.1 Why Fusion Is Needed

Neither accelerometer nor gyroscope alone provides accurate orientation tracking:

  • Gyroscope: Smooth, fast response. Excellent in the short term, but it drifts over time.
  • Accelerometer: No drift and an absolute gravity reference. Reliable in the long term, but noisy and affected by motion in the short term.

The key insight is that these sensors have complementary error characteristics: gyroscope errors accumulate (integration drift) but are smooth, while accelerometer errors fluctuate (noise) but do not accumulate. By applying a high-pass filter to gyroscope data (keeps fast changes) and a low-pass filter to accelerometer data (keeps slow trends), we get the best of both worlds.

22.1.2 The Complementary Filter Equation

\[\theta_{\text{gyro}} = \theta_{\text{prev}} + \omega \cdot \Delta t\]

\[\theta_{\text{fused}} = \alpha \cdot \theta_{\text{gyro}} + (1-\alpha) \cdot \theta_{\text{accel}}\]

Where:

  • \(\alpha\) = 0.98 (typical, “trust” parameter)
  • \(\theta_{\text{gyro}}\): Gyroscope prediction before correction
  • \(\omega\): Gyroscope angular velocity
  • \(\Delta t\): Time step
  • \(\theta_{\text{accel}}\): Orientation from accelerometer

How it works:

  1. 98% weight to gyroscope (alpha = 0.98): Preserves fast dynamics
  2. 2% weight to accelerometer (1-alpha = 0.02): Slowly corrects drift
  3. Drift correction time constant: \(\tau = \Delta t/(1-\alpha) = 0.5\) seconds (for alpha=0.98, dt=0.01)

Intuition: Trust the gyroscope for rapid changes (it is responsive), but continuously “nudge” it back toward the accelerometer’s gravity reference.

Understanding Sensor Complementarity in Time Domain

Core Concept: Sensors are complementary when their error characteristics occupy different frequency bands. The accelerometer measures gravity (constant, absolute reference) plus linear acceleration (noise during motion). It provides accurate orientation when stationary but becomes unreliable during movement. The gyroscope measures rotation rate, which must be integrated to get orientation. Integration accumulates small errors (bias, noise) into unbounded drift.

Key Takeaway: Before designing a fusion system, analyze each sensor’s error characteristics across frequency. Ask: “What time scales does each sensor excel at?”

Understanding Sensor Drift

Core Concept: Sensor drift is the gradual change in a sensor’s output over time even when the measured quantity remains constant - caused by component aging, temperature variations, mechanical stress, and environmental contamination.

Why It Matters: An accelerometer bias of 0.01 m/s\(^2\) accumulates to 18 meters position error after just one minute of dead reckoning. Drift is invisible in short tests but catastrophic in deployed systems.

Key Takeaway: Assume all sensors drift. Implement periodic calibration against known references. Use complementary sensors where possible - GPS corrects IMU drift, while IMU fills gaps between GPS updates.

22.1.3 Gyroscope Drift Explained

Gyroscopes measure angular velocity (degrees per second), not orientation directly. To get orientation, we must integrate over time:

\[\theta(t) = \theta_0 + \int_0^t \omega(\tau) \, d\tau\]

The Problem: Even tiny sensor bias accumulates relentlessly:

  • Gyroscope bias: 0.01 deg/s (typical for MEMS gyros)
  • After 30 seconds: 0.01 x 30 = 0.3 deg minimum drift
  • Real-world noise: Often 50+ deg drift in 30 seconds

22.1.4 Accelerometer Angles

Accelerometers measure the gravity vector (when at rest), providing an absolute reference for roll (\(\phi\), tilt left/right) and pitch (\(\theta\), nose up/down), but not yaw (\(\psi\), compass heading):

\[\text{Roll} = \arctan2(A_y, A_z)\]

\[\text{Pitch} = \arctan2(-A_x, \sqrt{A_y^2 + A_z^2})\]

Advantages:

  • No drift: Gravity direction is constant
  • Absolute reference: Not relative measurements

Limitations:

  • Noise: Vibrations cause high-frequency fluctuations
  • Motion interference: Linear acceleration adds to gravity vector
  • No yaw information: Gravity is vertical - can’t determine heading

Consider a drone IMU running at 100 Hz (dt = 0.01s) with alpha = 0.98. How long does drift correction take?

Time constant \(\tau = \frac{\Delta t}{1-\alpha} = \frac{0.01}{0.02} = 0.5\) seconds

After one time constant, 63% of drift is corrected. After 5τ (2.5 seconds), 99% corrected.

If gyroscope drifts 5° due to bias: - After 0.5s: Drift reduced to 5° × 0.37 = 1.85° - After 1.0s: Drift reduced to 5° × 0.14 = 0.7° - After 2.5s: Drift reduced to 5° × 0.01 = 0.05°

Convergence rate scales inversely with alpha: Higher alpha (0.995) gives slower correction (τ = 2.0s) but better vibration rejection. Lower alpha (0.95) gives faster correction (τ = 200ms) but passes more accelerometer noise.

22.2 Filter Parameter Tuning

  • 0.95: Fast drift correction with more noise. Best for high-vibration environments.
  • 0.98: Balanced and most common. Best for general-purpose IMU orientation.
  • 0.99: Slow drift correction with very smooth output. Best for low-vibration, slow-motion systems.

Time constant formula: \(\tau = \frac{\Delta t}{1-\alpha}\)

Complementary Filter Calculator

Adjust alpha and the sample rate to see how the filter behaves. The time constant tells you how quickly drift is corrected; the decay table shows how a 5-degree drift error diminishes over time.

Tradeoff: Kalman Filter vs Complementary Filter
  • Approach: Kalman filter uses optimal state estimation with covariance tracking. Complementary filter uses a simple weighted combination with tuned alpha.
  • Computation: Kalman filter needs about 500 FLOPS and 200+ bytes of RAM. Complementary filter needs about 10 FLOPS and 12 bytes.
  • Accuracy: Kalman filter is optimal for linear Gaussian systems. Complementary filter achieves about 90% of that accuracy.
  • Tuning: Kalman filter requires noise models (Q and R matrices). Complementary filter needs only one parameter (alpha).
  • Adaptivity: Kalman filter adapts its gain based on uncertainty. Complementary filter keeps a fixed weighting.

Choose Kalman for GPS/IMU fusion where accuracy matters and you have accurate noise models.

Choose complementary filters for IMU orientation on resource-constrained MCUs (runs on 8-bit AVR) where simplicity and reliability beat optimality.

When to upgrade: Use Extended Kalman Filter or Madgwick filter when you add a magnetometer (9-DOF) or need optimal sensor fusion with different update rates.

22.3 Real-World Implementation

Drone IMU Fusion Pipeline (100 Hz update rate):

  1. Read sensors every 10 ms: gyroscope wx, wy, wz in degrees/second and accelerometer Ax, Ay, Az in g’s.
  2. Calculate accelerometer angles:
    • roll_accel = atan2(Ay, Az) * 180/pi
    • pitch_accel = atan2(-Ax, sqrt(Ay^2 + Az^2)) * 180/pi
  3. Integrate the gyroscope using a trapezoidal step:
    • roll_gyro = roll_prev + (wx_prev + wx)/2 * 0.01
    • pitch_gyro = pitch_prev + (wy_prev + wy)/2 * 0.01
  4. Fuse the estimates with alpha = 0.98:
    • roll_fused = 0.98 * roll_gyro + 0.02 * roll_accel
    • pitch_fused = 0.98 * pitch_gyro + 0.02 * pitch_accel
  5. Send the fused orientation to the PID controller for motor corrections.

Result: +/-1 deg orientation accuracy even with propeller vibrations (200 Hz accelerometer noise), wind gusts (rapid gyroscope changes), and 30+ minutes of flight without gyroscope drift.

Performance metrics:

  • Without fusion: +/-10 deg oscillations (accel noise) OR 5 deg/minute drift (gyro only)
  • With fusion: +/-1 deg stable orientation, no drift, smooth response

22.4 Why This Matters for IoT

IMU sensor fusion is critical for numerous IoT domains:

  • Drone stabilization: Maintains level flight. Typical requirement is about +/-1 deg at 100+ Hz.
  • Wearable posture sensing: Detects slouching and falls. Typical requirement is about +/-5 deg at 50 Hz.
  • AR/VR head tracking: Keeps viewport motion natural. Typical requirement is about +/-0.5 deg at 200+ Hz.
  • Robotics navigation: Supports self-balancing robots. Typical requirement is about +/-2 deg at 100 Hz.
  • Gesture recognition: Enables smart-home controllers. Typical requirement is about +/-10 deg at 30 Hz.

22.5 Madgwick Filter (Quaternion-Based IMU Fusion)

The Madgwick filter is an efficient orientation filter for 9-DOF IMU data using quaternions to avoid gimbal lock.

Why Quaternions?

Advantages over Euler angles:

  • No gimbal lock: Euler angles fail at pitch=+/-90 deg, quaternions work for any orientation
  • Computational efficiency: 16 multiplies vs 27 for rotation matrices
  • Smooth interpolation: Natural rotation paths with SLERP
  • Compact: 4 values [w,x,y,z] vs 9 (rotation matrix)

Trade-off: Less intuitive for humans - convert to Euler angles for display.

Beta parameter: Typical values 0.01-0.1, controls accelerometer correction strength.

22.5.1 9-DOF IMU: Adding the Magnetometer

6-DOF (accel+gyro) can estimate roll/pitch from gravity but yaw (compass heading) is unobservable. Gyroscope integrates yaw but drifts without reference.

Magnetometer measures Earth’s magnetic field (~0.5 gauss, pointing north with dip angle). It provides absolute yaw reference like accelerometer provides pitch/roll reference.

Fusion strategy:

  1. Accel corrects pitch/roll drift
  2. Magnetometer corrects yaw drift
  3. Gyro provides high-frequency updates

Challenges: Magnetic interference from electronics, metal structures requires calibration.

22.5.2 Worked Example: DJI Matrice 300 RTK Drone Stabilization Tuning

Scenario: A surveying company in Queensland, Australia deploys DJI Matrice 300 RTK drones for photogrammetric mapping of open-pit mines. The onboard IMU uses a complementary filter for real-time attitude estimation. The operations team needs to tune the filter’s alpha parameter for optimal performance in high-vibration mining environments.

Given:

  • IMU: ICM-42688-P 6-axis (accel + gyro), 8 kHz sampling
  • Gyroscope bias: 0.5 deg/s (MEMS-grade)
  • Propeller vibration: dominant at 200 Hz, amplitude 0.3g
  • Wind gust frequency: up to 2 Hz gusts in open pit
  • Required attitude accuracy: less than 1 degree for survey-grade mapping
  • Update rate to flight controller: 1 kHz (every 1 ms)

Step 1: Calculate gyroscope drift without correction

  • 1 second: 0.5 deg
  • 10 seconds: 5.0 deg
  • 1 minute: 30.0 deg
  • 10 minutes (typical flight): 300 deg, which is unusable

Without the accelerometer correction, the drone would lose attitude reference within seconds.

Step 2: Evaluate alpha values

  • Alpha 0.95: Time constant 20 ms, 0.01 deg drift at 10 minutes, poor vibration rejection because 200 Hz vibration passes through, and too much accelerometer trust.
  • Alpha 0.98: Time constant 50 ms, 0.025 deg drift at 10 minutes, good vibration rejection with about 40 dB attenuation at 200 Hz, and a solid standard choice.
  • Alpha 0.995: Time constant 200 ms, 0.1 deg drift at 10 minutes, excellent vibration rejection with about 52 dB attenuation at 200 Hz, and better performance in high-vibration conditions.
  • Alpha 0.999: Time constant 1000 ms, 0.5 deg drift at 10 minutes, maximum vibration rejection with about 60 dB attenuation at 200 Hz, but too slow for wind response.

Step 3: Select optimal alpha for mining environment

The mining environment has both high propeller vibration (favouring higher alpha) and sudden wind gusts (favouring lower alpha for faster correction). The solution:

  • Alpha = 0.995 for pitch and roll (vibration rejection is critical for mapping accuracy)
  • Verify: At alpha = 0.995, the accelerometer correction time constant is 200 ms, meaning a 2 Hz wind gust is fully corrected within one gust cycle
  • Drift check: 0.1 deg drift over 10 minutes is well within the 1 degree requirement

Result: Setting alpha = 0.995 (instead of the default 0.98) reduced vibration-induced attitude noise from 0.15 deg RMS to 0.04 deg RMS in flight tests, improving photogrammetric map accuracy from 5 cm to 2 cm ground sample distance. The tuning required zero hardware changes – only a firmware parameter update.

Key Insight: The optimal alpha depends on the ratio between vibration frequency and drift rate. When vibration is high-frequency (200 Hz propellers) and the signal of interest is low-frequency (2 Hz wind gusts), there is a wide separation band where increasing alpha improves vibration rejection without meaningfully degrading drift correction. The “default 0.98” is a safe general choice, but application-specific tuning can yield 4x improvement in noise performance.

Common Pitfalls

A complementary filter alpha that works well for slow, smooth motion will exhibit excessive gyroscope drift during fast, jerky motion (and vice versa). Use an adaptive alpha that increases during slow motion (more accelerometer weight) and decreases during dynamic motion (more gyroscope weight).

Initialising the complementary filter from the first available accelerometer reading during dynamic motion produces a poor initial estimate that takes many seconds to converge. Always require a 1–2 second stationary calibration phase before trusting filter outputs.

A magnetometer-based heading complementary filter will fail near ferromagnetic materials (metal structures, motors, rebar). Detect magnetic anomalies using the magnitude check |B| ≈ local field strength and exclude magnetometer updates when disturbance is detected.

22.6 Summary

Complementary filters and IMU fusion provide efficient orientation estimation:

  • Complementary filters: Simple, efficient fusion of complementary sensor characteristics
  • Alpha parameter: Balances noise rejection vs drift correction speed
  • IMU fusion: Gyroscope for fast response, accelerometer for drift correction
  • Madgwick filter: Quaternion-based for 9-DOF IMU, avoids gimbal lock
  • Application-dependent: Choose based on accuracy needs vs computational constraints

Complementary filters are like two friends who are each good at different things teaming up to be amazing together!

22.6.1 The Sensor Squad Adventure: The Balancing Act

Bella the Battery was watching the school talent show when Sammy the Sensor came on stage to perform a BALANCING ACT on a big ball!

“I need two helpers!” called Sammy. “Gyro Greg and Accel Annie!”

Gyro Greg had AMAZING reflexes. Every time the ball wobbled, Greg shouted, “You just tilted 2 degrees left!” He was super fast and smooth. But after a few minutes, Greg started getting confused. “Umm… I think you are now tilted 50 degrees… wait, that cannot be right.” Greg was DRIFTING – his memory of the starting position slowly got worse and worse!

Accel Annie was different. She always knew which way was DOWN because she could feel gravity pulling on her. “You are tilted 3 degrees right!” she said confidently. But every time someone in the audience clapped or stomped, Annie got SHAKY. “3 degrees! No wait, 10! No, 2! No, 15!” She was noisy from all the vibrations!

Max the Microcontroller had an idea: “What if we COMBINE them? We listen to Greg 98% of the time for smooth, fast updates. But we also listen to Annie 2% of the time to keep Greg from drifting off!”

It worked PERFECTLY! Greg kept things smooth and responsive, while Annie gently nudged him back to reality whenever he started to drift. Together, they helped Sammy balance for the entire show!

“That is a complementary filter!” cheered Lila the LED. “Two sensors that are good at DIFFERENT things, working together!”

22.6.2 Key Words for Kids

Word What It Means
Gyroscope A sensor that detects how fast you are spinning or tilting
Accelerometer A sensor that feels the pull of gravity to know which way is down
Drift When a sensor slowly loses track of the correct answer over time
Complementary Two things that fill in each other’s weaknesses
Alpha The “trust dial” that controls how much we listen to each sensor
Concept Relationships

Builds On:

Enables:

Advanced Fusion:

Applications:

Implementation:

Key Takeaway

Complementary filters exploit the fact that gyroscopes and accelerometers have opposite error characteristics across frequency. Use them as the default choice for IMU orientation on resource-constrained devices. For full 3D orientation including heading, add a magnetometer and consider the Madgwick filter. Only upgrade to a Kalman filter when you need optimal estimation with uncertainty tracking.

22.7 What’s Next