Learning Goals 5 min
The MPU6050 is the cheapest combo accelerometer + gyroscope — a 6-axis IMU on a tiny breakout. It tells your robot which way is up, how fast it's rotating, and (with a bit of maths) what its tilt angle is. By the end of this lesson you will:
- Wire an MPU6050 over I²C (4 pins) to an Arduino.
- Read raw accelerometer (3 axes) and gyroscope (3 axes) values, and convert them to physical units (g and °/s).
- Compute a tilt angle from the accelerometer alone — and identify why this naive approach is too noisy for balancing.
Warm-Up 10 min
Hardware: MPU6050 breakout (very common and cheap). 4 wires: VCC, GND, SDA, SCL.
What an IMU measures
- Accelerometer: linear acceleration on 3 axes, in m/s² or "g" (1 g = 9.81 m/s²). Includes gravity: at rest, the "up" axis reads ~1 g.
- Gyroscope: angular velocity on 3 axes, in °/s. Tells you how fast you're spinning.
The MPU6050 has built-in temperature sensor too. 6 + 1 = 7 channels of data.
New Concept · Reading + processing 25 min
Wiring
| MPU6050 | UNO |
|---|---|
| VCC | 3.3 V or 5 V (breakout has a regulator) |
| GND | GND |
| SDA | A4 |
| SCL | A5 |
I²C address
Default 0x68. Some modules can be moved to 0x69 by tying the AD0 pin to VCC — useful if you also have a DS3231 RTC (also 0x68) on the same bus.
Library: Adafruit_MPU6050
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
void setup() {
Serial.begin(115200);
Wire.begin();
if (!mpu.begin()) {
Serial.println("# no MPU6050 found");
while (true);
}
mpu.setAccelerometerRange(MPU6050_RANGE_2_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_5_HZ);
}
void loop() {
sensors_event_t a, g, t;
mpu.getEvent(&a, &g, &t);
Serial.print("ax="); Serial.print(a.acceleration.x);
Serial.print(" ay="); Serial.print(a.acceleration.y);
Serial.print(" az="); Serial.print(a.acceleration.z);
Serial.print(" | gx="); Serial.print(g.gyro.x);
Serial.print(" gy="); Serial.print(g.gyro.y);
Serial.print(" gz="); Serial.println(g.gyro.z);
delay(100);
}At rest with the chip flat on the table:
ax,ay≈ 0 m/s²az≈ 9.81 m/s² (gravity straight up)gx,gy,gz≈ 0 (not rotating)
Tilt the chip on its side: az drops, ax or ay rises to ~9.81 (gravity now sideways).
Computing tilt angle from accelerometer
Pitch (rotation about the Y axis):
float pitchDeg = atan2(a.acceleration.x,
sqrt(a.acceleration.y * a.acceleration.y +
a.acceleration.z * a.acceleration.z))
* 180.0 / PI;Roll (rotation about the X axis):
float rollDeg = atan2(a.acceleration.y, a.acceleration.z) * 180.0 / PI;Both work at rest. The instant you move (shake, vibrate, accelerate), the "tilt angle" jumps — because the accelerometer can't tell apart gravity from any other acceleration. So the naive method is noisy under motion.
Why this matters for balancing
A self-balancing robot needs to know its tilt angle 100+ times per second. The accelerometer alone is too noisy. The gyroscope alone drifts (integration error compounds). Tomorrow you'll combine them with a complementary filter — the classic solution.
Worked Example · Tilt visualisation 25 min
Step 1 — wire MPU6050 to UNO
VCC → 3.3 V (or 5 V on a tolerant module), GND, SDA → A4, SCL → A5.
Step 2 — verify with the I²C scanner
Use the L03-18 I²C scanner to confirm 0x68 (or 0x69) appears on the bus.
Step 3 — read raw values
Upload the §3 sketch. Watch the values change as you tilt the breakout.
Step 4 — compute tilt
void loop() {
sensors_event_t a, g, t;
mpu.getEvent(&a, &g, &t);
float pitch = atan2(a.acceleration.x,
sqrt(a.acceleration.y * a.acceleration.y +
a.acceleration.z * a.acceleration.z))
* 180.0 / PI;
float roll = atan2(a.acceleration.y, a.acceleration.z) * 180.0 / PI;
Serial.print("pitch="); Serial.print(pitch);
Serial.print(" roll="); Serial.println(roll);
delay(50);
}Step 5 — open the Serial Plotter
Watch pitch and roll graph in real time. Tilt the breakout — the lines move smoothly. Tap the breadboard — they spike (vibration = false acceleration).
Step 6 — calibrate the gyro bias
float gyroOffsetX = 0, gyroOffsetY = 0, gyroOffsetZ = 0;
void calibrateGyro() {
Serial.println("# leave chip still; calibrating...");
long sumX = 0, sumY = 0, sumZ = 0;
const int N = 500;
for (int i = 0; i < N; i++) {
sensors_event_t a, g, t;
mpu.getEvent(&a, &g, &t);
sumX += g.gyro.x * 1000.0;
sumY += g.gyro.y * 1000.0;
sumZ += g.gyro.z * 1000.0;
delay(2);
}
gyroOffsetX = sumX / 1000.0 / N;
gyroOffsetY = sumY / 1000.0 / N;
gyroOffsetZ = sumZ / 1000.0 / N;
Serial.print("# offsets X="); Serial.print(gyroOffsetX);
Serial.print(" Y="); Serial.print(gyroOffsetY);
Serial.print(" Z="); Serial.println(gyroOffsetZ);
}Subtract the offsets from every reading after that. Now the gyro reads ~0 °/s at rest instead of ±2 °/s.
Basic 5 min
Goal: Light an LED when the breakout is tilted more than 30° (pitch or roll). The MPU6050 becomes a tilt switch.
1. Think first (on paper, no typing yet):
- You already work out pitch and roll. In plain English, what test means tilted more than 30° in any direction? Tilt can be negative.
- Which pin will the LED use, and what does it need in setup()?
2. Code it. Open your Step 4 tilt sketch. Add the LED and your test.
3. Upload and observe. Hold the board flat, then tilt it slowly forwards, backwards, left and right. Watch the printed angle as you go.
It works if:
- The LED is off when the board is flat.
- It comes on in all four directions once the printed angle passes 30°.
- It goes off again when you come back.
Challenge 1 5 min
Goal: Detect "tap" or "shake": if any acceleration magnitude exceeds 2 g for > 50 ms, fire an LED. Trial-and-error the threshold.
1. Think first (on paper, no typing yet):
- When the board sits still, how big is the acceleration it feels? What is 2 g in m/s²?
- How do you combine x, y and z into one size?
- More than 50 ms means you have to know how long it has been above the limit. What must you remember, and when do you forget it?
2. Code it. Start from the Step 3 sketch. Read quickly, with no long delay, so a short shake is not missed.
3. Upload and observe. Plot the size while you tap and shake the board. Choose your threshold from what you see.
It works if:
- The printed size is about 9.8 when the board is still.
- The LED stays off when the board is still or tilted slowly.
- A sharp shake lights it. Say whether a single light tap does, and why.
Challenge 2 5 min
Goal: Integrate gyro Z over time to estimate "heading" (yaw). Drift will accumulate (~1°/min); confirm by yaw-ing 360° physically and seeing the integrated value.
1. Think first (on paper, no typing yet):
- Gyro Z says how fast the board is turning. If it reads 90° per second for half a second, how far has it turned?
- So on each pass the heading grows by rate × something. What is that something, and how will you measure it?
- Which units does the library give for the gyro, and what must you convert?
2. Code it. Start from your sketch with calibrateGyro(). Remove the Z offset, add up the turning, and print the heading.
3. Upload and observe. Lay the board flat on a book. Mark a start line, turn the book slowly through one full circle, and stop on the line.
It works if:
- One full turn reads close to 360° (or −360°).
- Left alone for a minute, the heading creeps by about a degree.
- Without the offset, the creep is clearly bigger.
Challenge 3 · Spirit level 10 min
- Make a simple spirit-level using just the accelerometer.
- 3 LEDs: tilt left = left LED, level = middle, tilt right = right.
- Threshold ~5° each way.
- Bonus: drive a servo as the bubble.
1. Think first (on paper, no typing yet):
- Which angle changes when you tilt the board left and right: pitch or roll?
- Three LEDs, three ranges. Write each range in degrees.
- Bonus: how would you turn an angle into a servo position between 0 and 180?
2. Code it. Start from your tilt sketch and your Basic LED.
3. Upload and observe. Lay it on a table, then prop one end up with a coin.
It works if:
- Flat: only the middle LED is on.
- More than about 5° to the left: only the left LED is on. The same on the right.
- Exactly one LED is on at any time.
Recap 5 min
MPU6050 = 6-axis IMU on I²C. Accelerometer measures gravity + motion (so noisy under motion). Gyroscope measures rotation rate (drifts over time). Bias-calibrate the gyro at rest. Tomorrow: combine accelerometer + gyroscope with a complementary filter to get a clean tilt angle suitable for balancing.
- IMU (Inertial Measurement Unit)
- Sensor that measures linear acceleration and angular velocity. 6-axis = accel + gyro; 9-axis adds a magnetometer.
- Accelerometer
- Measures linear acceleration on 3 axes. Detects gravity when at rest.
- Gyroscope
- Measures angular velocity (°/s) on 3 axes. Drifts over time when integrated.
- g (acceleration unit)
- 1 g = 9.81 m/s² = Earth's surface gravity.
- Pitch / Roll / Yaw
- The three rotation axes of an aircraft. Pitch = nose up/down; Roll = wing up/down; Yaw = nose left/right.
- Bias / offset
- Sensor's non-zero reading when there's no real input. Calibrated at rest.
- Drift
- Slow accumulation of error when integrating a noisy / biased signal. The gyro's nemesis.
- Adafruit_MPU6050
- Adafruit's Arduino library for the MPU6050. Friendly events API.
Extra Mission 5 min
Part 1 — Design a tilt-aware gadget
The MPU6050 knows which way is down. On paper, design an everyday gadget that reacts to tilt. It might be a tray that warns before a drink spills. It might be a bike light that flashes when you brake.
Your design must include:
- A name and a one-sentence job for the gadget.
- Which angle it watches (pitch or roll) and the threshold in degrees.
- At least two outputs and what each one means.
- How it avoids false alarms when it is only bumped.
Part 2 — Make it
Build the core of your gadget with the MPU6050, an LED and a buzzer. Use the pitch or roll formula from the New Concept. Fire the alarm only when the angle stays past your threshold for at least half a second.
Bring back next class: your uploaded sketch, a photo of the working circuit, and a Serial Plotter screenshot showing the angle crossing your threshold.