MPU-6050: how to measure tilt and rotation
The MPU-6050 is an inertial measurement unit (IMU). It contains a 3-axis accelerometer that measures acceleration, including gravity. It also contains a 3-axis gyroscope that measures the speed of rotation, and a temperature sensor. The MPU-6050 sends data to the ESP32 through I²C. If you use only one sensor to calculate an angle, the result has errors. If you combine the two sensors, you get a steady, accurate tilt. Balancing robots, drones and motion game controllers use this principle.

Photo: Nevit Dilmen, CC BY-SA 3.0
6050
| Axis | Raw (int16) | Value |
|---|---|---|
| aX | 0 | 0.000 g |
| aY | 0 | 0.000 g |
| aZ | 0 | 1.000 g |
| gX | 0 | 0.0 °/s |
| gY | 0 | 0.0 °/s |
| gZ | 0 | 0.0 °/s |
1 LSB = 0.061 mg · 0.0076 °/s
How the sensors work
Accelerometer: a gravity sensor
Very small spring structures in the chip measure force along X, Y and Z. If the board is flat and stationary, it shows about +1 g on Z and 0 on X and Y. If you tilt the board, gravity divides between the axes, so when the board is stationary, you can calculate the tilt:
roll = atan2(aY, aZ)pitch = atan2(−aX, √(aY² + aZ²))
Other movement, for example shaking or acceleration, adds to the reading and looks like tilt, so that line has noise.
Gyroscope: rotation speed
The gyro gives the angular velocity in °/s. This is the speed at which the board turns. To get an angle, add (integrate) the rate over time:
angle += rate × dt. The result is smooth and shaking has no effect on it. But each small error in the rate adds to the total,
so the angle slowly drifts. Calibration decreases the drift, but it cannot remove it.
Complementary filter
Use the gyro for fast changes. Use the accelerometer to slowly move the result back to the true angle:
angle = α·(angle + gyro·dt) + (1−α)·accelAngle
With α ≈ 0.98 at 100 Hz, the accelerometer corrects the drift in about half a second. Set high vibration and a large gyro bias. Then move the α slider and look at the result.
16-bit readings & ranges
Each axis is a signed 16-bit number (−32768…32767). The range setting sets the span of these numbers. At ±2 g, 1 g = 16384 counts. At ±16 g, you can measure hard impacts, but each count is 8× larger. The Quantization page shows the same balance between bits and resolution.
Yaw needs one more sensor
If you turn the board flat on a table (yaw, about Z), gravity does not change, so the accelerometer cannot measure yaw. Only the gyro can measure it, and the gyro drifts. A magnetometer (compass) corrects this problem. Use the MPU-9250 or a separate magnetometer chip.
Filters & interrupts
The chip has a built-in digital low-pass filter (DLPF). You can set its bandwidth from about 260 Hz down to 5 Hz. The DLPF decreases vibration noise. The INT pin can send a signal for “new data ready” or for motion, so you do not have to poll the chip.
Wiring (GY-521 breakout)
Pins
| GY-521 | ESP32 | Purpose |
|---|---|---|
| VCC | 3V3 | Power (usually, the board can use 3.3–5 V) |
| GND | GND | Ground |
| SCL | GPIO 22 | I²C clock (Arduino default) |
| SDA | GPIO 21 | I²C data (Arduino default) |
| AD0 | GND / open | Address 0x68. For 0x69, connect AD0 to 3.3 V (two sensors on one bus). |
| INT | any GPIO | Optional interrupt for data ready or motion |
| XDA, XCL | — | Auxiliary I²C bus for an external magnetometer |
Build steps
- Solder the headerSolder the header onto the GY-521. Loose push-fit pins cause most “sensor not found” errors.
- Connect the four main pinsThen run an I²C scanner sketch. Make sure that it shows a device at
0x68. - Install the libraryLibrary Manager → Adafruit MPU6050 (the library also installs Adafruit Unified Sensor and BusIO).
- Attach the board tightlyAttach the board to your project and put labels on the axes. Calibrate when the board is stationary.
Code
1 · Adafruit library
mpu6050_basic.ino
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
void setup() {
Serial.begin(115200);
Wire.begin(21, 22); // SDA, SCL
if (!mpu.begin()) { // default address 0x68
Serial.println("MPU6050 not found - check wiring");
while (true) delay(10);
}
mpu.setAccelerometerRange(MPU6050_RANGE_4_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ); // built-in low-pass filter
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
// acceleration in m/s^2, rotation in rad/s, temperature in °C
Serial.printf("a: %6.2f %6.2f %6.2f g: %6.2f %6.2f %6.2f T: %.1f\n",
a.acceleration.x, a.acceleration.y, a.acceleration.z,
g.gyro.x, g.gyro.y, g.gyro.z, temp.temperature);
delay(100);
}
2 · Raw registers with Wire (no library)
This sketch shows what the library does. It starts the chip, then reads 14 bytes from register 0x3B.
mpu6050_raw.ino
#include <Wire.h>
const uint8_t MPU = 0x68;
int16_t read16() {
uint8_t hi = Wire.read(); // read the two bytes in two separate statements.
uint8_t lo = Wire.read(); // C++ does not set the order inside one expression.
return (int16_t)((hi << 8) | lo);
}
void setup() {
Serial.begin(115200);
Wire.begin(21, 22);
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1
Wire.write(0x00); // clear the SLEEP bit to start the chip
Wire.endTransmission();
}
void loop() {
Wire.beginTransmission(MPU);
Wire.write(0x3B); // ACCEL_XOUT_H: the first data register
Wire.endTransmission(false); // repeated start
Wire.requestFrom(MPU, (uint8_t)14);
int16_t ax = read16(), ay = read16(), az = read16();
int16_t t = read16();
int16_t gx = read16(), gy = read16(), gz = read16();
// Default values after a reset: ±2 g and ±250 °/s
Serial.printf("aX %.3f g aY %.3f g aZ %.3f g gX %.1f dps T %.1f C\n",
ax / 16384.0, ay / 16384.0, az / 16384.0,
gx / 131.0, t / 340.0 + 36.53);
delay(100);
}
3 · Calibrated complementary filter (roll & pitch)
mpu6050_filter.ino
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
const float ALPHA = 0.98;
float gyroBiasX = 0, gyroBiasY = 0; // °/s, measured at start-up
float roll = 0, pitch = 0; // degrees
uint32_t lastUs;
void calibrateGyro(int samples) { // keep the sensor STATIONARY while this runs
sensors_event_t a, g, t;
for (int i = 0; i < samples; i++) {
mpu.getEvent(&a, &g, &t);
gyroBiasX += g.gyro.x * RAD_TO_DEG;
gyroBiasY += g.gyro.y * RAD_TO_DEG;
delay(3);
}
gyroBiasX /= samples;
gyroBiasY /= samples;
}
void setup() {
Serial.begin(115200);
Wire.begin(21, 22);
if (!mpu.begin()) { Serial.println("MPU6050 not found"); while (true) delay(10); }
mpu.setFilterBandwidth(MPU6050_BAND_44_HZ);
calibrateGyro(500);
lastUs = micros();
}
void loop() {
sensors_event_t a, g, t;
mpu.getEvent(&a, &g, &t);
uint32_t now = micros();
float dt = (now - lastUs) * 1e-6f;
lastUs = now;
float ax = a.acceleration.x, ay = a.acceleration.y, az = a.acceleration.z;
float accRoll = atan2(ay, az) * RAD_TO_DEG;
float accPitch = atan2(-ax, sqrt(ay * ay + az * az)) * RAD_TO_DEG;
float rateX = g.gyro.x * RAD_TO_DEG - gyroBiasX; // °/s
float rateY = g.gyro.y * RAD_TO_DEG - gyroBiasY;
roll = ALPHA * (roll + rateX * dt) + (1 - ALPHA) * accRoll;
pitch = ALPHA * (pitch + rateY * dt) + (1 - ALPHA) * accPitch;
Serial.printf("roll %6.1f pitch %6.1f\n", roll, pitch);
delay(10); // ~100 Hz
}
The axis directions change with the position of the board. If roll or pitch has the incorrect sign, negate that output angle. Keep the gyro terms and the accelerometer terms the same as each other. To see a live graph of the values, open Tools → Serial Plotter.
Troubleshooting
“MPU6050 not found”
Run an I²C scanner. If the scanner finds no device, examine the solder joints and the power.
Make sure that SDA and SCL are not interchanged. Make sure that your code calls Wire.begin(21, 22).
If the scanner finds the device at 0x69, AD0 is high. Use mpu.begin(0x69). Some low-cost “MPU-6050” boards have a copy chip with a different
WHO_AM_I value. Some libraries do not accept this chip.
Angles drift or jump
If the angles drift, calibrate the gyro biases when the board is stationary. Then increase the accelerometer weight a little (decrease α). If the angles jump near ±90° pitch, roll is not defined there (gimbal lock). For full 3D orientation, use quaternion or sensor-fusion libraries.
Readings with noise
Decrease the DLPF bandwidth. Attach the board tightly (use foam tape on drones). Keep the board away from motors. Calculate the average of some samples. Long I²C wires (> 30 cm) need slower clocks or stronger pull-ups.
Resources
- Adafruit: MPU-6050 6-DoF guideLibrary installation, wiring and examples.
- MPU-6000/6050 register map (PDF)All registers: PWR_MGMT_1 (0x6B), ACCEL_XOUT_H (0x3B), CONFIG/DLPF (0x1A).
- Random Nerd Tutorials: ESP32 + MPU-6050Step-by-step projects with Serial Plotter and a web dashboard.
- Arduino-ESP32 I²C (Wire) APIPins, clock speed and multiple buses.
- QuantizationWhy 16 bits give 65 536 levels, and how the range changes the resolution.
- OLED displayUses the same I²C bus. Show a live tilt indicator.
- Wi-FiSend IMU data to a web page.