Tilt angles with an MPU6050
Read acceleration and rotation from an MPU6050 and work out pitch and roll.
Sensors · Intermediate
In a real product: Self-balancing scooter (Consumer electronics): Tilt angles keep the scooter upright.
The MPU6050 combines an accelerometer and a gyroscope. At rest, the accelerometer measures gravity, so the direction it points tells you how the board is tilted. Drones, phones and self-balancing robots all use sensors like this.
What you'll learn
- Reading an I²C sensor with its library (Adafruit MPU6050)
- What an accelerometer measures: gravity plus any acceleration
- Working out pitch and roll with
atan2()
How it works
SDA and SCL go to A4 and A5 (I²C), and the sensor answers at 0x68. mpu.getEvent() fills in the acceleration (in m/s²), the rotation rate (in rad/s) and the chip's temperature.
Lying flat, gravity is all on Z (about 9.8 m/s²). Tip the sensor and some of it moves to X or Y. The angles follow from trigonometry:
pitch = atan2(ax, sqrt(ay² + az²))
roll = atan2(ay, az)
Try this
- Change the sensor's accelX/Y/Z sliders (in g) while it runs and watch the angles.
- Light an LED when the tilt goes past 30°.
- Drive a servo to the pitch angle, as a simple gimbal.
sketch.ino
// An MPU6050 on I2C (A4 = SDA, A5 = SCL): acceleration, rotation, and pitch and roll from gravity.
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
void setup() {
Serial.begin(9600);
if (!mpu.begin()) {
Serial.println("MPU6050 not found");
while (true) delay(10);
}
mpu.setAccelerometerRange(MPU6050_RANGE_2_G);
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
}
void loop() {
sensors_event_t accel, gyro, temp;
mpu.getEvent(&accel, &gyro, &temp);
float ax = accel.acceleration.x, ay = accel.acceleration.y, az = accel.acceleration.z;
float pitch = atan2(ax, sqrt(ay * ay + az * az)) * 180 / PI;
float roll = atan2(ay, az) * 180 / PI;
Serial.print("Accel (m/s2) x: ");
Serial.print(ax, 2);
Serial.print(" y: ");
Serial.print(ay, 2);
Serial.print(" z: ");
Serial.print(az, 2);
Serial.print(" Pitch: ");
Serial.print(pitch, 1);
Serial.print(" Roll: ");
Serial.println(roll, 1);
delay(500);
}