All tutorials

4 · Displays & buses

Compute tilt (roll/pitch)

Expert30 min

Goal

Turn the 3 acceleration axes into tilt angles.

Why it matters

atan2() on the gravity vector gives attitude: the basis of a stabiliser.

Steps

  1. 01Start from the IMU sketch.
  2. 02Compute roll = atan2(ay, az) and pitch = atan2(-ax, √(ay²+az²)).
  3. 03Convert radians to degrees (×57.2958).
  4. 04Filter the result slightly to stabilise it.

Starter sketch

// MPU6050 over I2C — raw register reads, no external library needed.
#include <Wire.h>

const uint8_t MPU = 0x68;

void writeReg(uint8_t reg, uint8_t val) {
  Wire.beginTransmission(MPU);
  Wire.write(reg);
  Wire.write(val);
  Wire.endTransmission();
}

int16_t readWord(uint8_t reg) {
  Wire.beginTransmission(MPU);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, (uint8_t)2);
  int16_t hi = Wire.read();
  int16_t lo = Wire.read();
  return (hi << 8) | lo;
}

void setup() {
  Serial.begin(9600);
  Wire.begin();
  writeReg(0x6B, 0x00);   // wake up
  writeReg(0x1B, 0x00);   // gyro +/- 250 deg/s
  writeReg(0x1C, 0x00);   // accel +/- 2 g
  Serial.println("MPU6050 ready");
}

void loop() {
  float ax = readWord(0x3B) / 16384.0;
  float ay = readWord(0x3D) / 16384.0;
  float az = readWord(0x3F) / 16384.0;
  float gz = readWord(0x47) / 131.0;

  Serial.print("accel ");
  Serial.print(ax); Serial.print(" ");
  Serial.print(ay); Serial.print(" ");
  Serial.print(az);
  Serial.print("  gyroZ ");
  Serial.println(gz);

  delay(300);
}

This tutorial runs inside the Circuitly simulator: your wiring and your code are checked automatically at every step.

Next tutorials