22 Complementary Filters and IMU Fusion
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.
For Beginners: Complementary Sensor 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:
| Sensor | Strength | Weakness | Time Domain |
|---|---|---|---|
| Gyroscope | Smooth, fast response | Drifts over time | Short-term OK, Long-term bad |
| Accelerometer | No drift, absolute gravity reference | Noisy, affected by motion | Short-term bad, Long-term OK |
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{fused}} = \alpha \cdot (\theta_{\text{prev}} + \omega \cdot \Delta t) + (1-\alpha) \cdot \theta_{\text{accel}}\]
Where:
- \(\alpha\) = 0.98 (typical, “trust” parameter)
- \(\omega\): Gyroscope angular velocity
- \(\Delta t\): Time step
- \(\theta_{\text{accel}}\): Orientation from accelerometer
How it works:
- 98% weight to gyroscope (alpha = 0.98): Preserves fast dynamics
- 2% weight to accelerometer (1-alpha = 0.02): Slowly corrects drift
- 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
Putting Numbers to It
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
| Alpha Value | Behavior | Use Case |
|---|---|---|
| 0.95 | Fast drift correction, more noise | High-vibration environments |
| 0.98 | Balanced (most common) | General-purpose IMU orientation |
| 0.99 | Slow drift correction, very smooth | Low-vibration, slow motion |
Time constant formula: \(\tau = \frac{\Delta t}{1-\alpha}\)
Tradeoff: Kalman Filter vs Complementary Filter
| Kalman Filter | Complementary Filter | |
|---|---|---|
| Approach | Optimal state estimation with covariance tracking | Simple weighted combination with tuned alpha |
| Computation | ~500 FLOPS, 200+ bytes RAM | ~10 FLOPS, 12 bytes RAM |
| Accuracy | Optimal (for linear/Gaussian systems) | ~90% of Kalman accuracy |
| Tuning | Requires noise models (Q, R matrices) | Single parameter (alpha) |
| Adaptivity | Adapts gain based on uncertainty | 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 10ms):
- Gyroscope: wx, wy, wz (degrees/second)
- Accelerometer: Ax, Ay, Az (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 gyroscope (trapezoidal):
roll_gyro = roll_prev + (wx_prev + wx)/2 * 0.01
pitch_gyro = pitch_prev + (wy_prev + wy)/2 * 0.01
4. Complementary fusion (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 to PID controller for motor corrections
Result: +/-1 deg orientation accuracy even with:
- Propeller vibrations (200 Hz accelerometer noise)
- Wind gusts (rapid gyroscope changes)
- 30+ minutes of flight (no 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:
| Application | Role of IMU Fusion | Required Accuracy |
|---|---|---|
| Drone Stabilization | Maintains level flight | +/-1 deg, 100+ Hz |
| Wearable Posture | Detects slouching, falls | +/-5 deg, 50 Hz |
| AR/VR Head Tracking | Natural viewport control | +/-0.5 deg, 200+ Hz |
| Robotics Navigation | Self-balancing robots | +/-2 deg, 100 Hz |
| Gesture Recognition | Smart home controllers | +/-10 deg, 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:
- Accel corrects pitch/roll drift
- Magnetometer corrects yaw drift
- 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
| Time | Accumulated Drift |
|---|---|
| 1 second | 0.5 deg |
| 10 seconds | 5.0 deg |
| 1 minute | 30.0 deg |
| 10 minutes (typical flight) | 300 deg (unusable) |
Without the accelerometer correction, the drone would lose attitude reference within seconds.
Step 2: Evaluate alpha values
| Alpha | Time Constant (tau = dt/(1-alpha)) | Drift at 10 min | Vibration Rejection | Assessment |
|---|---|---|---|---|
| 0.95 | 20 ms | 0.01 deg | Poor – 200 Hz vibration passes through | Too much accel trust |
| 0.98 | 50 ms | 0.025 deg | Good – attenuates 200 Hz by 40 dB | Standard choice |
| 0.995 | 200 ms | 0.1 deg | Excellent – attenuates 200 Hz by 52 dB | Better for high vibration |
| 0.999 | 1000 ms | 0.5 deg | Maximum – attenuates 200 Hz by 60 dB | 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
1. Using a single alpha value across all motion conditions
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).
2. Initialising the filter without a stationary calibration phase
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.
3. Ignoring magnetic disturbances when using magnetometer for heading
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
For Kids: Meet the Sensor Squad!
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 |
See Also
Advanced Fusion:
- Kalman Filters - When to upgrade from complementary
- Madgwick Filter Papers - Quaternion-based fusion
- Particle Filters - Non-linear alternatives
Applications:
- Drone Stabilization - Flight control with IMU
- AR/VR Tracking - Head tracking systems
- Wearable Devices - Activity and posture monitoring
Implementation:
- Edge Compute Patterns - Running fusion on MCUs
- Real-Time Processing - Low-latency fusion pipelines
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
| If you want to… | Read this |
|---|---|
| Upgrade to a Kalman filter for optimal fusion | Kalman Filter for IoT |
| Explore particle filters for non-linear problems | Particle Filters |
| See this technique applied in navigation and robotics | Data Fusion Applications |
| Understand fusion architecture context | Data Fusion Architectures |
| Return to the module overview | Data Fusion Introduction |