All articles

    The MPU6050: Measuring Tilt and Motion with an Accelerometer and Gyroscope

    The MPU6050 (GY-521) module explained: accelerometer vs gyroscope, I2C wiring and address 0x68, reading the sensor without a library and converting to real units, calculating tilt, drift and a complementary filter with complete code and calibration, yaw, ranges and the internal filter, and troubleshooting.

    Updated 7 min read

    Your phone knows when you turn it sideways, a drone stays level in the air, and a balancing robot stands on two wheels. Behind all of these is the same idea: a motion sensor. And the most popular one in hobby projects is the MPU6050 on the GY-521 module.

    The accelerometer measures tilt, and the gyroscope measures rotation speed
    The accelerometer measures tilt, and the gyroscope measures rotation speed

    Two sensors inside

    SensorMeasuresStrengthsWeaknesses
    AccelerometerAcceleration (and from it, the direction of gravity)Gives the true tilt over the long termConfused by vibration and movement
    GyroscopeRotation speed (degrees per second)Fast and smooth"Drifts" over time

    Each one measures on 3 axes (X, Y and Z), so the sensor is called 6-axis (6-DOF). The chip also has a small temperature sensor, but that measures the chip's own temperature, not the air.

    Wiring (I2C)

    GY-521Arduino Uno
    VCC5V (the module has a regulator)
    GNDGND
    SCLA5
    SDAA4
    • The address is 0x68, and if you tie the AD0 pin HIGH it becomes 0x69. So you can put two sensors on the same bus.
    • With an ESP32 the default pins are SDA = 21 and SCL = 22.
    • Make sure your module has a regulator before connecting it to 5 V. See I2C.
    • The INT pin outputs a pulse when a new reading is ready, useful with interrupts if you want precise timing.

    From raw numbers to units

    The sensor returns integers from −32768 to 32767. To convert them to real units, divide by the sensitivity of the range you're on:

    Accelerometer rangeDivide byGyro rangeDivide by
    ±2g (default)16384±250 °/s (default)131
    ±4g8192±500 °/s65.5
    ±8g4096±1000 °/s32.8
    ±16g2048±2000 °/s16.4

    So with the sensor lying flat on the table on the ±2g range, the Z axis reads about 16384 (that's 1g, gravity), and X and Y are close to zero.

    Calculating tilt from the accelerometer

    While the sensor is still, the accelerometer measures only gravity. So from the ratio of the values on each axis you get the angle:

    float pitch = atan2(ax, sqrt(ay*ay + az*az)) * 180.0 / PI;
    float roll  = atan2(ay, az) * 180.0 / PI;

    This works well as long as the sensor isn't vibrating or accelerating. As soon as it moves, the acceleration of the movement itself adds to gravity, and the angle jumps.

    Combining the two: a complementary filter

    The classic solution: use the gyro for fast changes, and the accelerometer to slowly correct the drift:

    angle = 0.98 * (angle + gyroRate * dt) + 0.02 * accelAngle;
    • gyroRate in degrees per second from the gyro.
    • dt is the time since the last reading in seconds (calculate it with micros()).
    • The 0.98 and 0.02 ratio is tuned for each project: the larger the first, the smoother the angle but the slower the drift correction.

    Complete code without a library

    This code wakes the sensor, calibrates the gyro, and prints the fused roll angle:

    #include <Wire.h>
    const int MPU = 0x68;
    float angle = 0, gyroOffset = 0;
    unsigned long last;
    
    int16_t read16() { int16_t h = Wire.read(); return (h << 8) | Wire.read(); }
    
    void readMPU(int16_t &ay, int16_t &az, int16_t &gx) {
      Wire.beginTransmission(MPU);
      Wire.write(0x3B);                 // first data register
      Wire.endTransmission(false);
      Wire.requestFrom(MPU, 10);
      read16(); ay = read16(); az = read16();   // ax not needed here
      read16();                                 // temperature
      gx = read16();
    }
    
    void setup() {
      Serial.begin(115200);
      Wire.begin();
      Wire.beginTransmission(MPU);
      Wire.write(0x6B); Wire.write(0);  // wake the sensor (it starts asleep)
      Wire.endTransmission();
      delay(100);
      long sum = 0; int16_t ay, az, gx;
      for (int i = 0; i < 500; i++) { readMPU(ay, az, gx); sum += gx; delay(2); }
      gyroOffset = sum / 500.0;         // calibration: the sensor must be still
      angle = atan2((float)ay, (float)az) * 180.0 / PI;
      last = micros();
    }
    
    void loop() {
      int16_t ay, az, gx;
      readMPU(ay, az, gx);
      unsigned long now = micros();
      float dt = (now - last) / 1e6; last = now;
      float acc  = atan2((float)ay, (float)az) * 180.0 / PI;
      float rate = (gx - gyroOffset) / 131.0;   // degrees/second on the ±250 range
      angle = 0.98 * (angle + rate * dt) + 0.02 * acc;
      Serial.println(angle);
      delay(5);
    }

    Open the Serial Plotter in the Arduino IDE instead of the Monitor, and you'll see the angle as a curve. Try printing acc beside it and move the sensor quickly: acc jumps around while the fused angle stays smooth.

    Notice that we started angle from the accelerometer reading instead of zero; otherwise the filter takes seconds to reach the real angle.

    For more accurate results there's the Kalman filter, or the DMP inside the chip itself with dedicated libraries, which outputs ready-made angles.

    Yaw: rotation around the vertical axis

    Pitch and roll are corrected by gravity, but rotation around the vertical axis (yaw, like turning a compass) doesn't change gravity, so nothing corrects the gyro's drift. You'll find yaw drifting by degrees every minute. If you need a true heading, you need magnetic sensing (a sensor such as the MPU9250 or a separate compass module) or a sensor with built-in fusion.

    Detecting a fall or an impact

    You don't need angles to know something fell. Calculate the total acceleration magnitude from the three axes:

    float g = sqrt(ax*ax + ay*ay + az*az) / 16384.0;   // in g on the ±2g range

    While the sensor is still or moving normally, this number is about 1 (just gravity) whatever its orientation. While it's falling, it approaches zero (free fall). And at the moment of impact it spikes high (2 or 3g and more). So a fall = a short period near zero followed by a spike. The same idea counts steps: each step makes a small wave above and below 1g, and you count the peaks. If you want to log impacts with their time, see the SD card logging article.

    Tips

    • Calibration: with the sensor still on a level surface, average the gyro readings and subtract them (the offset), as in the code above. Repeat it at every start-up, because the offset changes with temperature.
    • Range: choose the smallest range that's enough (±2g and ±250 °/s) for the best resolution. A balancing robot doesn't need ±16g.
    • The internal filter (DLPF): the chip has a filter you set in register 0x1A that reduces jitter at the cost of a small delay. Very useful if there are motors.
    • Vibration: mount the sensor firmly; motors cause mechanical noise. You may need a foam mount.
    • Wiring: keep the I2C wires short, and away from the motor wires.
    • The original chip is old and many modules on the market are clones. For a new project, consider newer alternatives such as ICM or BMI sensors.

    Not working?

    • All readings are zero or frozen: you forgot to wake the sensor (register 0x6B), so it's still asleep.
    • The scanner doesn't find it: SDA and SCL wiring, the supply, or the address became 0x69 because AD0 is connected. See the I2C troubleshooting article.
    • The program freezes after a while: a long I2C wire or motor noise hangs the bus. Shorten the wires, and add a capacitor on the module's supply.
    • The angle is reversed or on the wrong axis: the sensor's mounting orientation. Swap the axis or invert the sign in the code.

    Uses

    Balancing robots, gimbals, tilt control, step counting, and detecting a fall or impact. And if you're building a robot, driving the motors is in the DC motor and H-bridge article.

    Circuits Nerd
    © 2026 Circuits Nerd. All rights reserved.