Chapters

49 Complementary Filters: Tuning and Validity

analytics-ml
data
fusion
complementary

49.1 Start With the Decision

One alpha value cannot fit every update rate and motion state. Tuning must follow time, vibration, and valid gravity evidence.

49.2 Route Overview

This is part 2 of 2. Review Complementary Filters: Sensor Trust for the preceding evidence.

49.3 Learning Objectives

  • Calculate alpha from sample time and filter response.
  • Add validity gates for motion, saturation, and bad samples.

49.4 Chapter Roadmap

  • Kalman state-space bridge
  • Validity Gates Beat Formula
  • Summary
  • Key Takeaway
  • See Also

49.5 Kalman state-space bridge

49.5.1 Kalman state-space bridge

The complementary filter uses a fixed blend. A Kalman filter makes the same predict-and-correct story explicit as a state model with uncertainty. Define a state vector xk\mathbf{x}_k containing the physical quantities to estimate at sample kk, a control input uk\mathbf{u}_k, and a measurement zk\mathbf{z}_k:

xk=Akxk1+Bkuk+wk,wkN(0,Qk),\mathbf{x}_k=\mathbf{A}_k\mathbf{x}_{k-1} +\mathbf{B}_k\mathbf{u}_k+\mathbf{w}_k, \qquad \mathbf{w}_k\sim\mathcal{N}(\mathbf{0},\mathbf{Q}_k), zk=Hkxk+vk,vkN(0,Rk).\mathbf{z}_k=\mathbf{H}_k\mathbf{x}_k+\mathbf{v}_k, \qquad \mathbf{v}_k\sim\mathcal{N}(\mathbf{0},\mathbf{R}_k).

A\mathbf{A} advances the old state through the physical model, B\mathbf{B} maps a measured or commanded input into that state, and H\mathbf{H} selects the combination the sensor can observe. The process disturbance w\mathbf{w} covers model error; the measurement disturbance v\mathbf{v} covers sensor error. Their covariance matrices Q\mathbf{Q} and R\mathbf{R} describe expected variance and cross-correlation, not arbitrary “trust knobs.”

For one IMU tilt axis, a useful state estimates angle θ\theta and gyroscope bias bb while the measured gyro rate ωm\omega_m acts as the input:

xk=[θkbk],A=[1Δt01],B=[Δt0],uk=[ωm,k].\mathbf{x}_k= \begin{bmatrix}\theta_k\\b_k\end{bmatrix}, \quad \mathbf{A}= \begin{bmatrix}1&-\Delta t\\0&1\end{bmatrix}, \quad \mathbf{B}= \begin{bmatrix}\Delta t\\0\end{bmatrix}, \quad \mathbf{u}_k=\begin{bmatrix}\omega_{m,k}\end{bmatrix}.

The first row says θkθk1+Δt(ωm,kbk1)\theta_k\approx\theta_{k-1}+\Delta t(\omega_{m,k}-b_{k-1}); the second models bias as slowly varying. When the accelerometer supplies a roll or pitch observation zk=θacc,kz_k=\theta_{acc,k},

H=[10],\mathbf{H}=\begin{bmatrix}1&0\end{bmatrix},

because the measurement directly observes angle, not gyro bias. With Δt=0.01\Delta t=0.01 s, previous state [10.0,0.2/s]T[10.0^\circ,0.2^\circ/\text{s}]^T, and measured rate 5.0/s5.0^\circ/\text{s}, the prediction is 10.0+0.01(5.00.2)=10.04810.0+0.01(5.0-0.2)=10.048^\circ. The measurement update decides how far to move from that prediction only after comparing the predicted covariance with accelerometer noise.

The complete recursion is:

x^k=Ax^k1+Buk,Pk=APk1AT+Q,\hat{\mathbf{x}}^-_k=\mathbf{A}\hat{\mathbf{x}}_{k-1}+\mathbf{B}\mathbf{u}_k, \qquad \mathbf{P}^-_k=\mathbf{A}\mathbf{P}_{k-1}\mathbf{A}^T+\mathbf{Q}, yk=zkHx^k,Sk=HPkHT+R,\mathbf{y}_k=\mathbf{z}_k-\mathbf{H}\hat{\mathbf{x}}^-_k, \qquad \mathbf{S}_k=\mathbf{H}\mathbf{P}^-_k\mathbf{H}^T+\mathbf{R}, Kk=PkHTSk1,\mathbf{K}_k=\mathbf{P}^-_k\mathbf{H}^T\mathbf{S}_k^{-1}, x^k=x^k+Kkyk,Pk=(IKkH)Pk.\hat{\mathbf{x}}_k=\hat{\mathbf{x}}^-_k+\mathbf{K}_k\mathbf{y}_k, \qquad \mathbf{P}_k=(\mathbf{I}-\mathbf{K}_k\mathbf{H})\mathbf{P}^-_k.

Read it step by step: predict the state, predict its uncertainty, form the measurement residual, predict the residual variance, calculate the Kalman gain, correct the state, then reduce the covariance in the observed direction. If accelerometer variance RR rises during vibration, the residual variance grows and the gain normally gives that angle less influence. If process covariance QQ is too small, the filter becomes overconfident in an imperfect motion/bias model and responds sluggishly to real change.

Matrix or recordIMU meaningEvidence used to set it
A,B\mathbf{A},\mathbf{B}Sample-period motion and bias modelTimestamped update rate and chosen physical state
H\mathbf{H}Which state combination the accelerometer angle observesAxis convention and angle derivation
Q\mathbf{Q}Gyro integration/model and bias random-walk uncertaintyStationary and temperature-varying gyro data
R\mathbf{R}Accelerometer-angle measurement uncertaintyStatic orientation, vibration, and linear-acceleration tests
P0\mathbf{P}_0Initial uncertainty in angle and biasStartup alignment and calibration procedure

49.5.2 IMU Kalman matrices and tilt-compensated yaw

The complete estimator is easier to review when matrices and axis observability remain on the data path. Figure 49.1 keeps gyro and accelerometer roll/pitch correction separate from magnetometer tilt compensation for yaw.

Block diagram: gyro enters a Kalman predict block with A and Q; accelerometer enters a correct block with H and R; roll and pitch rotate calibrated magnetometer measurements onto the horizontal plane; atan2 publishes yaw with separate health.
Figure 49.1: A calibrated gyro and accelerometer feed explicit Kalman prediction and correction blocks, while a magnetometer is rotated to the horizontal plane for yaw.

In Figure 49.1, PREDICT records A and Q, while CORRECT records H and R instead of hiding uncertainty inside a generic filter box. TILT COMPENSATE rotates m using roll and pitch before the YAW atan2 step, so magnetic disturbance can widen yaw health without falsely invalidating roll and pitch.

Calculate the matrix dimensions and units before writing the loop. In the two-state example, x\mathbf{x} is 2×12\times1, A\mathbf{A} and Q\mathbf{Q} are 2×22\times2, B\mathbf{B} is 2×12\times1, H\mathbf{H} is 1×21\times2, and scalar angle measurement noise may be represented by a 1×11\times1 R\mathbf{R}. The angle-bias off-diagonal entries in P\mathbf{P} matter: a measurement that corrects angle can also improve the inferred bias through that covariance. For numerical robustness, keep P\mathbf{P} symmetric, verify that Q\mathbf{Q} and R\mathbf{R} are positive semidefinite, and use the Joseph covariance update when finite-precision rounding is visible:

Pk=(IKkHk)Pk(IKkHk)T+KkRkKkT.\boxed{\mathbf{P}_k=(\mathbf{I}-\mathbf{K}_k\mathbf{H}_k)\mathbf{P}^-_k(\mathbf{I}-\mathbf{K}_k\mathbf{H}_k)^T+\mathbf{K}_k\mathbf{R}_k\mathbf{K}_k^T.}

Roll and pitch provide the missing geometry for magnetometer heading. First calibrate hard-iron offset and soft-iron scale, then rotate the body-frame magnetic vector (mx,my,mz)(m_x,m_y,m_z) onto the horizontal plane. For one common right-handed roll-ϕ\phi, pitch-θ\theta convention,

mx,h=mxcosθ+mzsinθ,m_{x,h}=m_x\cos\theta+m_z\sin\theta, my,h=mxsinϕsinθ+mycosϕmzsinϕcosθ,m_{y,h}=m_x\sin\phi\sin\theta+m_y\cos\phi-m_z\sin\phi\cos\theta, ψ=atan2(my,h,mx,h).\psi=\operatorname{atan2}(-m_{y,h},m_{x,h}).

The signs and axis order change with ENU/NED coordinates and sensor mounting, so prove the implementation with known north/east headings and positive roll/pitch rotations rather than copying the equations without a frame definition. Tilt compensation removes the geometric projection error; it does not remove magnetic distortion, gyro drift during magnetic rejection, or the need to apply local magnetic declination when the product requires true rather than magnetic north.

49.6 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.

What “gravity dominates” means in practice is a decision the firmware must take dozens of times per second. Figure 49.2 replays twelve seconds from a delivery robot to show the two ways the accelerometer earns a time-out.

Two aligned charts over twelve seconds. Accelerometer magnitude stays near 1.0 g inside a shaded 0.9 to 1.1 g gate band except during a vibration burst around seconds three to five and a hard-braking ramp to about 1.45 g near second nine. The accelerometer-derived roll below shows a steady five degrees while calm, wild plus or minus sixteen degree spikes during vibration, and a smooth false swing to minus twenty-four degrees during braking while true roll never changes. A rule card applies the correction only inside the gate band, otherwise holding the gyro and labelling the output as coasting.
Figure 49.2: Twelve seconds on a delivery robot: vibration and braking both push the accelerometer outside its gate, and the derived angle turns confidently wrong.

Hold the two panels of Figure 49.2 against each other, window by window. While |a| stays inside the gate band 0.9–1.1 g, the derived roll hugs the true 5°. The vibration window throws fast spikes that honest averaging could partially tame; the braking window is the treacherous one — the magnitude climbs smoothly to 1.45 g and the derived roll swings smoothly to −24°, a clean-looking, confidently wrong angle, because atan2 read the brake’s force as gravity’s. The green card turns the diagnosis into firmware: apply the correction only inside the band, otherwise hold the gyro prediction and publish a coasting label — plus a timer, because every second spent coasting is a second of unpaid gyro drift accumulating from the linked figure in Part 1.

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

49.7 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.

49.8 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.

49.9 Continue Your Route

This final part closes the route from Kalman state-space bridge through See Also. Return to Complementary Filters: Sensor Trust or continue from the analytics-ml module index.