Complementary Filter vs EKF for Embedded IMU Orientation
How to choose between a complementary filter and an EKF for IMU orientation on embedded robots, with a worked configuration and verification steps.
15 Sept 2026, 04:28 UTC

The drift problem on a moving robot
Your robot’s heading slowly creeps away from north, or a hovering platform rolls to one side with no command. A gyroscope measures angular rate, and integrating that rate gives you angle, but any small bias in the sensor accumulates without bound. An accelerometer can measure gravity to correct roll and pitch, and a magnetometer can correct yaw, but both are noisy and unreliable during rapid motion. If you are building an embedded orientation estimator, the real question is not whether to fuse sensors, but how much filtering complexity your hardware and motion profile can justify.
Takeaway: start with a complementary filter. It is deterministic, cheap, and easy to tune. Move to an extended Kalman filter (EKF) only when logged data shows the simpler filter cannot handle your motion or magnetic environment, and validate either choice offline before freezing firmware.
Complementary filter: one gain, predictable cost
A complementary filter blends two estimates. The gyroscope provides short-term precision: integrate angular rate over a small time step dt to update roll, pitch, and yaw. The accelerometer and magnetometer provide long-term reference: gravity defines down, and Earth’s magnetic field defines north, at least when the sensor is not being shaken or disturbed by nearby metal.
One tunable gain, usually called alpha, decides how much to trust each source. A high alpha favors the gyroscope and responds quickly but drifts over time. A low alpha favors the accelerometer and magnetometer and resists drift but lags during fast movement. Because the math is just a weighted sum and an integration, it runs comfortably on low-power microcontrollers with limited RAM and no floating-point unit.
Extended Kalman filter: accuracy under motion, at a cost
An EKF fuses the same sensors while maintaining estimates of sensor noise and process noise in covariance matrices—matrices that describe how much uncertainty to assign to each prediction and measurement. It can weight the accelerometer less during aggressive acceleration and the magnetometer less during magnetic interference, which makes it more robust for drones, gimbals, or fast-moving robots.
The cost is implementation complexity. You must initialize and tune process-noise and measurement-noise matrices, predict state and covariance, and update with measurements at each step. Poorly chosen matrices can make the filter diverge, especially during rapid acceleration or when a nearby motor distorts the magnetometer. It also consumes more flash, RAM, and CPU cycles than a complementary filter.
Worked example: complementary filter configuration
Assume a Cortex-M4-based board reading an IMU over I2C. The following is a starting configuration, not a tested implementation.
/* Run on: target firmware, built with an ARM cross-toolchain */
/* Permissions: debugger/SWD access to flash the device */
/* Placeholders: replace with your sensor addresses and bus */
#define IMU_I2C_ADDR 0x68
#define ALPHA 0.98f /* 0.98 = favor gyroscope short term */
#define DT_S 0.01f /* 100 Hz update loop */
typedef struct {
float roll;
float pitch;
float yaw;
} orientation_t;
void fuse_step(orientation_t *o,
float gx, float gy, float gz, /* deg/s */
float ax, float ay, float az, /* m/s^2 */
float mx, float my, float mz) /* uT */
{
/* Integrate gyroscope */
o->roll += gx * DT_S;
o->pitch += gy * DT_S;
o->yaw += gz * DT_S;
/* Accelerometer tilt correction (simplified) */
float acc_roll = atan2f(ay, az);
float acc_pitch = atan2f(-ax, sqrtf(ay*ay + az*az));
/* Blend: high alpha keeps gyroscope, low alpha pulls toward accel */
o->roll = ALPHA * o->roll + (1.0f - ALPHA) * acc_roll;
o->pitch = ALPHA * o->pitch + (1.0f - ALPHA) * acc_pitch;
/* Magnetometer yaw correction omitted here; add hard/soft-iron calibration first */
}
Example build and flash commands:
# Build host
arm-none-eabi-gcc -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -O2 -Wall firmware.c -o firmware.elf
# Debugger host; requires access to the SWD interface
openocd -f interface/stlink.cfg -f target/stm32f4x.cfg -c "program firmware.elf verify reset exit"
Where to run: compile on a build host; flash over SWD/JTAG from a debugger host. On Linux, serial debug output may require membership in the dialout group or sudo.
Expected checks: no compiler warnings; OpenOCD reports verification passed; with the board stationary, roll and pitch settle near zero within a few seconds.
Risks: an incorrect target configuration can fail to flash or leave the device unresponsive. An incorrect alpha can make the estimator sluggish or drift-prone. Integrating raw gyroscope bias without correction causes unbounded yaw error, so never ship a configuration that relies on gyroscope integration alone for long-running heading.
Rollback: keep the previous firmware binary and re-flash it if the new estimator causes instability.
Limitation: magnetic distortion and calibration drift
Magnetometer heading is easily corrupted by nearby ferrous objects, current-carrying wires, or onboard electronics. Production pipelines usually apply hard-iron and soft-iron calibration, or reject magnetometer updates when the field magnitude deviates from the expected local value. Calibration values also drift with temperature and age, so factory calibration should be validated or refreshed rather than hardcoded permanently.
Verify before you commit to a filter
Record synchronized IMU data while performing a figure-eight motion, then replay it offline in Python or MATLAB. Check that the fused roll, pitch, and yaw converge and recover after a brief magnetic disturbance. If possible, compare against a motion-capture system or a higher-grade reference IMU. Use the sensor datasheet’s noise density and random-walk specifications to initialize any EKF covariance matrices with realistic values.
If the complementary filter meets your accuracy target on logged data, ship it. If it fails during aggressive motion or magnetic disturbance, the logged data will show exactly where it breaks down, which is the right basis for deciding whether an EKF’s complexity is justified.
Closing
Choose the simplest fusion method that passes your motion tests. Start with a complementary filter, tune alpha against real logs, and only introduce an EKF when the data proves you need it.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.