Skip to content

Class 1 · Read the tilt

A balancing robot is only as good as its sense of which way is up. Today you connect the MPU6050, read its raw numbers, and turn them into two things: the tilt angle from the accelerometer and the turning rate from the gyro. Then you plot both and see why neither one is good enough by itself.

By the end of class

A live plot shows the accelerometer angle and the gyro rate as you tilt the board, and your group can explain what is wrong with each.

New parts today

Part What it's for
MPU6050 (GY-521 board) Accelerometer (which way is down) + gyro (how fast it's turning)

Build it

  1. Push the GY-521 into the breadboard so its pins sit in separate rows.
  2. Wire it to the Uno, with the USB cable unplugged:

    GY-521 pin → Uno pin
    VCC 5V
    GND GND
    SCL A5
    SDA A4
    XDA, XCL, AD0, INT nothing
  3. Make a new PlatformIO project for the Uno. This is the full platformio.ini:

    [env:uno]
    platform = atmelavr
    board = uno
    framework = arduino
    monitor_speed = 115200
    

The GY-521 has its own 3.3 V regulator, so 5V on VCC is fine. With AD0 left unconnected, the chip's address is 0x68.

Tool: I²C with the Wire library

I²C is a two-wire bus: SDA carries the data and SCL carries the clock. On the Uno those are A4 and A5. Each chip on the bus has an address, and inside each chip are numbered registers, like numbered mailboxes. You talk to a chip by saying "I want register 0x41" and then asking for some bytes.

The Wire library is built into the Arduino framework, so there's nothing to add to platformio.ini. This example reads something you won't use in the project: the MPU6050's temperature sensor. It also asks the chip who it is.

#include <Arduino.h>
#include <Wire.h>

const int MPU = 0x68;           // the chip's I²C address

// Read one byte from a register
byte readRegister(byte reg) {
  Wire.beginTransmission(MPU);
  Wire.write(reg);              // "I want this register"
  Wire.endTransmission(false);  // false = keep the bus, we're not done
  Wire.requestFrom(MPU, 1);     // ask for 1 byte
  return Wire.read();
}

void setup() {
  Serial.begin(115200);
  Wire.begin();

  // The chip starts asleep. Writing 0 to register 0x6B (PWR_MGMT_1) wakes it.
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission();

  Serial.print("WHO_AM_I = 0x");
  Serial.println(readRegister(0x75), HEX);
}

void loop() {
  // Temperature is two bytes: high byte at 0x41, low byte at 0x42
  Wire.beginTransmission(MPU);
  Wire.write(0x41);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 2);
  byte hi = Wire.read();
  byte lo = Wire.read();
  int16_t raw = (hi << 8) | lo;   // glue them into one signed number

  float tempC = raw / 340.0 + 36.53;  // formula from the MPU6050 register map
  Serial.println(tempC);
  delay(500);
}

A genuine MPU6050 answers WHO_AM_I = 0x68. Many boards are clones that answer something else (0x70, 0x72 and 0x98 are common). Any answer other than 0x0 or 0xFF means the chip is talking. 0x0 or 0xFF means check your wiring.

Two details matter. Every reading is two bytes, high byte first, glued together with (hi << 8) | lo. And the result is an int16_t, a signed 16-bit number, so negative readings come out negative. Read the two bytes in two separate lines like above: C++ doesn't promise which Wire.read() runs first if you put both in one expression.

Mission 1 · Talk to the chip

Run the example. Put your finger on the chip and watch the temperature rise. Write down what your board answers for WHO_AM_I.

Done when

The Serial Monitor shows a sensible temperature (around room temperature, a little warmer from the chip itself) that rises when you touch the chip.

The six numbers you need

Starting at register 0x3B, the chip keeps 14 bytes in a row. Ask for all 14 at once and read them in this order:

Registers Value What it means
0x3B–0x3C ax Acceleration along X
0x3D–0x3E ay Acceleration along Y
0x3F–0x40 az Acceleration along Z
0x41–0x42 temperature (skip it, but you still have to read it)
0x43–0x44 gx Turning rate around X
0x45–0x46 gy Turning rate around Y
0x47–0x48 gz Turning rate around Z

At the chip's default settings:

  • Accelerometer: 16384 counts = 1 g (range ±2 g). Lying flat and still, az reads about 16384 and the others about 0.
  • Gyro: 131 counts = 1 °/s (range ±250 °/s). Still, all three read close to 0.

The X, Y and Z arrows are printed on the GY-521.

Tool: an angle from two sides with atan2

If you know the two sides of a right triangle, atan2(opposite, adjacent) gives the angle, in radians. Multiply by RAD_TO_DEG (built into Arduino) to get degrees. Unlike plain atan, atan2 gets the sign right in every direction.

Example: a ladder leans against a wall. Its top is 3.5 m up and its foot is 1.2 m out from the wall.

float height = 3.5;   // m
float out = 1.2;      // m
float angle = atan2(height, out) * RAD_TO_DEG;   // angle from the floor
Serial.println(angle);                           // about 71.1

For the robot, the triangle is gravity. When the board tilts, gravity's pull splits between two of its axes. The two accelerometer readings are the two sides.

Mission 2 · Accelerometer angle and gyro rate

  1. Read all 14 bytes from 0x3B in one Wire.requestFrom(MPU, 14), and store ax, ay, az, gx, gy, gz as int16_t.
  2. Lay the board flat. Pick the tilt you'll measure: rotating the board around its X axis (the X arrow is the hinge). That's the way the robot will tip when the board lies flat on its middle deck with X pointing along the wheel axle.
  3. Compute accAngle = atan2(ay, az) * RAD_TO_DEG and gyroRate = gx / 131.0 (°/s).
  4. Add a gyro-only angle: every loop, gyroAngle += gyroRate * 0.01; with delay(10) at the end of loop(). (The 0.01 s is a guess at how long one loop takes. You'll measure it properly next class.)
  5. Print all three for Teleplot. Every line that starts with > gets plotted:

    Serial.print(">acc:");   Serial.println(accAngle);
    Serial.print(">rate:");  Serial.println(gyroRate);
    Serial.print(">gyro:");  Serial.println(gyroAngle);
    
  6. Close the PlatformIO Serial Monitor (only one program can hold the port), open Teleplot from the VS Code sidebar, pick the Uno's port at 115200, and connect. Disconnect Teleplot before you upload again.

Done when

Tilting the board forward makes acc and gyro both go the same direction (positive, say), and rate jumps while you're moving it and returns to about 0 when you stop. If rate goes negative when the angle goes up, the signs disagree: use -gx instead.

Noise and drift

Now look closely at the plot.

  • Tap the table. The accelerometer angle spikes. It can't tell gravity from a bump, so every jolt looks like a tilt. Slide the board quickly across the table without tilting it: the angle changes even though the tilt didn't.
  • Leave it still for a minute. The gyro angle creeps away from the truth, even though nothing moves. The gyro reads a small rate even at rest (its bias), and adding up a small error 100 times a second becomes a big error.

Tool: average away the offset

If a sensor reads a little high all the time, measure how much while you know the true value, then subtract it. Averaging many readings gets rid of the noise in that measurement.

Example: a pot that should read 0 when turned all the way down, but doesn't quite.

long sum = 0;
for (int i = 0; i < 200; i++) {
  sum += analogRead(A0);
  delay(2);
}
float zeroOffset = sum / 200.0;
// later: float reading = analogRead(A0) - zeroOffset;

Use a long for the sum: 200 readings of up to 1023 don't fit in an int.

Mission 3 · Calibrate the gyro

In setup(), while the board sits still, average 500 readings of gx. Call it gyroBias. In loop(), use gyroRate = (gx - gyroBias) / 131.0. Print the bias once so you know its size. Run the one-minute still test again.

Done when

The gyro angle drifts much less than before (write down roughly how many degrees per minute, before and after), and your group can explain in two sentences why neither the accelerometer angle nor the gyro angle is good enough alone.

If you finish early

  • Try the other axes. Which formula would you use if the board were mounted standing up instead of flat?
  • Shake the board without tilting it. How big do the accelerometer spikes get?
  • Read the chip's datasheet section on GYRO_CONFIG (register 0x1B). What would you change to measure faster rotations, and what would happen to the 131?

Sign-off with Dr. Alvear

  • Live plot of the accelerometer angle, gyro rate and gyro angle
  • Gyro bias calibrated at startup
  • Your group explains noise (accelerometer) and drift (gyro)
  • Build log updated (photo + two sentences)