Tilt compass on an Arduino Mega
An MPU-9250 on a Mega reads which way is down and which way is north: the accelerometer and the AK8963 compass through the bypass. The whole build, an Arduino Mega and 1 more part, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Intermediate About 20 minutes to build and run. Runs in your browser. Free, and no account needed.
The parts retail for about $56. On Mokxi they're free.
What you'll learn
- Accelerometer and magnetometer in one chip
- Computing pitch and roll with atan2()
- A compass bearing from magnetic field readings
- Why tilting the board changes the heading
- I2C and reading a chip's ID
- Difficulty: Intermediate
- Time: About 20 minutes
- Board: Arduino Mega 2560 R3
- Parts: 3
How it works
The MPU-9250 has two devices in one chip. The accelerometer feels gravity, so it shows which way is down. A magnetometer behind it feels the Earth's field, which points north. Both talk over I2C on SDA and SCL, on a Mega.
Every half second the sketch turns the accelerometer values into pitch and roll angles, and the magnetometer into a direction in degrees. It prints all three. The direction only means a true compass heading when the board is level.
Parts list
3 parts, plus the jumper wires. They retail for about $56; on Mokxi they're free.
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| Nine-axis IMU, MPU-9250 pin SCL | Arduino Mega 2560 R3 pin SCL |
| Nine-axis IMU, MPU-9250 pin SDA | Arduino Mega 2560 R3 pin SDA |
| Nine-axis IMU, MPU-9250 pin GND | Arduino Mega 2560 R3 pin GND |
| Nine-axis IMU, MPU-9250 pin VCC | 5 V |
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Tilt compass: an MPU-9250 reads which way is down and which way is north,
// with asukiaaa's MPU9250 library, on a Mega: the library's floating point
// and atan2() take more flash than an Uno example is allowed.
//
// MPU-9250 SDA -> SDA, SCL -> SCL, VCC -> 5 V, GND -> GND
//
// Inside the chip are two devices. The accelerometer and gyroscope answer
// at 0x68, like an MPU6050. The AK8963 magnetometer sits behind them, and
// beginMag() sets the bypass bit so it answers at 0x0C on the same two
// wires. The accelerometer gives the tilt; the magnetometer gives the
// Earth's field, whose horizontal part points north.
//
// magHorizDirection() is atan2 of the magnetometer's X and Y: the angle of
// north from the chip's own axes, which only means a compass bearing while
// the board is held level.
//
// Things to try. Drag the heading slider and watch the direction follow.
// Then tip the board: the tilt changes and so does the direction, because
// the field also points down into the ground. A tilt-compensated compass
// uses the accelerometer to undo that.
#include <Wire.h>
#include <MPU9250_asukiaaa.h>
MPU9250_asukiaaa imu;
void setup() {
Serial.begin(9600);
Wire.begin();
imu.setWire(&Wire);
uint8_t id = 0;
imu.readId(&id);
Serial.print("WHO_AM_I 0x");
Serial.println(id, HEX);
imu.beginAccel(ACC_FULL_SCALE_2_G);
imu.beginMag();
}
void loop() {
if (imu.accelUpdate() == 0) {
float pitch = atan2(-imu.accelX(), imu.accelZ()) * 180.0 / PI;
float roll = atan2(imu.accelY(), imu.accelZ()) * 180.0 / PI;
Serial.print("pitch ");
Serial.print((int)lround(pitch));
Serial.print(" roll ");
Serial.print((int)lround(roll));
}
if (imu.magUpdate() == 0) {
Serial.print(" direction ");
Serial.print((int)lround(imu.magHorizDirection()));
}
Serial.println();
delay(500);
}
Code walkthrough
The key functions of the sketch, and what each one does.
setup sketch.ino
Opens the serial port, starts I2C and gives the library the Wire bus. It reads the chip's ID and prints it as WHO_AM_I. Then imu.beginAccel starts the accelerometer at plus or minus 2 g, and imu.beginMag() starts the magnetometer.
void setup() {
Serial.begin(9600);
Wire.begin();
imu.setWire(&Wire);
uint8_t id = 0;
imu.readId(&id);
Serial.print("WHO_AM_I 0x");
Serial.println(id, HEX);
imu.beginAccel(ACC_FULL_SCALE_2_G);
imu.beginMag();
}loop sketch.ino
If the accelerometer updates, it works out pitch and roll with atan2 and prints them in degrees. If the magnetometer updates, it prints magHorizDirection() as the direction. Then it waits 500 ms.
void loop() {
if (imu.accelUpdate() == 0) {
float pitch = atan2(-imu.accelX(), imu.accelZ()) * 180.0 / PI;
float roll = atan2(imu.accelY(), imu.accelZ()) * 180.0 / PI;
Serial.print("pitch ");
Serial.print((int)lround(pitch));
Serial.print(" roll ");
Serial.print((int)lround(roll));
}
if (imu.magUpdate() == 0) {
Serial.print(" direction ");
Serial.print((int)lround(imu.magHorizDirection()));
}
Serial.println();
delay(500);
}Troubleshooting
The usual mistakes with this circuit, and the fix for each.
- The direction changes when you tip the board This project
The heading is only a compass reading when the board is level. Tipping mixes in the field that points down. - No numbers appear This project
Check SDA and SCL, and the 5V and ground on the IMU. Look at the WHO_AM_I line first. - The compass is not found at 0x0C. Nine-axis IMU
The AK8963 sits behind the MPU. Enable BYPASS_EN in the INT_PIN_CFG register (0x37) to talk to it directly. The MPU itself is at 0x68, or 0x69 with AD0 high. - The sensor reads all zeros or noise. Nine-axis IMU
Wake it first by clearing the sleep bit in PWR_MGMT_1. It is a 3.3 V part, so use level shifting on 5 V boards. The compass also needs setup and calibration before heading is trustworthy. - The upload fails or nothing runs. Arduino Mega 2560 R3
Under Tools, choose Arduino Mega or Mega 2560 as the board, then pick the right port. An Uno selection uploads the wrong build. - I2C, SPI, or serial pins are in the Uno spots and do not work. Arduino Mega 2560 R3
On the Mega, SDA is pin 20 and SCL is 21. SPI uses 50 to 53, not 10 to 13. Serial1 to Serial3 are on pins 19 to 14.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.