Try Embedded

Sensors and sensor fusion

Integrating sensors, calibration, IMUs and complementary and Kalman filters.

Sensors are the product's senses

Most embedded products are built around sensors: a thermostat's temperature sensor, a phone's accelerometer, a drone's gyroscope, a wearable's heart-rate sensor. Integrating one well means more than reading a register: configuring it, understanding its errors, calibrating it and combining it with others.

Choosing and reading a digital sensor

Modern sensors are usually ICs with an I2C or SPI interface. Reading the datasheet, look for:

ParameterWhy it matters
Range and resolutionWill it saturate? Can it see the change you care about?
Accuracy, offset and gain errorAbsolute correctness; often needs calibration
Noise (RMS or density, e.g. µg/√Hz)The smallest change you can detect; averaging reduces it
Output data rate and bandwidthHow fast it samples; internal filters set the bandwidth
Temperature driftOffset and gain change with temperature
Power modes and currentBattery life; many sensors have low-power and wake-on-motion modes
FIFO, interrupts, data-ready pinLet the MCU sleep and read in batches instead of polling

Good practice: read and verify the WHO_AM_I or chip-ID register at start-up, check every bus transaction, use the data-ready interrupt or FIFO watermark interrupt, read multi-byte values in a single burst (so high and low bytes come from the same sample), and convert raw counts to units with the datasheet's sensitivity.

Inertial sensors

SensorMeasuresWeakness
AccelerometerAcceleration including gravity (m/s² or g)Noisy; cannot tell tilt from linear acceleration
GyroscopeAngular rate (°/s)Bias drifts; integrating it to get angle accumulates error
MagnetometerMagnetic field (µT)Distorted by nearby metal and currents

An IMU combines an accelerometer and gyroscope (6-axis), sometimes with a magnetometer (9-axis).

Tilt from an accelerometer at rest uses gravity: roll = atan2(ay, az), pitch from ax and the other two. The gyroscope gives smooth short-term changes but drifts; the accelerometer gives a drift-free but noisy long-term reference. Sensor fusion combines them.

The complementary filter

The simplest fusion: integrate the gyro for short-term changes and gently pull the result towards the accelerometer's angle to remove drift.

angle = α × (angle + gyro_rate × dt) + (1 − α) × accel_angle      α ≈ 0.98

It acts as a high-pass filter on the gyro and a low-pass filter on the accelerometer, which is where the name comes from.

#include <stdio.h>

int main(void) {
  /* The true angle is 10 degrees and constant. The gyro has a bias of +0.5 deg/s,
     the accelerometer reading is noisy around the true value. */
  double dt = 0.01, alpha = 0.98;
  double gyro_only = 0.0, fused = 0.0;
  double noise[5] = { 2.0, -1.5, 1.0, -2.5, 1.0 };

  for (int i = 1; i <= 1000; i++) {                  /* 10 seconds at 100 Hz */
    double gyro_rate = 0.0 + 0.5;                    /* true rate 0 plus bias */
    double accel_angle = 10.0 + noise[i % 5];
    gyro_only += gyro_rate * dt;
    fused = alpha * (fused + gyro_rate * dt) + (1 - alpha) * accel_angle;
    if (i % 200 == 0)
      printf("t=%4.1fs  gyro only %6.2f deg   fused %6.2f deg\n", i * dt, gyro_only + 10.0, fused);
  }
  return 0;
}

The gyro-only estimate (started at the true angle) drifts steadily away; the fused estimate converges near 10° and stays there with the accelerometer noise heavily smoothed. A gyro bias leaves a small constant offset (about α/(1−α) × bias × dt), which bias calibration removes.

The Kalman filter in one paragraph

A Kalman filter generalises this: it keeps an estimate of the state (for example angle and gyro bias) together with its uncertainty, predicts the next state from a model and the gyro, then updates with each measurement, weighting it by the relative uncertainty of prediction and measurement (the Kalman gain). It estimates the gyro bias as it goes and is optimal for linear systems with Gaussian noise. Orientation in 3D usually uses an extended Kalman filter or the Madgwick or Mahony filters, which represent orientation as a quaternion to avoid the singularities of Euler angles (gimbal lock). Many IMUs now run fusion on-chip (BNO085, ICM-20948 with DMP).

Calibration

ErrorCalibration
Gyro biasAverage the output while stationary at start-up (or continuously when still) and subtract
Accelerometer offset and scaleMeasure with each axis pointing up and down (±1 g) and solve for offset and gain
Magnetometer hard iron (offset) and soft iron (distortion)Rotate the device through many orientations, fit an ellipsoid, apply offset and correction matrix
Temperature driftCharacterise over temperature and store a correction table

Store calibration in non-volatile memory with a CRC (see the flash lesson), and design the product so the user or production line can recalibrate.

Other common sensors

  • Environmental: temperature, humidity (BME280, SHT4x), pressure (barometric altitude), gas and particulate sensors (often need warm-up and long-term baseline correction).
  • Distance: ultrasonic (time of flight measured with timer input capture), infrared and laser time-of-flight (VL53L1X), radar.
  • Optical: ambient light, proximity, photoplethysmography (heart rate and SpO2 from reflected light).
  • Current and power: shunt monitors (INA219/INA226), Hall-effect current sensors.
  • Position: encoders, potentiometers, Hall switches, GPS/GNSS receivers (NMEA or binary protocols over UART).

Pitfall: Reading a 16-bit sensor value as two separate single-byte transactions can combine the high byte of one sample with the low byte of the next, producing occasional large glitches. Use a burst read with the sensor's "block data update" setting so both bytes come from the same sample.

Interview question: Explain a complementary filter for estimating tilt angle.

Answer: Each update, the gyro rate times dt is added to the previous angle estimate, which tracks fast changes smoothly but drifts because bias is integrated. The accelerometer gives an angle from the direction of gravity, which is drift-free but noisy and disturbed by linear acceleration. The filter blends them: angle = α·(angle + rate·dt) + (1−α)·accel_angle with α near 0.98, so over short times the gyro dominates (high-pass) and over long times the estimate is pulled to the accelerometer (low-pass). The time constant is about dt·α/(1−α).

Interview question: How would you integrate a new I2C sensor into a product?

Answer: Read the datasheet for range, noise, power modes, timing and register map. Write a driver against a bus abstraction: at start-up verify the chip ID, reset and configure it (range, data rate, filters, FIFO and interrupts), with error handling and retries. Read data in bursts triggered by its data-ready or FIFO interrupt, convert to physical units, apply stored calibration, and filter as needed. Test with a fake bus on the host, then characterise on hardware for noise, temperature drift and current, and implement calibration and fault detection (stuck or out-of-range values).

Build it: know which way the camera points

This is step 5, the last of the module project. The camera gimbal's PID loops (step 3) need the camera's angle, 1000 times a second. The gyro is smooth and fast but drifts; the accelerometer knows where "down" is but is noisy, and wrong whenever the person holding the gimbal accelerates. A complementary filter combines them, after a calibration at power-up removes the gyro's bias, but only if the gimbal really was standing still.

Lab: Gyro calibration, an accelerometer check and a complementary filter

Rates are in millidegrees per second, angles in millidegrees, accelerations in mg. Use 64-bit intermediate values.

  • fusion_calibrate(f, gyro, n) averages n gyro readings taken at power-up (rounded to the nearest) into f->bias. If the readings spread by more than STILL_MDPS (largest minus smallest), the gimbal was moved: return -1 and leave the bias unchanged, so the user is asked to put it down. Otherwise return 0.
  • acc_trust(ax, ay, az) returns 1 when the accelerometer can be trusted for "down": the length of the vector is between 900 and 1100 mg (compare squares; no square root needed). Outside that, someone is accelerating the gimbal.
  • fusion_step(f, gyro, acc_angle, acc_ok, dt_ms) returns the new angle:
  • The first time it is called with acc_ok set, the angle starts at acc_angle. Before that, return 0 and change nothing.
  • Otherwise predict with the gyro: pred = angle + (gyro − bias) × dt_ms / 1000.
  • With acc_ok, blend: angle = (980 × pred + 20 × acc_angle) / 1000. Without it, angle = pred: trust the gyro alone while the accelerometer is fooled.

Going deeper

Interview question: How would you track a VR headset's orientation without drift or lag?

Answer: Integrate the gyroscope at a high rate for low latency, correct its drift with the accelerometer (gravity, for tilt) and the magnetometer or cameras (for heading), in a complementary or Kalman filter. Calibrate the sensors' biases and alignment, timestamp samples precisely, and predict a little ahead to cover the display's latency.

Interview question: Why do orientation filters use quaternions instead of Euler angles?

Answer: Euler angles (roll, pitch, yaw) have singularities: at certain orientations, such as pitch of ±90°, two axes align and one degree of freedom is lost (gimbal lock), making the equations ill-defined. Quaternions represent any 3D rotation with four numbers and no singularities, compose rotations with simple multiplication, and are cheap to normalise, so filters like Madgwick, Mahony and Kalman variants work in quaternions and convert to Euler angles only for display.

Interview question: What does a Kalman filter add over a complementary filter?

Answer: It models the uncertainty of both its prediction and the measurements and computes the optimal weighting (the Kalman gain) at each step instead of using a fixed α, adapting when measurements are more or less trustworthy. It can also estimate hidden states such as gyro bias, and it extends naturally to more sensors and states. The cost is more computation, a model and noise parameters to tune; for a simple tilt estimate a well-tuned complementary filter is often close in performance.

Explain it: In your own words, explain why integrating a gyroscope alone gives a drifting angle.

Answer: A gyroscope measures angular rate, so finding the angle means adding up rate times time at every sample. Every real gyro has a small bias (a non-zero output when not rotating) plus noise, and integration adds that bias in at every step, so the error grows steadily with time instead of averaging out. Even 0.1 degree per second of bias becomes 6 degrees after a minute. Without an absolute reference such as gravity from an accelerometer or a magnetometer heading to correct it, the estimate drifts without limit.