Ground Embedded KO Subscribe

Notes / Sensors & Signal Processing

IMU and sensor fusion: tilt from a complementary filter

An accelerometer is accurate over the long run but weak against vibration; a gyro is fast but drifts over time. The complementary filter blends the two.

GROUND EMBEDDED · NOTESensors & Signal Processing 05IMU and sensor fusionMCUTempI2CIMUSPIHallGPIORangeUARTCurrentADC

The character of the two sensors

Sensor Measures Strength Weakness
Accelerometer Direction of gravity (+ acceleration of motion) Accurate in the long term Badly disturbed by vibration and acceleration
Gyro Angular rate Fast and smooth Error accumulates when integrated (drift)

Complementary filter

Gyro integralfast but drifts× 0.98+Accel angleslow reference × 0.02Tilt
Complementary filter. Combines the gyro's fast changes with the accelerometer's slow reference.

Trust the gyro only for high frequencies (fast changes) and the accelerometer only for low frequencies (the long-term average).

float acc_angle = atan2f(ay, az) * RAD2DEG;
angle = 0.98f * (angle + gyro_x * dt) + 0.02f * acc_angle;

The 0.98 relates to a time constant τ ≈ dt · 0.98 / 0.02. With dt = 1 ms, τ ≈ 49 ms. Motion faster than this follows the gyro and slower trends follow the accelerometer.

RoadmapSee where this note sits in Sensors & Signal Processing→

Calibration

  • At rest, read the gyro a few hundred times and subtract the average as the offset. Without this the angle keeps drifting.
  • Match the accelerometer axes to the board's mounting orientation.
  • Turning on the MPU6050's built-in DLPF reduces motor vibration.

Going further

Three-axis attitude (roll, pitch, yaw) uses a Mahony or Madgwick filter or a Kalman filter. Yaw (heading) cannot be corrected by an accelerometer and needs a magnetometer. There are also IMU chips with a sensor-fusion processor built in (BNO085 and others).

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →