Why Sensor Fusion?
No single sensor is perfect. Each has strengths and weaknesses — fusion combines them to get the best estimate. Think of it like a team of experts: the accelerometer is great at detecting gravity but noisy during motion, the gyroscope is clean during rotation but drifts over time, and the magnetometer provides heading but gets confused near metal.
What fusion really buys you is a state estimate whose error does not grow without bound. A gyroscope integrating angle rates accumulates bias error linearly — a 0.1 °/s bias becomes about 6° of attitude error after 100 seconds of flight. An accelerometer gives an absolute gravity reference but only when the vehicle is not accelerating, which is almost never true during aggressive flight. A magnetometer anchors heading absolutely but reads 5° or more of local deviation near steel structures and high-current wiring. Each sensor fails in a different way, and a filter's job is to trust each one only in the conditions where it is actually honest.
The engineering discipline that separates working systems from drifting ones is characterizing your specific sensors before choosing a filter. Noise density from a static bench run, bias instability from a long stationary log, and vibration response from a hover log tell you the numbers to feed the filter — filters do not fix uncharacterized sensors, they just hide the error until the first hard maneuver.
| Sensor | Useful for | Typical error mode | Time behavior |
|---|---|---|---|
| Accelerometer | Gravity direction, vertical accel | Vibration, maneuver acceleration | Absolute but noisy instantaneously |
| Gyroscope | Short-term rate and attitude change | Bias walk, scale factor | Smooth, drifts without bound |
| Magnetometer | Absolute heading | Hard/soft iron, external fields | Absolute but easily disturbed |
| Barometer | Absolute altitude | Wind and prop wash, weather drift | Slow, lagging reference |
| GNSS | Position and velocity | Multipath, outages, lag | Absolute, low rate |
Complementary Filter
The simplest fusion approach. It trusts the gyroscope for fast changes (high-pass) and the accelerometer for slow/steady changes (low-pass).
class ComplementaryFilter:
def __init__(self, alpha=0.96):
self.alpha = alpha
self.angle = 0.0
def update(self, gyro_rate, accel_angle, dt):
"""
gyro_rate: angular velocity from gyroscope (deg/s)
accel_angle: angle calculated from accelerometer (deg)
dt: time step (seconds)
"""
# Predict from gyro (integrate), correct with accel (low-pass)
self.angle = self.alpha * (self.angle + gyro_rate * dt) + \
(1 - self.alpha) * accel_angle
return self.angle
# Demo
filter = ComplementaryFilter(alpha=0.96)
angles = []
for i in range(100):
gyro = 5.0 + np.random.normal(0, 0.5) # 5 deg/s with noise
accel = 45.0 + np.random.normal(0, 2.0) # True angle ~45°
dt = 0.01
angle = filter.update(gyro, accel, dt)
angles.append(angle)
print(f"Final angle: {angles[-1]:.2f}° (target: ~45°)")
Choosing the Complementary Cutoff
The single blend factor in a complementary filter encodes a question: over what time horizon should the accelerometer be allowed to correct gyro drift? At 0.98 the estimate follows the gyro for roughly half a second before the accelerometer pulls it back; at 0.90 the correction lands in about 100 ms but admits more of the vibration noise that accelerometers pick up in hover. The relationship is simple — the effective time constant is dt / (1 − alpha), so at 1 kHz update rate, alpha of 0.98 gives a 50 ms time constant.
Two constraints bound the choice. The filter's lag must stay shorter than the maneuver you care about: aggressive 3D flight produces attitude transients over 100 to 200 ms, so a time constant near 50 ms keeps the estimate inside the real motion while still bleeding off drift. And the accelerometer's noise during aggressive flight can exceed the drift it corrects, which is why production stacks ramp alpha toward 1.0 whenever commanded acceleration or thrust magnitude departs from 1 g — the blend becomes trust, not a constant.
A practical tuning session looks like this: fly a 30-second hover and step maneuver, log accelerometer RMS (this sets the noise floor), then log attitude error against a level reference during and after aggressive rolls. If the level reading recovers too slowly after a snap roll, alpha is too low; if the attitude jitters in hover while the craft sits still, alpha is too high. One constant, two symptoms, no other knobs — that simplicity is exactly why the complementary filter remains the default for small multirotors.
Madgwick Filter
The Madgwick filter is the most popular choice for drone AHRS. It uses gradient descent to minimize the error between predicted and measured orientations.
class MadgwickFilter:
"""Simplified Madgwick AHRS filter."""
def __init__(self, sample_rate=100, beta=0.1):
self.sample_rate = sample_rate
self.beta = beta # Filter gain
self.q = np.array([1.0, 0.0, 0.0, 0.0]) # Quaternion [w, x, y, z]
def update(self, gyro, accel, mag=None, dt=None):
"""
gyro: [gx, gy, gz] in rad/s
accel: [ax, ay, az] normalized
mag: [mx, my, mz] normalized (optional)
"""
if dt is None:
dt = 1.0 / self.sample_rate
q = self.q.copy()
# Normalize accelerometer
norm = np.sqrt(accel[0]**2 + accel[1]**2 + accel[2]**2)
if norm > 0:
ax, ay, az = accel / norm
else:
ax, ay, az = 0, 0, 1
# Gradient descent step
f = np.array([
2*(q[1]*q[3] - q[0]*q[2]) - ax,
2*(q[0]*q[1] + q[2]*q[3]) - ay,
2*(0.5 - q[1]**2 - q[2]**2) - az
])
j = np.array([
[-2*q[2], 2*q[3], -2*q[0], 2*q[1]],
[ 2*q[1], 2*q[0], 2*q[3], 2*q[2]],
[ 0, -4*q[1], -4*q[2], 0]
])
step = j.T @ f
step = step / np.linalg.norm(step) if np.linalg.norm(step) > 0 else step
# Quaternion rate from gyroscope
q_dot = 0.5 * self._quaternion_multiply(q, np.array([0, *gyro])) - self.beta * step
# Integrate
self.q = q + q_dot * dt
self.q = self.q / np.linalg.norm(self.q)
return self.q
def _quaternion_multiply(self, q1, q2):
w = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3]
x = q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2]
y = q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1]
z = q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0]
return np.array([w, x, y, z])
def get_euler(self):
"""Convert quaternion to Euler angles (roll, pitch, yaw)."""
w, x, y, z = self.q
roll = np.arctan2(2*(w*x + y*z), 1 - 2*(x**2 + y**2))
pitch = np.arcsin(np.clip(2*(w*y - z*x), -1, 1))
yaw = np.arctan2(2*(w*z + x*y), 1 - 2*(y**2 + z**2))
return np.degrees([roll, pitch, yaw])
# Demo
madgwick = MadgwickFilter(sample_rate=100, beta=0.1)
for i in range(100):
gyro = np.array([0.1, 0.05, 0.02]) # rad/s
accel = np.array([0.0, 0.0, 9.81]) # gravity
q = madgwick.update(gyro, accel)
roll, pitch, yaw = madgwick.get_euler()
print(f"Roll: {roll:.2f}°, Pitch: {pitch:.2f}°, Yaw: {yaw:.2f}°")
Tuning the Gradient Descent Gain
Beta is the one number that decides how Madgwick behaves, and it balances two competing errors. The gyro term propagates a smooth but drifting quaternion; the gradient descent term pulls that quaternion toward the accelerometer's gravity reading with a step size proportional to beta. Larger beta trusts the accelerometer more — faster recovery from gyro bias, but more attitude jitter whenever the vehicle accelerates. Smaller beta tracks the gyro more closely — cleaner output in aggressive flight, but slower correction of the drift that made you leave the complementary filter in the first place.
A defensible starting procedure does not guess. Run a static bench log and measure accelerometer noise (for many MEMS parts, 0.02 to 0.05 m/s² RMS), then set beta so the gradient step magnitude at that noise level is roughly one percent of a typical rotation rate (0.1 rad/s). In practice this lands beta between 0.03 and 0.2 for consumer IMUs; the demo above uses 0.1 at a 100 Hz update rate, which recovers a 1° gyro-induced attitude error within a few seconds of level flight.
Two symptoms disambiguate a bad setting. Attitude that visibly wobbles in hover but looks clean in a fast yaw corresponds to beta too high — the accelerometer's vibration leaks into the output. Attitude that settles correctly at arm-up but creeps several degrees over a two-minute hold corresponds to beta too low — bias never gets corrected faster than it accumulates. If a single constant cannot fix both, the honest fix is estimating gyro bias as a state (an EKF or a Mahony filter with integral action) rather than pushing beta into a compromise that handles neither case.
Kalman Filter: Full Mathematical Framework
The Kalman filter maintains a state estimate and its uncertainty, optimally combining predictions with measurements.
The predict step advances the state with the model and grows the covariance with process noise Q; the update step scales the measurement residual by the Kalman gain K, which is essentially the ratio of predicted uncertainty to predicted uncertainty plus measurement uncertainty R. When P is large relative to R, K approaches 1 and the measurement overwrites the prediction. When R dominates, K approaches 0 and the filter ignores the sensor. Everything about tuning a Kalman filter comes back to keeping those two matrices honest descriptions of reality.
Tuning Q and R by Hand
Autotuners exist, but a practitioner should be able to move both knobs deliberately. Process noise Q answers: how wrong can my model be between updates? For attitude propagation from a gyro, the dominant model error is bias walk, so Q on the bias states should be set from the IMU's bias instability datasheet — typically 1e-6 to 1e-5 (deg/s)² per second for consumer parts — while Q on the angle states stays near zero because the gyro integration is accurate over one sample. Inflating Q says "the model drifts fast," which makes the filter responsive but noisy; deflating it says "trust the model," which smooths output but lets stale predictions outrun reality.
Measurement noise R answers the mirror question: how wrong can this sensor be right now? For an accelerometer providing gravity direction, R comes from the measured RMS noise during hover plus a term for maneuver acceleration — a filter running through a 2 g turn needs an R several times its hover value, or the update will yank the attitude toward the false gravity reading. For GNSS, R scales with reported variance and should be inflated on low satellite count or high dilution of precision rather than kept fixed.
The diagnostic that catches bad tuning is the normalized innovation squared: the squared measurement residual divided by its expected variance. Averaged over a window, it should hover near 1.0. Persistently above 1.0 means R is too small or Q too large — the filter is surprised by measurements it claims to understand. Persistently below 1.0 means the opposite — the filter is so conservative it discards real information. Checking this statistic after every tuning change turns "it feels smoother" into evidence, which is the difference between a filter you can defend in a flight review and one you cannot.
Hands-On Project: 6-State EKF Implementation
class EKF_AHRS:
"""6-state Extended Kalman Filter for AHRS."""
def __init__(self, dt=0.01):
self.dt = dt
# State: [roll, pitch, yaw, gyro_bias_x, gyro_bias_y, gyro_bias_z]
self.x = np.zeros(6)
# State covariance
self.P = np.eye(6) * 0.1
# Process noise
self.Q = np.eye(6) * 0.001
self.Q[3:, 3:] *= 0.01 # Gyro bias process noise
# Measurement noise
self.R_accel = np.eye(2) * 0.5
self.R_mag = np.eye(1) * 2.0
def predict(self, gyro):
"""Predict step using gyroscope."""
roll, pitch, yaw, bx, by, bz = self.x
# Remove estimated bias from gyro
gx, gy, gz = gyro - np.array([bx, by, bz])
# State transition (simplified)
self.x[0] += gx * self.dt # roll
self.x[1] += gy * self.dt # pitch
self.x[2] += gz * self.dt # yaw
# Biases remain constant (random walk)
# Jacobian
F = np.eye(6)
F[0, 3] = -self.dt
F[1, 4] = -self.dt
F[2, 5] = -self.dt
# Update covariance
self.P = F @ self.P @ F.T + self.Q
def update_accel(self, accel):
"""Update with accelerometer (roll and pitch)."""
ax, ay, az = accel / np.linalg.norm(accel)
# Expected measurement from current state
roll, pitch = self.x[0], self.x[1]
h = np.array([
np.arctan2(ay, az) - roll,
np.arctan2(-ax, np.sqrt(ay**2 + az**2)) - pitch
])
# Jacobian
H = np.zeros((2, 6))
H[0, 0] = -1
H[1, 1] = -1
# Kalman gain
S = H @ self.P @ H.T + self.R_accel
K = self.P @ H.T @ np.linalg.inv(S)
# Update
self.x += K @ h
self.P = (np.eye(6) - K @ H) @ self.P
def update_mag(self, mag, declination=0.0):
"""Update with magnetometer (yaw only)."""
mx, my = mag[0], mag[1]
expected_yaw = np.arctan2(my, mx) - declination
error = expected_yaw - self.x[2]
error = np.arctan2(np.sin(error), np.cos(error)) # Wrap to [-π, π]
H = np.zeros((1, 6))
H[0, 2] = 1
S = H @ self.P @ H.T + self.R_mag
K = self.P @ H.T @ np.linalg.inv(S)
self.x += (K @ np.array([error])).flatten()
self.P = (np.eye(6) - K @ H) @ self.P
def get_orientation(self):
"""Get current orientation in degrees."""
return np.degrees(self.x[:3])
# Demo
ekf = EKF_AHRS(dt=0.01)
np.random.seed(42)
for i in range(100):
gyro = np.array([0.1, 0.05, 0.02]) + np.random.normal(0, 0.01, 3)
accel = np.array([0.0, 0.0, 9.81]) + np.random.normal(0, 0.1, 3)
mag = np.array([20.0, 5.0, 0.0]) + np.random.normal(0, 0.5, 3)
ekf.predict(gyro)
ekf.update_accel(accel)
if i % 5 == 0: # Magnetometer slower
ekf.update_mag(mag)
roll, pitch, yaw = ekf.get_orientation()
print(f"Roll: {roll:.2f}°, Pitch: {pitch:.2f}°, Yaw: {yaw:.2f}°")
Sensor Failure Modes the Filter Cannot Fix Alone
Filters degrade gracefully only when failures are declared. Four cases recur on real airframes, and each needs a detection rule outside the filter's own equations.
GNSS dropouts and multipath. Urban canyons and tree cover produce position jumps of several meters rather than clean outages. Detect them with innovation monitoring — a residual beyond three sigma triggers rejection — and switch to dead reckoning with inflated covariance instead of feeding the jump to the update step. On recovery, ramp the measurement back in over a few seconds; slamming full gain on the first good fix yanks the track.
Barometer disturbances. Prop wash and rotor downwash on the fuselage vent can move the reported altitude by 5 to 10 m within a second of throttle change. Gate the barometer on throttle transients, or mount it in a shielded static port fed by tubing rather than a direct hole in the shell. Under-rotor pressure changes scale roughly with the square of airspeed over the sensor, so the corruption follows throttle, not terrain.
Magnetometer hard and soft iron effects. Current through the main power leads produces a field that rotates with throttle; nearby steel shifts the field by a fixed offset in the body frame. Both are removed by an onboard calibration — figure-eight rotations on the ground plus, ideally, a full 3D sweep with props removed — and the resulting offsets and scale matrix belong in the sensor configuration, not in ad hoc heading corrections. If heading residual grows with throttle after calibration, suspect the current-loop field and move the sensor or route the wiring.
Accelerometer saturation. At 16 g full scale, aggressive maneuvers or a hard prop strike exceed the range, and the clipped reading looks like a valid gravity vector pointing somewhere wrong. Detect clipping at the driver level (many IMUs report saturation flags) and suspend accelerometer updates during the clip rather than let a saturated sample corrupt the attitude for the milliseconds it takes to wash out.
None of these require a different filter. They require treating each sensor as an input with availability and quality metadata, which is precisely what the innovation and chi-square checks in a well-built EKF provide.
Filter Comparison
| Filter | CPU | Accuracy | Tuning | Best For |
|---|---|---|---|---|
| Complementary | Very Low | Good | Simple (α) | Basic drones |
| Madgwick | Low | Very Good | Moderate (β) | Most applications |
| Mahony | Low | Good | Moderate (Kp, Ki) | Outdoor flight |
| EKF | Medium | Excellent | Complex | Professional systems |
Key Takeaways
- Sensor fusion combines multiple sensors for better estimates than any single sensor
- Complementary filter: simplest, good for basic applications
- Madgwick filter: best balance of performance and simplicity for most drones
- Kalman/EKF: most accurate but complex to tune and implement
- Always calibrate sensors before fusion — garbage in, garbage out
- Gyro bias estimation is critical for long-term accuracy
Common Mistakes
Choosing a filter before measuring the actual sensor noise and bias
Fix: Run static and hover bench logs first; feed measured noise density, bias instability, and vibration response into Q and R.
Setting one fixed complementary blend factor for every phase of flight
Fix: Ramp alpha toward the gyro when acceleration departs from 1 g, and back toward the accelerometer in steady hover.
Leaving R fixed while the sensor's real noise changes with conditions
Fix: Scale R with throttle transients, satellite count, and reported variance — a barometer in prop wash is not a barometer in still air.
Trusting heading after a single ground magnetometer calibration
Fix: Detect throttle-correlated heading residuals, rerun a full 3D calibration with props removed, and store offsets in the airframe configuration.
Tuning by feel until the output looks smooth
Fix: Track the normalized innovation squared near 1.0; smooth output that fails this check means over-trust in the model, not a good filter.