Simvik

Complementary filter for tilt

Blend a gyro's smooth but drifting angle with an accelerometer's noisy but absolute one. A medium embedded C problem (Sensors and sensor fusion), run and…

medium · Sensors and sensor fusion · sensor-fusion · imu · fixed-point

A gyro measures turn rate: integrating it gives a smooth angle that slowly drifts. An accelerometer gives an absolute angle from gravity, but it is noisy whenever the device moves. A complementary filter trusts the gyro in the short term and the accelerometer in the long term.

Write comp_update(c, gyro_mdps, acc_mdeg, dt_ms), with the gyro rate in millidegrees per second, the accelerometer's angle in millidegrees and the time step in milliseconds. Return the new angle:

  • On the first call, the angle is the accelerometer's angle.
  • After that: predicted = angle + gyro_mdps * dt_ms / 1000, then angle = (98 * predicted + 2 * acc_mdeg) / 100.

Use 32-bit signed integers and C's / (which rounds toward zero). Angles and rates can be negative.

Starter code

int32_t comp_update(comp_t *c, int32_t gyro_mdps, int32_t acc_mdeg, uint32_t dt_ms) {
  c->angle += gyro_mdps * dt_ms / 1000;
  return c->angle;
}

Example tests

Turning at 10 degrees per second, accelerometer at 0

comp_t c = {0};
run(&c, 0, 0, 10, 1);
run(&c, 10000, 0, 10, 5);
printf("\n");

Expected output:

0 98 194 288 380 470

The accelerometer pulls a stationary angle across

comp_t c = {0};
run(&c, 0, 0, 10, 1);
run(&c, 0, 30000, 10, 3);
printf("\n");

Expected output:

0 600 1188 1764

Learn it first

More Sensors and sensor fusion problems