Module 2/5 · Weeks 4–6 · 27 h

IMUs and magnetometers

UAT 205 Sensors and Instrumentation Systems

About 90 minDraft, awaiting reviewLast updated 21 October 2026

Lesson

By the end of this module you will be able to

  1. Explain MEMS gyroscopes and accelerometers and the error model of bias, scale factor and noise
  2. Calibrate an accelerometer with the six-position method
  3. Read an Allan deviation plot to find angle random walk and bias instability
  4. Correct magnetometer hard iron and explain its effect on heading

Prerequisites: UAT 205 Module 1

Why this matters

The IMU (inertial measurement unit) is the heart of the flight controller. It contains gyroscopes, which measure rotation rate, and accelerometers, which measure acceleration. The controller reads the IMU hundreds to thousands of times per second to hold attitude. The magnetometer measures the Earth’s magnetic field to give heading. If these sensors are slightly off, the drone tilts, drifts or flies in the wrong direction.

MEMS and the error model

Almost all drone sensors are MEMS (micro-electro-mechanical systems): micrometre-scale mechanical structures on a silicon chip. An accelerometer has a small proof mass on springs; when it accelerates, the mass moves and a capacitance changes. A MEMS gyro has a mass that vibrates continuously; when it rotates, the Coriolis force makes it vibrate along another axis (Groves, 2013).

Each axis has a basic error model , where is the scale factor, the bias and the noise. Real sensors also have misaligned axes and temperature dependence. Datasheets give noise levels; TDK’s ICM-42688-P, for example, specifies gyro noise of 2.8 mdps/√Hz and accelerometer noise of 70 µg/√Hz.

Graph of reading against true value. A solid dark line through the origin is ideal. A parallel pink dashed line shifted up shows a bias. A blue dotted line through the origin but steeper shows a scale factor error
Figure 1 Sensor error model

Six-position accelerometer calibration

At rest, an accelerometer measures gravity with magnitude exactly . Placing each axis pointing up and then down, six positions in total, gives and readings on every axis, from which bias and scale factor follow directly. The ArduPilot guide uses these six positions (level, right side, left side, nose down, nose up and on its back), and IEEE 1293-2018 describes tumble testing of accelerometers in detail.

Example 1 Bias and scale factor from six positions

Mean at-rest readings for each position (m/s²) are hypothetical values.

import math

G = 9.80665
readings = {"x": (9.93, -9.69), "y": (9.85, -9.77), "z": (9.62, -10.02)}   # m/s² axis pointing up, pointing down

cal = {}
for axis, (up, down) in readings.items():
    bias = (up + down) / 2
    scale = (up - down) / (2 * G)
    cal[axis] = (bias, scale)
    print(f"{axis}: bias {bias:+.3f} m/s^2, scale factor {scale:.4f}")

raw = (0.12, 0.04, -10.02)            # truly level hover, z axis pointing down
fixed = [(r - cal[a][0]) / cal[a][1] for a, r in zip("xyz", raw)]
tilt = lambda v: math.degrees(math.atan2(math.hypot(v[0], v[1]), -v[2]))
print(f"apparent tilt before {tilt(raw):.2f} deg, after {tilt(fixed):.2f} deg")
x: bias +0.120 m/s^2, scale factor 1.0003
y: bias +0.040 m/s^2, scale factor 1.0003
z: bias -0.200 m/s^2, scale factor 1.0014
apparent tilt before 0.72 deg, after 0.00 deg

Before calibration, the controller would believe the drone is tilted by about three quarters of a degree while it sits level, and would keep correcting until the drone drifts to one side.

Allan deviation

Recording at rest for a long time and computing the Allan deviation against averaging time separates noise types. NXP application note AN5087 and El-Sheimy et al. (2008) explain how to read this log-log plot.

  • Where the curve falls with slope −1/2, the noise is white; its value on this line at s is the angle random walk (ARW).
  • The flat region before the curve rises is the bias instability, the smallest amount the bias wanders. AN5087 reads the minimum directly, while the IEEE gyro standard divides the minimum by 0.664; a report must say which method it uses.

These values set the noise parameters of the EKF and help compare two sensor models before buying.

Magnetometers and hard iron

A magnetometer measures the Earth’s very weak magnetic field, so iron parts and currents on the drone disturb it easily. Hard iron is a constant field from permanent magnets or magnetised parts; it makes the data collected while rotating form a circle with a shifted centre. Soft iron from magnetically permeable materials stretches the circle into an ellipse. Compass calibration in ArduPilot or PX4 therefore asks you to rotate the drone in many directions, and ArduPilot has a CompassMot procedure to correct motor current effects.

Example 2 Correcting hard iron and comparing heading

An assumed horizontal field of 35 µT has a hard-iron offset of (12, −8) µT. The drone rotates a full turn in 10° steps. A simple 2D model measures heading from the mx axis.

import math

OFF, H = (12.0, -8.0), 35.0          # µT hard-iron offset and assumed horizontal field
samples = [(d, H * math.cos(math.radians(d)) + OFF[0], H * math.sin(math.radians(d)) + OFF[1])
           for d in range(0, 360, 10)]

def worst_error(off):
    errs = []
    for d, mx, my in samples:
        head = math.degrees(math.atan2(my - off[1], mx - off[0]))
        errs.append(abs((head - d + 180) % 360 - 180))
    return max(errs)

est = ((max(s[1] for s in samples) + min(s[1] for s in samples)) / 2,
       (max(s[2] for s in samples) + min(s[2] for s in samples)) / 2)
print(f"worst heading error without calibration: {worst_error((0, 0)):.1f} deg")
print(f"estimated offset ({est[0]:.1f}, {est[1]:.1f}) uT")
print(f"worst heading error after hard-iron correction: {worst_error(est):.1f} deg")
worst heading error without calibration: 24.3 deg
estimated offset (12.0, -8.0) uT
worst heading error after hard-iron correction: 0.0 deg

An offset of about two fifths of the field magnitude puts heading off by more than 20°, enough to make the drone circle around its target (toilet bowling). Real work must also correct soft iron by fitting the ellipse back to a circle, and must recalibrate after moving equipment or changing a battery near the compass.

Axes mx and my. Pink dots form a circle whose centre is shifted right and down: the raw data. Green dots form a circle centred at the origin: after hard-iron correction. An arrow from the origin points to the pink circle's centre, the offset of 12 and minus 8 microtesla
Figure 2 Magnetometer data shifted by hard iron

Compass heading is relative to magnetic north, which differs from true north by the magnetic declination, varying with place and time. ArduPilot has a built-in world magnetic model and can set it automatically. To check the value, use NOAA’s World Magnetic Model calculator (WMM2025).

Fusing gyro and accelerometer with a complementary filter

A gyro gives rotation rate, so its integrated angle is smooth but drifts with bias. An accelerometer gives the tilt angle directly from the gravity direction, so it does not drift but is disturbed by motion and vibration. A complementary filter fuses the two so they cover each other. According to the AHRS library documentation, the fused angle is , where is the previous angle plus rate times and lies between 0 and 1. In this module we define with a chosen time constant (a teaching choice, not what every software package uses). A larger trusts the gyro for longer; a smaller one pulls toward the accelerometer faster.

Both inputs must be converted to angles in the same units and axis definition before fusing. Never average the raw gyro and accelerometer values, and use from the real sample times.

Example 3 Reducing gyro drift, and fusing a heading across the ±180° seam

Hold the device still so the true roll is 0°. The gyro has a constant bias of 0.5 °/s, sampled at 100 Hz ( = 0.01 s). Choose = 0.5 s and let the accelerometer angle be 0° throughout. Then fuse a heading prediction of 179° with a measurement of −179°, which are almost the same direction.

import math

# 1) one axis, constant gyro bias, device held still at a true roll of 0 deg
BIAS, DT, TAU, STEPS = 0.5, 0.01, 0.5, 1000          # deg/s, s, s, 10 s of samples
alpha = TAU / (TAU + DT)
gyro_only = fused = 0.0
for _ in range(STEPS):
    gyro_only += BIAS * DT
    fused = alpha * (fused + BIAS * DT) + (1 - alpha) * 0.0   # accelerometer angle = 0 deg (still)
print(f"alpha = {alpha:.4f}")
print(f"after 10 s: gyro only {gyro_only:.2f} deg, fused {fused:.2f} deg")
print(f"steady-state fused error = {BIAS * TAU:.2f} deg")

# 2) blending a heading near the +-180 deg seam
def wrap(x):
    return x - 360 * math.floor((x + 180) / 360)

pred, meas = 179.0, -179.0                             # same direction, 2 deg apart on the circle
naive = alpha * pred + (1 - alpha) * meas
safe = wrap(pred + (1 - alpha) * wrap(meas - pred))
print(f"naive blend {naive:.2f} deg, wrapped blend {safe:.2f} deg")
alpha = 0.9804
after 10 s: gyro only 5.00 deg, fused 0.25 deg
steady-state fused error = 0.25 deg
naive blend 171.98 deg, wrapped blend 179.04 deg

The gyro alone drifts 5° in 10 seconds, while the filter settles at an error of = 0.25° because the accelerometer keeps pulling it back. Averaging 179° and −179° directly gives 171.98°, which is 7° off although the two values differ by only 2° on the circle. Take the difference across the seam first () and then weight it, which gives 179.04°. The same care applies when you compute a rotation rate from two heading values. Also, the accelerometer is wrong when the vehicle accelerates, so must suit the task.

Module lab

Lab: IMU and compass calibration

  1. Calibrate the accelerometer in six positions with Mission Planner or QGroundControl, then read the offsets and scales it produces.
  2. Record raw readings in the six positions yourself, compute them with the code from Example 1 and compare with the software.
  3. Leave the IMU still for at least an hour, record the gyro and compute the Allan deviation with a library such as AllanTools to find ARW and bias instability.
  4. Rotate the compass board all the way round, record mx and my, and use the code from Example 2 to find the hard iron.
  5. Place a steel screwdriver near the compass, observe how the circle changes and record it in the lab notebook.

Common mistakes

Watch out

  • Moving the airframe during six-position calibration.
  • Calibrating the compass near steel structures or cars.
  • Mounting the compass near high-current wiring.
  • Relying on a single datasheet value instead of measuring.
  • Not recalibrating after moving equipment.

Summary

  • MEMS IMUs have bias, scale factor and noise errors.
  • Six-position calibration finds bias and scale factor from ±g on every axis.
  • Allan deviation separates angle random walk and bias instability from at-rest data.
  • Hard iron shifts the centre of the compass data circle and can make heading badly wrong; calibrate and watch for interference.

Check your understanding

  1. An axis reads +9.90 and −9.70 m/s². What is the bias?
  2. From question 1, what is the scale factor (g = 9.80665)?
  3. What noise type does the −1/2 slope region of an Allan deviation plot represent?
  4. mx ranges from −20 to 40 µT. What is the hard-iron offset on this axis?
  5. How do hard iron and soft iron change the shape of compass data differently?
Answers
  1. m/s²
  2. White noise, read as angle random walk.
  3. µT
  4. Hard iron shifts the circle’s centre; soft iron stretches the circle into an ellipse.

Key formulas

Per-axis error model
Six-position calibration
Hard-iron centre

Key references

  1. AHRS developers. Complementary filter. AHRS: Attitude and Heading Reference Systems documentation. link
  2. Groves, P. D. (2013). Principles of GNSS, inertial, and multisensor integrated navigation systems (2nd ed.). Artech House. link
  3. TDK InvenSense. ICM-42688-P high precision 6-axis MEMS motion sensor (Datasheet DS-000347). link
  4. Freescale Semiconductor. (2015). Allan variance: Noise analysis for gyroscopes (Application Note AN5087, Rev. 0). link
  5. El-Sheimy, N., Hou, H., & Niu, X. (2008). Analysis and modeling of inertial sensors using Allan variance. IEEE Transactions on Instrumentation and Measurement, 57(1), 140–149. link
  6. IEEE. (2019). IEEE standard specification format guide and test procedure for linear single-axis, nongyroscopic accelerometers (IEEE Std 1293-2018). link
  7. ArduPilot Dev Team. Accelerometer calibration. ArduPilot Copter documentation. link
  8. ArduPilot Dev Team. Advanced compass setup (CompassMot). ArduPilot Copter documentation. link
  9. NOAA National Centers for Environmental Information. (2024). The World Magnetic Model (WMM2025). link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

AvailableD04D06

IMU ไจโรสโคป แอกเซเลอโรมิเตอร์ และแมกนีโตมิเตอร์

MEMS principles, bias, noise, vibration and calibration
AvailableD05

Applied level: reading an IMU, fusing data and communicating on time

Choose I2C, SPI or UART for Arduino/ESP32 before reading an IMU, check units and timing, understand sensor fusion, and design messages that can detect stale and dropped data.
AvailableD05

Complementary filter: from angular rate to a fused angle

Practise a one-axis complementary filter, separating rotation rate from angle, checking dt and alpha, with a worked example, a worksheet, answers and the limits of simulated data.
AvailableD05

Angle wrap at ±180°: reading differences and fusing on a circle

Practice shortest-path angle differences, wrap, and one-axis angle adjustment, with exercises, answers, a photorealistic image, and diagrams, separating mathematical direction from actual motion.
AvailableD05

Continuous angle and angular rate: reading a log that crosses the boundary

Practise unwrapping angles over time, calculate the average rotation rate from the real dt, and check ambiguity when data are missing, with examples, worksheets, answers, images and diagrams
AvailableD05

Accumulating angle from a gyro: use the real dt and read the effect of bias

Practise integrating a single-axis rotation rate using the real time intervals, compare the hold-start value with the trapezoid, and read the angle accumulated from bias, with worksheets, answers, images and diagrams.

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Sensors and embedded systems · Control, autopilot and navigation · Aircraft, structures and design