Skip to content
Velloreth
Engineering & Robotics 11 min read

Sensor Fusion: Combining Data from Multiple Sensors

Why individual sensors fail differently, and how complementary, Kalman, and gradient-descent filters combine them — with code, tuning, and calibration details.

By

No sensor is trustworthy across every condition. A gyroscope is excellent for a fraction of a second and then drifts. An accelerometer gives an absolute reference to gravity and is useless the moment the device accelerates. A magnetometer knows heading and will happily point north in a steel-framed building.

Sensor fusion is the practice of combining measurements whose failure modes are different, so that the weaknesses of one are covered by the strengths of another. The algorithms that do it range from a single line of arithmetic to full state estimators, and choosing the simplest one that covers your failure modes is the whole discipline.

What each sensor is actually good at

SensorMeasuresReliable forFails when
AccelerometerSpecific force (gravity when static)Absolute tilt in pitch and rollAny linear acceleration; vibration; mounting offset
GyroscopeAngular rateShort-term rotation, fast dynamicsZero-rate offset integrates into unbounded drift
MagnetometerLocal magnetic fieldAbsolute yaw / headingNear iron, currents, magnets, speaker drivers
BarometerAbsolute pressureAltitude changes of metersWeather drift; rotor wash; enclosure pressure
GPSPosition and velocityAbsolute position, 1–10 HzMultipath, indoors, canyons, foliage
Encoder / odometerWheel or joint rotationRelative displacementSlip, surface changes, wheel flex
ToF / ultrasonic / lidarDistance to surfaceObstacle rangeSpecular surfaces, dust, acoustic cross-talk
Thermistor / RTDTemperatureSlow processesSelf-heating, thermal lag, placement

The pattern in the table: absolute sensors are accurate but slow, noisy, or easily disturbed; relative sensors are smooth and fast but integrate error without bound. Every fusion scheme pairs them along that axis.

Three levels of fusion

Signal-level (low-level) fusion combines raw measurements into a refined signal — filtering an IMU to produce orientation. This is what people usually mean, and it is the bulk of this post.

State-level fusion estimates quantities you cannot measure directly by combining measurements through a model — estimating position and velocity from GPS plus IMU plus wheel odometry, where no single sensor sees the full state.

Decision-level fusion combines conclusions rather than signals: three sensors each decide “door open”, and a voter produces the final answer. Simpler to build, easier to debug, and appropriate when the sensors observe different aspects of the situation rather than the same quantity.

The baseline: averaging, and why it is not enough

Independent noise averages down: if you take N samples of a static value with noise standard deviation σ, the average has standard deviation σ / √N. Four samples halve the noise. That is real and worth using for static readings.

But averaging has two limits. It does nothing about bias — a constant offset averages to itself — and it trades latency for smoothness: a moving-average filter with a long window lags real motion by roughly half the window length. Both problems recur in every scheme below, which is why fusion is more than averaging.

The complementary filter: the right default for attitude

Attitude from a six-axis IMU has a clean structure: the gyroscope tells you how the orientation is changing right now (smooth, fast, drifting), and the accelerometer tells you where gravity points (absolute, noisy, invalid under acceleration). Complementary filtering splits the frequency spectrum between them:

float alpha = 0.98f;                    /* gyro weight */
float dt = 0.01f;                       /* 100 Hz */

gyro_rate  = read_gyro();               /* deg/s */
accel_ref  = atan2f(ay, sqrtf(ax*ax + az*az));   /* accel-only tilt */

angle = alpha * (angle + gyro_rate * dt)
      + (1.0f - alpha) * accel_ref;

Read that as two weighted contributions: the integrated gyro term keeps the estimate responsive, and the accelerometer term gently drags it back toward the true gravity direction, preventing unbounded drift.

The single parameter alpha controls the trade. It is easiest to think in terms of the correction time constant:

tau ≈ dt / (1 - alpha)

At 100 Hz with alpha = 0.98, tau = 0.01 / 0.02 = 0.5 s: drift accumulated by the gyro is corrected with a half-second time constant. Raise alpha toward 1 and the estimate tracks motion more closely but takes longer to shed drift. Lower it and corrections are quicker but jitter from the accelerometer comes through. Start at 0.98 and tune by watching a still device drift and a fast device lag.

Gating: the accelerometer under acceleration

The scheme above has one known weakness: during linear acceleration, the accelerometer’s gravity reference is contaminated, and the filter will happily correct toward a wrong angle. Fix it by checking whether the measured acceleration magnitude is close to 1 g before trusting the direction:

float norm = sqrtf(ax*ax + ay*ay + az*az);
bool static_like = fabsf(norm - 9.81f) < 1.0f;   /* +-1 m/s^2 */

if (static_like) {
    angle = alpha * (angle + gyro_rate * dt) + (1.0f - alpha) * accel_ref;
} else {
    angle += gyro_rate * dt;                     /* integrate only */
}

This one check removes most of the visible error during quick motions, and it costs a square root. The threshold is a judgment call: too tight and the filter never corrects (the device is almost never perfectly static), too loose and it corrects during maneuvers. Around 0.5–1 m/s² from 1 g works for handheld and slow-robot cases.

The Kalman filter: when a model pays for itself

A Kalman filter is a recursive estimator for a system you can describe with equations. It has two phases:

predict:  x_hat = F * x_hat + B * u           /* advance the model */
          P     = F * P * F' + Q               /* grow the uncertainty */

update:   K     = P * H' * (H * P * H' + R)^-1 /* Kalman gain */
          x_hat = x_hat + K * (z - H * x_hat)  /* correct by the residual */
          P     = (I - K * H) * P

The interesting object is P, the error covariance: the filter continuously weighs its model prediction against the new measurement according to which is currently less uncertain (Q versus R). If you model the sensor noise honestly, the blend is statistically optimal for a linear system.

What that buys you:

  • Multiple simultaneous sources — GPS, IMU, odometry, and barometer all updating one state with different rates and uncertainties.
  • Estimating the unobservable — gyro bias, acceleration offsets, sensor delays — by treating them as additional state variables.
  • Optimal weighting rather than hand-picked alpha values.

What it costs:

  • A model. If your process model is wrong, the filter is confidently wrong; a complementary filter with no model has no such failure mode.
  • Tuning of Q and R, which is not easier than tuning alpha — it just has more knobs.
  • Compute. Published comparisons of orientation filters find complementary filters running up to an order of magnitude faster than Kalman implementations, with comparable accuracy on the same IMU data.

Nonlinear systems (rotation is nonlinear — angles wrap, trigonometry is involved) require an extended or unscented Kalman filter, which raises both the implementation cost and the number of ways to get it subtly wrong. Use a Kalman filter when you have a genuine process model and more than two sources to combine; reach for the complementary filter when you are estimating attitude from an accelerometer and gyro.

Madgwick and Mahony: the middle ground

Two open-source alternatives sit between the two camps:

  • Mahony uses a proportional-integral feedback loop on the gravity residual to correct a quaternion estimate. Cheap, stable, widely used on flight controllers.
  • Madgwick formulates the correction as a gradient-descent step toward the measured gravity direction, with a gain beta that plays a role analogous to alpha.

Both are quaternion-based (avoiding gimbal lock near vertical orientations) and both are considerably cheaper than a full EKF. One caveat worth knowing: with only an accelerometer and gyro, the yaw component of any of these estimates is unobservable — gravity constrains two axes, not three. Yaw drifts unless you add a magnetometer, and adding one introduces the hard- and soft-iron distortion problem described below.

An alternative that avoids the algorithm choice entirely: parts like the MPU-6050 ship with a digital motion processor that fuses accelerometer and gyro internally and outputs quaternions or Euler angles. It is decent, well-tested, and frees your MCU. Write your own filter when you need to know exactly how the estimate behaves, need gating logic, or need to fuse in additional sources.

Choosing at a glance

ApproachAccuracyComputeTuningModel neededBest for
Raw trigonometryPoor under motionMinimalNoneNoStatic tilt measurement only
ComplementaryGoodVery lowOne constantNoPitch/roll from 6-axis IMU
Mahony / MadgwickGood to very goodLowOne gainNoQuaternion attitude, flight controllers
Kalman / EKFBest with a good modelHighCovariancesYesMulti-sensor state estimation
Vendor DMPGoodOffloadedNoneNoWhen the hardware can do it

Beyond attitude: other common fusion problems

GPS + IMU dead reckoning. GPS updates position at a few hertz with large uncertainty; the IMU integrates between updates at high rate with growing uncertainty. Fuse them so the IMU carries the solution through gaps and the GPS resets the drift. Add wheel odometry for ground vehicles and the solution holds through short GPS outages in tunnels and streets.

Altitude. Barometers give absolute altitude but are noisy and shift with weather; accelerometers give precise vertical acceleration but integrate into drift. Fuse them, and gate the accelerometer during vertical maneuvers — the same pattern as attitude, with the roles played by different physics.

Redundant sensors of the same type. Three temperature sensors in a chamber: take the median rather than the mean, so one failed-open sensor (reading ambient) cannot drag the estimate. Robust fusion is often outlier rejection before it is any kind of estimator.

Encoder + IMU on a robot. Wheel odometry says how far the base moved; the IMU says how it rotated. Fusing them covers wheel slip in rotation and gyro drift in translation.

The unglamorous work that decides accuracy

Filters get the attention. These decide the outcome:

Calibration.

  • Gyro bias: average several seconds at rest and subtract it, on every boot. Uncorrected, this alone produces visible drift within seconds.
  • Accelerometer: six-position calibration gives scale and offset per axis; a simple three-position check catches gross errors.
  • Magnetometer: hard-iron offsets (from magnets and current loops on your own board) and soft-iron scaling (from surrounding ferrous material) require a calibration routine run while rotating the device through all orientations. Calibrate after final assembly — the board’s own currents are part of the problem.
  • Mounting misalignment: if the sensor is rotated 2° relative to the body you are measuring, no filter fixes it. Measure the mounting or estimate it as part of the state.

Time synchronization. A 5 ms timestamp error at 100 deg/s is half a degree. Read sensors in one place, timestamp at the point of acquisition, and if two devices must be synchronized, sync their clocks before trusting their fusion. Filters that assume simultaneous measurements will degrade quietly when the assumption breaks.

Units and conventions. m/s² versus g, degrees versus radians, right-hand versus left-hand axis conventions, and Euler order (yaw-pitch-roll versus roll-pitch-yaw) are responsible for a surprising share of “the filter does not work” reports. Fix conventions in one header, not per-file.

Noise characterization. Record data from your actual sensor in your actual configuration — powered, mounted, near the motors — and compute the variance while static. Those numbers become R, or they tell you your alpha. Datasheet noise density figures are a starting point; the board decides the rest.

Dropouts and reset behavior. Decide what the estimator does when a sensor stops reporting: hold the last state, degrade to another sensor, or reset. Silence handling is part of the algorithm, not an afterthought.

Start simple, escalate with evidence

The practical sequence for a new project: fix calibration and synchronization first, then raw trigonometry to confirm wiring and axes, then a complementary filter with gating, and only then a Kalman filter if the requirements still demand it — a GPS-IMU state estimate, a bias you must observe, or a spec the simple filter measurably misses.

Most attitude projects never leave step three, and that is not a compromise. A well-calibrated complementary filter with a sensible gate beats an untuned EKF fed by a misaligned sensor, because the limits of fusion are set by the measurements going in, not by the mathematics coming out.

Frequently asked questions

Do I need a Kalman filter for an MPU6050?
Usually not. For pitch and roll on a six-axis IMU, a complementary filter gives results close to a Kalman filter at a fraction of the code and tuning cost, and published comparisons find the complementary filter substantially cheaper to compute. If the part's built-in digital motion processor produces usable quaternions, even that is often enough — apply your own filter only when you need to know exactly how the estimate behaves.
Why does my orientation drift when the device is still?
Gyroscopes integrate small zero-rate offsets into steadily growing angle error, and a stationary accelerometer cannot correct heading at all. Fix it by calibrating the gyro bias while at rest, then let an absolute reference — accelerometer for pitch and roll, magnetometer for yaw — correct the drift through a filter.
Can sensor fusion fix a bad sensor?
No. Fusion combines complementary error profiles; it cannot rescue a sensor whose noise you have not characterized or whose mounting you have not calibrated. A badly calibrated magnetometer will make a fused heading confidently wrong, which is worse than an obviously drifting one.
What is sensor fusion at the decision level?
Instead of combining raw signals, each sensor produces its own conclusion and the system combines those — a thermostat deciding from both temperature and a door contact, or a robot voting among three wheel encoders. It is simpler to implement and debug than signal-level fusion, and appropriate when the sensors measure different aspects of the situation rather than the same quantity.