Try Embedded

Orientation from 9 axes (MPU9250)

Roll and pitch from the accelerometer, turn rate from the gyroscope, and a heading from the magnetometer hidden behind the MPU9250's I²C bypass.

Sensors · Advanced

In a real product: Drone flight controller (Aerospace and drones): Nine axes give roll, pitch and heading for stable flight.

An MPU9250 is three sensors in one package. The accelerometer feels gravity, so it knows which way is down (roll and pitch). The gyroscope measures how fast it turns. The magnetometer, an AK8963 inside the same package, finds north.

What you'll learn

  • Roll and pitch from gravity with atan2, and why that only works while the board is still
  • That the magnetometer is a separate I²C device, reachable only through the MPU9250's bypass
  • A library's conventions: this one returns every accelerometer and gyro axis negated

How it works

beginMag() wakes the MPU9250, sets BYPASS_EN in its INT_PIN_CFG register so the AK8963 at 0x0C joins the bus, reads the magnetometer's factory sensitivity adjustments (ASA) in its fuse ROM mode, and starts it measuring. Before that an I²C scan finds only 0x68.

Roll is atan2(ay, az) and pitch atan2(-ax, sqrt(ay² + az²)). Because the library negates each axis, the sketch flips them back first. The heading is magHorizDirection(), valid while the board lies flat; a tilted compass needs the roll and pitch to correct it (tilt compensation).

Try this

  • Click the sensor and give it some X acceleration (tilt it): the pitch follows. Then the Y axis for the roll.
  • Set a rotation about Z: the turn rate shows it. Integrate it over time and watch the angle drift: that is why orientation filters combine the gyro with the accelerometer and magnetometer.
  • Scan the bus before and after beginMag() to watch 0x0C appear.

sketch.ino

// An MPU9250: roll and pitch from gravity, the turn rate about Z, and the compass heading from the AK8963 behind the
// I2C bypass, twice a second.
#include <MPU9250_asukiaaa.h>

MPU9250_asukiaaa imu;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  imu.setWire(&Wire);
  uint8_t id;
  imu.readId(&id);
  Serial.print("WHO_AM_I 0x");
  Serial.println(id, HEX);
  imu.beginAccel();
  imu.beginGyro();
  imu.beginMag();
}

void loop() {
  imu.accelUpdate();
  imu.gyroUpdate();
  imu.magUpdate();
  // The library returns each axis negated: flip them back.
  float ax = -imu.accelX(), ay = -imu.accelY(), az = -imu.accelZ();
  float roll = atan2(ay, az) * 180 / PI;
  float pitch = atan2(-ax, sqrt(ay * ay + az * az)) * 180 / PI;
  Serial.print("roll ");
  Serial.print(roll, 1);
  Serial.print(", pitch ");
  Serial.print(pitch, 1);
  Serial.print(", turning ");
  Serial.print(-imu.gyroZ(), 1);
  Serial.print(" deg/s, heading ");
  Serial.println(imu.magHorizDirection(), 0);
  delay(500);
}

Lessons behind it