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.
What you need
- Arduino UNO board
- Piezo buzzer
- MPU6050 IMU
Nothing to buy: every component below is simulated in the browser.
Steps
- 01Start from the IMU sketch.
- 02Compute roll = atan2(ay, az) and pitch = atan2(-ax, √(ay²+az²)).
- 03Convert radians to degrees (×57.2958).
- 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.
Frequently asked questions
- Do I need to buy hardware for this tutorial?
- No. Everything runs in the browser: Circuitly simulates the board, the components and the code. Real hardware is optional if you want to rebuild the circuit afterwards.
- Which components are used?
- Arduino UNO board, Piezo buzzer, MPU6050 IMU. They are already available in the simulator library.
- How long does it take?
- About 30 minutes, expert level, in 4 guided steps.
- What should I know before starting?
- The previous tutorial in the series, “MPU6050 inertial unit”, is enough preparation. No software install is required.
- Is the code provided and checked?
- Yes: a starter sketch is provided, and the simulator checks your wiring and your code automatically at every step.
For teachers
Get the teaching pack: 6 ready-to-run sessions
Full progression, objectives, student steps and an assessment grid — printable, free.
One address, no spam: just the pack and classroom updates.