🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

IMU & Motion Sensors: The Drone's Inner Ear

🟢 Free Lesson

What Is an IMU?

Sponsored

An Inertial Measurement Unit (IMU) is like a drone's inner ear — it tells the drone how it's moving through space without needing external references. Just as your inner ear helps you balance and know which way is up, an IMU provides the orientation and motion data a drone needs to stay stable.

A typical drone IMU contains three types of sensors:

  • Accelerometer — measures linear acceleration (how fast speed is changing)
  • Gyroscope — measures angular velocity (how fast it's rotating)
  • Magnetometer — measures magnetic field direction (compass heading)

The 6-Axis IMU

A 6-axis IMU combines a 3-axis accelerometer and a 3-axis gyroscope into a single chip. The 7th and 8th axes come from the magnetometer.

6-Axis IMU ArchitectureIMU ChipMPU-6050 / ICM-20948Accelerometer±2/4/8/16gGyroscope±250-2000°/s16-bit ADCXYZSignal Flow PipelineRaw SensorCalibrationFilterFusionOrientationSensor readingBias/Scale fixNoise reduceCombine dataEuler anglesX (Roll)Y (Pitch)Z (Yaw)

Axis Frames and Mounting Conventions

An IMU reports motion in its own chip frame, which rarely matches the frame your flight controller expects. Most flight stacks use a forward-right-down body frame: X points out of the nose, Y out of the right wing, Z toward the ground. Consumer chips such as the ICM-20948 mark their axes with a silkscreen arrow on the package, and a right-hand rule fixes the sign of every rotation — thumb along the positive axis, fingers curl the way a positive angular rate is reported.

Two mounting mistakes show up immediately in a flight log. Rotate the chip 90° about Z and roll commands appear as pitch responses, so the estimator spends the whole flight fighting a sign error it can never resolve. Mount it upside down and both vertical acceleration and yaw invert, so the vehicle climbs where the controller commands a descent. Sketch the mounting on paper, tilt the board by hand in each axis, and confirm the log agrees before the propellers go on.

Accelerometer Deep Dive

An accelerometer measures proper acceleration — the acceleration relative to freefall. When sitting on a table, it reads +9.81 m/s² upward (countering gravity). Think of it like the feeling you get in an elevator: you feel heavier accelerating up, lighter when accelerating down.

Key characteristics:

  • Great for detecting gravity direction (tilt sensing)
  • Noisy during fast movements (motor vibrations)
  • Drift-free over long periods for gravity reference
python

# Simulated accelerometer reading
ax, ay, az = 0.12, -0.05, 9.78  # m/s²

# Calculate roll and pitch from accelerometer
roll = np.arctan2(ay, az)   # ~ -0.005 rad (-0.3°)
pitch = np.arctan2(-ax, np.sqrt(ay**2 + az**2))  # ~ 0.012 rad (0.7°)

print(f"Roll:  {np.degrees(roll):.1f}°")
print(f"Pitch: {np.degrees(pitch):.1f}°")

Gyroscope Deep Dive

Sponsored

A gyroscope measures how fast something is spinning around each axis. Think of a spinning top — the faster it spins, the higher the angular velocity reading. Unlike the accelerometer, gyroscopes are clean during fast motion but slowly drift over time due to bias errors.

Key characteristics:

  • Excellent for short-term rotation tracking
  • Low noise during dynamic maneuvers
  • Suffers from bias drift (integrates error over time)
python
# Simulated gyroscope reading (degrees per second)
gx, gy, gz = 15.2, -3.8, 0.5  # °/s

# Integrate to get angle change over dt
dt = 0.01  # 100Hz sampling
angle_change = gz * dt  # 0.005° around Z-axis

print(f"Yaw rate: {gz}°/s")
print(f"Angle change in {dt}s: {angle_change:.4f}°")

Magnetometer: The Digital Compass

The magnetometer detects Earth's magnetic field to provide heading information. It's like a compass in your phone — it tells you which direction you're facing. However, it's sensitive to nearby metal objects and electromagnetic interference from motors.

Two distortion sources dominate in practice. Hard-iron distortion comes from material that is magnetized and fixed to the airframe, so it simply offsets the measured field. Against a 50 µT ambient field, a 10 µT offset from a battery lead sitting close to the sensor produces a heading error of about arctan(10 ÷ 50), which is 11°, and the error is worst on east and west headings while north and south barely move. Soft-iron distortion comes from induced magnetization and warps the reading into an ellipse rather than a circle, so the error varies continuously as the drone yaws. Field calibration means rolling and pitching the airframe through a full circle on site and fitting offset and scale to the captured points; run it again whenever the battery, mounting position, or payload changes.

Calibration: Where the Error Actually Comes From

Two static errors dominate a raw IMU reading, and both are cheap to remove. A bias is what the sensor reports when the true input is zero — on a resting accelerometer it shows up as a small offset from 9.80665 m/s². A scale-factor error makes the reading grow too fast or too slow as the input increases.

The standard procedure is six-position calibration: hold each face of the drone steady against a level surface, average a few hundred samples per face, then solve for the offset and scale of each axis. Worked numbers make the stakes clear. If the vertical axis reports 9.78 m/s² instead of 9.80665 m/s² while the drone sits level, the 0.027 m/s² bias tilts your computed pitch and roll by arctan(0.027 ÷ 9.80665) — about 0.16°. Small on the bench, but the same bias contaminates horizontal acceleration, so every second of integrated velocity picks up an extra 0.027 m/s² of phantom drift.

python
# Six-position accelerometer calibration (vertical axis, level surface)
REST_G = 9.80665
level_readings = [9.74, 9.79, 9.81, 9.77, 9.80, 9.78]  # six repeats

bias = REST_G - np.mean(level_readings)          # +0.037 m/s^2
scale = 1.0                                       # set from ±1 g readings

def calibrated(raw, bias, scale):
    return (raw - bias) / scale

print(f"Static bias: {bias:.4f} m/s^2")
print(f"Residual tilt: {np.degrees(np.arctan2(bias, REST_G)):.2f} deg")

Sensor Fusion: Combining the Best of Each

No single sensor is perfect. Sensor fusion combines all three to get the best estimate:

SensorStrengthWeakness
AccelerometerStable long-term (gravity)Noisy during motion
GyroscopeClean during motionDrifts over time
MagnetometerProvides headingSensitive to interference
Complementary Filter FusionGyroscopeHigh-freq accurateAccel + MagLow-freq stableIntegrate∫ω dtLow-PassLP filterBlendα·gyro + (1-α)·accOrientationRoll, Pitch, YawFilter Parameter α (alpha)α ≈ 0.96–0.98 → Trust gyro more (smooth but drifts)α ≈ 0.80–0.90 → Trust accelerometer more (noisy but stable)

Complementary Filter

The complementary filter is a simple yet effective fusion approach. It uses a high-pass filter on gyroscope data (trust gyro for fast changes) and a low-pass filter on accelerometer data (trust accel for slow/steady changes).

python
class ComplementaryFilter:
    def __init__(self, alpha=0.96):
        self.alpha = alpha
        self.angle = 0.0

    def update(self, gyro_angle, accel_angle, dt):
        # High-pass on gyro (fast response), low-pass on accel (drift correction)
        self.angle = self.alpha * (self.angle + gyro_angle * dt) + \
                     (1 - self.alpha) * accel_angle
        return self.angle

# Usage
filter = ComplementaryFilter(alpha=0.96)
for gyro, accel in zip(gyro_readings, accel_readings):
    angle = filter.update(gyro, accel, dt=0.01)

Kalman Filter: The Gold Standard

Advertisement

The Kalman filter is more sophisticated — it maintains an estimate of the state and its uncertainty, then optimally combines predictions with measurements.

Kalman Filter: Predict → Update CyclePREDICTx̂⁻ = A·x̂ + B·uP⁻ = A·P·Aᵀ + QUsing gyroscope inputstepUPDATEK = P⁻·Hᵀ·(H·P⁻·Hᵀ+R)⁻¹x̂ = x̂⁻ + K·(z - H·x̂⁻)Correct with accelerometerNext timestepx̂ = state estimate | P = error covariance | K = Kalman gain | Q = process noise | R = measurement noiseA = state transition | B = control input | H = measurement model | z = measurement

When to Use Each Filter

FilterComplexityCPU UsageAccuracyBest For
ComplementaryLowVery LowGoodSimple drones, resource-limited
MadgwickMediumLowVery GoodMost drone applications
KalmanHighMediumExcellentPrecision navigation, GPS-denied

The table assumes a comparable sample rate. On a 168 MHz flight controller a complementary filter costs a few microseconds per cycle, while a full error-state Kalman filter with a 15-state vector and matrix inversions can consume several percent of the loop budget at 1 kHz — enough to matter if the same chip also runs the motor mixer and the radio stack.

Sampling Rate, Bandwidth, and Vibration Aliasing

Propellers are the loudest signal an onboard IMU will ever see. A 5-inch prop spinning at 25,000 RPM completes 417 revolutions per second, and with two blades it pushes air at 833 Hz. Sampling the chip at 100 Hz cannot resolve that: everything above the 50 Hz Nyquist limit folds back into the band you actually use, so motor vibration masquerades as attitude change and the filter dutifully believes it.

The first line of defence is analogue, not digital. Consumer IMUs carry a low-pass filter in front of the converter; set its configuration register so the corner sits near 42 Hz, keep the internal output rate at 1 kHz, and sample at 200 Hz so the filter has room to settle between reads. Decision rule: place the corner 2–3 times above your attitude controller bandwidth — roughly 20–30 Hz on a 5-inch quad — and never higher, because anything above the corner arrives as noise and anything below it eats phase margin you need for damping.

Datasheet Numbers That Predict Flight Performance

Range and resolution dominate the marketing page and say almost nothing about attitude accuracy. These five specifications do, with typical values for a consumer MEMS part such as the BMI088 or the ICM-42688:

SpecificationTypical valueWhy it matters in flight
Rate noise density2.8–5 mdps/√HzSets gyro RMS noise once bandwidth is chosen
Angle random walk0.2–0.5 °/√hConverts rate noise into slow heading drift
Zero-rate offset±0.05 °/s at 25 °CIntegrates directly into yaw error
Bias instability1–10 °/hFloor that no software filter can remove
Cross-axis sensitivity±1 %Couples motion on one axis into another

Multiply noise density by the square root of the chosen bandwidth to get the noise you will actually see. A 4 mdps/√Hz part filtered to a 50 Hz band yields about 0.028 °/s of RMS rate noise, which integrates to 0.28° of heading error over a ten-second GPS outage. Bias instability is the number that ends the argument: once the estimator has averaged away the random noise, whatever the bias wanders by during that window is the best heading you can ever claim.

Hands-On Project: IMU Data Logger

Build a basic IMU data logger using an MPU-6050 sensor with Raspberry Pi Pico:

python
from machine import I2C, Pin

class MPU6050:
    def __init__(self, i2c, addr=0x68):
        self.i2c = i2c
        self.addr = addr
        # Wake up sensor
        self.i2c.writeto_mem(self.addr, 0x6B, b'\x00')
        # Set accelerometer range ±2g
        self.i2c.writeto_mem(self.addr, 0x1C, b'\x00')
        # Set gyroscope range ±250°/s
        self.i2c.writeto_mem(self.addr, 0x1B, b'\x00')

    def read_accel(self):
        data = self.i2c.readfrom_mem(self.addr, 0x3B, 6)
        ax, ay, az = struct.unpack('>hhh', data)
        return ax/16384.0, ay/16384.0, az/16384.0

    def read_gyro(self):
        data = self.i2c.readfrom_mem(self.addr, 0x43, 6)
        gx, gy, gz = struct.unpack('>hhh', data)
        return gx/131.0, gy/131.0, gz/131.0

# Initialize
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
mpu = MPU6050(i2c)

# Log data for 10 seconds
print("timestamp,ax,ay,az,gx,gy,gz")
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < 10000:
    ax, ay, az = mpu.read_accel()
    gx, gy, gz = mpu.read_gyro()
    t = time.ticks_diff(time.ticks_ms(), start) / 1000.0
    print(f"{t:.3f},{ax:.3f},{ay:.3f},{az:.3f},{gx:.1f},{gy:.1f},{gz:.1f}")
    time.sleep_ms(10)

Project Extensions:

  1. Add a simple complementary filter to compute real-time tilt
  2. Log data to SD card for post-flight analysis
  3. Visualize live data using a web dashboard
  4. Compare raw vs filtered readings during aggressive maneuvers

Common Mistakes

Flying with factory-default sensor settings and then blaming the estimator for a drifting hover

Fix: Run the six-position accelerometer calibration and a resting gyro bias check on every battery, then store the offsets in persistent storage.

Trusting a compass heading that was calibrated beside different equipment or after a payload change

Fix: Recalibrate the magnetometer on site after every airframe change and check heading against GPS course while hovering.

Averaging a heavily vibrating board instead of filtering it, then raising the filter gain to hide the noise

Fix: Lower the hardware low-pass corner to about 42 Hz, sample at 200 Hz, and mount the board on damping foam so vibration is attenuated before it reaches the sensor.

Key Takeaways

  • An IMU provides 6-DOF motion sensing (accelerometer + gyroscope)
  • Accelerometers are stable long-term but noisy; gyroscopes are clean but drift
  • Sensor fusion combines strengths of each sensor for accurate orientation
  • Start with a complementary filter; upgrade to Kalman/Madgwick for precision
  • Calibration (bias removal) is essential before any filtering
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Drone AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement