Show motion in 3D in the browser with an MPU-6050 on the Raspberry Pi

Connect the MPU-6050 motion sensor to the Raspberry Pi over I2C, read its registers yourself, combine the accelerometer and gyroscope with a complementary filter, and stream the result 30 times a second to a web page that turns a 3D...
  • Level:Advanced
  • Duration: 1 h 30 min
  • Ages 12+
  • Platform: Raspberry Pi
Show motion in 3D in the browser with an MPU-6050 on the Raspberry Pi – EEMENTOR STEM™ lesson

Phones know which way up they are, drones stay level in the wind, and game controllers feel every swing. Inside all of them is a tiny motion sensor like the MPU-6050. In this project you connect one to the Raspberry Pi, read its numbers straight from its registers, and turn them into angles you can trust. Then the Pi streams those angles 30 times a second to a web page, where a 3D board and a spirit level copy every tilt of the real sensor, live, on your phone or laptop.

What you'll learn

  • How the I2C bus works and how to switch it on with raspi-config
  • How to wake the MPU-6050 and read its accelerometer and gyroscope registers with smbus2
  • How to turn raw numbers into g, degrees per second and tilt angles
  • Why the accelerometer is noisy, why the gyroscope drifts, and how a complementary filter combines the best of both
  • How a WebSocket pushes live data to the browser without reloading the page

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS and its USB-C power supply, connected to your Wi-Fi (see the starter path)
  • GY-521 MPU-6050 module (45-in-1 Sensor Kit), with its pin header soldered on
  • Breadboard and 4 female-to-male jumper wires
  • A phone, tablet or computer on the same Wi-Fi network, with a web browser

Look after your Pi: power the GY-521 from the Pi's 3V3 pin, not 5V. The module has its own regulator and pull-up resistors, and on 3.3 V its SDA and SCL lines stay at a level the Pi's GPIO pins are made for. Shut the Pi down and unplug it before you change any wiring.

Wiring

The MPU-6050 talks over I2C: one data wire (SDA), one clock wire (SCL), plus power and ground. On the Pi, I2C bus 1 lives on GPIO 2 and GPIO 3. Push the GY-521 into the breadboard with its pins in one row and connect it like this. Leave XDA, XCL, AD0 and INT unconnected: with AD0 open the module answers at address 0x68.

Breadboard wiring diagram: GY-521 MPU-6050 module VCC to 3V3 (pin 1), SDA to GPIO 2 (pin 3), SCL to GPIO 3 (pin 5), GND to the minus rail and GND (pin 9) on a Raspberry Pi 4; XDA, XCL, AD0 and INT not connected.
Breadboard view. Check each connection against the wiring table below.
GY-521 pin Raspberry Pi pin
VCC 3V3 (pin 1)
GND The blue (−) rail, then GND (pin 9)
SCL GPIO 3 / SCL (pin 5)
SDA GPIO 2 / SDA (pin 3)

Lay the breadboard flat on the table before you start the program: the sensor learns what "still" looks like in the first few seconds.

Step 1: Switch on I2C and find the sensor

I2C is switched off on a fresh Raspberry Pi OS. Open a terminal and run sudo raspi-config, choose Interface Options → I2C → Yes, then reboot. Now check that the Pi can see the sensor:

sudo apt install -y i2c-tools
i2cdetect -y 1

You should see 68 in the grid. That is the MPU-6050 saying hello at address 0x68. If the grid is empty, check SDA and SCL first: swapping them is the most common mistake.

Step 2: Install the Python libraries

Raspberry Pi OS protects its own Python, so extra libraries go into a virtual environment. This one can still use the Flask that comes with the system. You install smbus2 to talk I2C and flask-sock for the WebSocket:

python3 -m venv --system-site-packages ~/mpu-env
~/mpu-env/bin/pip install smbus2 flask-sock

In Thonny, choose Run → Configure interpreter, pick "Alternative Python 3 interpreter or virtual environment" and select ~/mpu-env/bin/python3, so Thonny uses the same libraries.

Step 3: The program

Save the program as mpu3d.py and run it. It checks the sensor, spends two seconds measuring the gyroscope while the sensor is still, then starts a small web server on port 5000. The register addresses and scale factors come from the InvenSense MPU-6050 register map.

# 3D motion viewer: MPU-6050 on I2C -> complementary filter -> WebSocket -> browser
import json
import math
import threading
import time

from flask import Flask
from flask_sock import Sock
from smbus2 import SMBus

ADDR = 0x68              # MPU-6050 address with AD0 low (GY-521 default)
SMPLRT_DIV = 0x19
CONFIG = 0x1A
GYRO_CONFIG = 0x1B
ACCEL_CONFIG = 0x1C
ACCEL_XOUT_H = 0x3B      # first of 14 data bytes: accel X/Y/Z, temperature, gyro X/Y/Z
PWR_MGMT_1 = 0x6B
WHO_AM_I = 0x75

ACCEL_SCALE = 16384.0    # LSB per g at +-2 g
GYRO_SCALE = 131.0       # LSB per degree/s at +-250 degrees/s
ALPHA = 0.98             # how much we trust the gyro in the filter
RATE = 100               # sensor readings per second

bus = SMBus(1)           # I2C bus 1 = GPIO 2 (SDA) and GPIO 3 (SCL)
state = {"pitch": 0.0, "roll": 0.0, "yaw": 0.0, "temp": 0.0}
gyro_offset = [0.0, 0.0, 0.0]


def setup_sensor():
    who = bus.read_byte_data(ADDR, WHO_AM_I)
    print(f"WHO_AM_I = 0x{who:02X} (expected 0x68)")
    bus.write_byte_data(ADDR, PWR_MGMT_1, 0x01)    # wake up, use the gyro X clock
    time.sleep(0.1)
    bus.write_byte_data(ADDR, CONFIG, 0x03)        # digital low-pass filter, about 44 Hz
    bus.write_byte_data(ADDR, SMPLRT_DIV, 9)       # 1 kHz / (1 + 9) = 100 readings per second
    bus.write_byte_data(ADDR, GYRO_CONFIG, 0x00)   # +-250 degrees/s
    bus.write_byte_data(ADDR, ACCEL_CONFIG, 0x00)  # +-2 g


def to_int16(high, low):
    value = (high << 8) | low
    return value - 65536 if value >= 32768 else value


def read_sensor():
    data = bus.read_i2c_block_data(ADDR, ACCEL_XOUT_H, 14)
    raw = [to_int16(data[i], data[i + 1]) for i in range(0, 14, 2)]
    ax, ay, az = (v / ACCEL_SCALE for v in raw[0:3])
    temp = raw[3] / 340.0 + 36.53
    gx, gy, gz = (v / GYRO_SCALE for v in raw[4:7])
    return ax, ay, az, temp, gx, gy, gz


def calibrate(samples=200):
    print("Calibrating the gyro. Keep the sensor still...")
    sums = [0.0, 0.0, 0.0]
    for _ in range(samples):
        *_, gx, gy, gz = read_sensor()
        sums[0] += gx
        sums[1] += gy
        sums[2] += gz
        time.sleep(1 / RATE)
    for i in range(3):
        gyro_offset[i] = sums[i] / samples
    print("Gyro offsets (degrees/s): " + ", ".join(f"{o:.2f}" for o in gyro_offset))


def accel_angles(ax, ay, az):
    roll = math.degrees(math.atan2(ay, az))
    pitch = math.degrees(math.atan2(-ax, math.sqrt(ay * ay + az * az)))
    return pitch, roll


def sensor_loop():
    ax, ay, az, *_ = read_sensor()
    state["pitch"], state["roll"] = accel_angles(ax, ay, az)
    last = time.monotonic()
    while True:
        ax, ay, az, temp, gx, gy, gz = read_sensor()
        now = time.monotonic()
        dt = now - last
        last = now
        gx -= gyro_offset[0]
        gy -= gyro_offset[1]
        gz -= gyro_offset[2]
        acc_pitch, acc_roll = accel_angles(ax, ay, az)
        # Complementary filter: the gyro for quick moves, the accelerometer to stop drift
        state["roll"] = ALPHA * (state["roll"] + gx * dt) + (1 - ALPHA) * acc_roll
        state["pitch"] = ALPHA * (state["pitch"] + gy * dt) + (1 - ALPHA) * acc_pitch
        state["yaw"] += gz * dt          # gyro only: nothing corrects it, so it drifts
        state["temp"] = temp
        time.sleep(max(0, 1 / RATE - (time.monotonic() - now)))


PAGE = """<!doctype html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>MPU-6050 in 3D</title>
<style>
 body{margin:0;font-family:system-ui,sans-serif;background:#F6F8FC;color:#1B3A7B;text-align:center}
 h1{font-size:22px;margin:16px 0 0}
 .stage{height:300px;perspective:800px;display:flex;align-items:center;justify-content:center}
 .board{width:220px;height:140px;background:#1E5BB8;border-radius:10px;box-shadow:0 0 0 4px #0E3A80;
  display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;transform-style:preserve-3d}
 .chip{width:44px;height:44px;background:#111;border-radius:4px;margin-right:12px}
 .level{width:160px;height:160px;border-radius:50%;margin:0 auto;background:#E9EDF3;position:relative;border:3px solid #C9CED6}
 .level:after{content:"";position:absolute;left:50%;top:50%;width:40px;height:40px;margin:-20px;border:2px solid #9AA1AB;border-radius:50%}
 .bubble{position:absolute;left:50%;top:50%;width:28px;height:28px;margin:-14px;border-radius:50%;background:#2ECC71}
 .nums{font-size:18px;margin:14px} button{font-size:16px;padding:8px 16px;border-radius:8px;border:0;background:#1B3A7B;color:#fff}
</style></head><body>
<h1>MPU-6050 in 3D</h1>
<div class="stage"><div class="board" id="board"><div class="chip"></div>GY-521</div></div>
<div class="level"><div class="bubble" id="bubble"></div></div>
<p class="nums" id="nums">Connecting...</p>
<button id="zero">Zero yaw</button>
<script>
 const ws = new WebSocket("ws://" + location.host + "/ws");
 const board = document.getElementById("board"), bubble = document.getElementById("bubble");
 const clamp = (v) => Math.max(-60, Math.min(60, v));
 ws.onmessage = (e) => {
   const s = JSON.parse(e.data);
   board.style.transform = `rotateX(${55 + s.pitch}deg) rotateY(${s.roll}deg) rotateZ(${-s.yaw}deg)`;
   bubble.style.transform = `translate(${clamp(-s.roll)}px, ${clamp(s.pitch)}px)`;
   document.getElementById("nums").textContent =
     `Pitch ${s.pitch.toFixed(1)}°  Roll ${s.roll.toFixed(1)}°  Yaw ${s.yaw.toFixed(1)}°  ${s.temp.toFixed(1)} °C`;
 };
 ws.onclose = () => document.getElementById("nums").textContent = "Disconnected. Is the program running?";
 document.getElementById("zero").onclick = () => ws.send("zero");
</script></body></html>"""

app = Flask(__name__)
sock = Sock(app)


@app.route("/")
def index():
    return PAGE


@sock.route("/ws")
def stream(ws):
    while True:
        message = ws.receive(timeout=0)       # None when nothing was sent
        if message == "zero":
            state["yaw"] = 0.0
        ws.send(json.dumps(state))
        time.sleep(1 / 30)                     # about 30 updates per second


if __name__ == "__main__":
    setup_sensor()
    calibrate()
    threading.Thread(target=sensor_loop, daemon=True).start()
    print("Open http://<your-pi-address>:5000 in a browser on the same network")
    app.run(host="0.0.0.0", port=5000)

To find your Pi's address, run hostname -I in a terminal. Then open http://<that address>:5000 in a browser on the same Wi-Fi, for example http://192.168.1.42:5000. Stop the program with the red Stop button or Ctrl+C.

What you should see

The Shell shows WHO_AM_I = 0x68, the calibration message and the gyro offsets, a few tenths of a degree per second on each axis. On the web page the blue board lies at an angle as if on a table. Tilt the breadboard forward and back (pitch) and side to side (roll): the board on the screen follows smoothly, the green bubble rolls away from the high side like in a real spirit level, and the numbers change. Turn the breadboard flat on the table (yaw) and the board turns too, but watch the yaw number: even when you stop, it slowly creeps. Press Zero yaw to reset it.

The browser page served by the Pi: a blue 3D board tilted like the real sensor, a spirit level with the green bubble off centre, the pitch, roll, yaw and temperature readings and a Zero yaw button, next to the Thonny Shell messages.
Tilt the breadboard and the page follows 30 times a second.

How it works

Talking to the registers. The MPU-6050 keeps everything in numbered memory cells called registers. It starts in sleep mode, so the program first writes to PWR_MGMT_1 (0x6B) to wake it and use the gyroscope's clock, which the datasheet recommends because it is more stable. It sets a low-pass filter in CONFIG (0x1A), 100 readings per second with SMPLRT_DIV (0x19), and the most sensitive ranges: ±2 g and ±250 degrees per second. Then one I2C read fetches 14 bytes starting at ACCEL_XOUT_H (0x3B): accelerometer X, Y, Z, the temperature, and gyroscope X, Y, Z, each as a signed 16-bit number split over two bytes. to_int16() glues each pair together and handles negative values.

From numbers to units. At ±2 g, 16384 counts mean 1 g, so dividing by 16384 gives the acceleration in g. At ±250 degrees per second, 131 counts mean 1 degree per second. The chip's temperature is raw / 340 + 36.53 degrees Celsius; it measures the chip itself, so it reads a little above room temperature.

How it works: the X, Y and Z axes with roll, pitch and yaw; a graph comparing the jumpy accelerometer angle, the drifting gyroscope angle and the smooth filtered angle; and the complementary filter formula.
The gyroscope handles fast moves, gravity keeps the angle true.

Two sensors, two problems. When the sensor is still, the accelerometer only feels gravity. Gravity always points down, so the way it splits over the X, Y and Z axes tells you the tilt: roll = atan2(ay, az) and pitch = atan2(−ax, √(ay² + az²)). But every bump and shake adds acceleration too, so these angles jitter. The gyroscope measures how fast the sensor turns. Add up speed × time and you get the angle, smooth and quick, but every tiny error is added up too, so the angle slowly drifts away.

The complementary filter mixes them: every reading, the new angle is 98% "old angle plus what the gyroscope says" and 2% "what the accelerometer says". The gyroscope handles fast moves, and the small share of the accelerometer pulls the angle back to the truth over a second or two, so it never drifts away. You can change ALPHA to trust one sensor more than the other.

Why yaw drifts. Turning flat on the table doesn't change how gravity falls on the sensor, so the accelerometer can't tell you anything about yaw. Only the gyroscope sees it, and nothing corrects its error. To fix yaw you need a sensor that knows where north is: a magnetometer, as found in 9-axis modules such as the MPU-9250. That is why phones combine all three.

Streaming to the browser. A normal web page asks the server for data and waits. A WebSocket keeps one connection open in both directions, so the Pi can push 30 updates per second and the browser can send "zero" back. The sensor loop runs in its own thread at 100 readings per second, while each browser gets its own WebSocket loop at 30 messages per second. In the page, JavaScript turns the angles into a CSS 3D transform: rotateX for pitch, rotateY for roll and rotateZ for yaw.

Try this next

  • Change ALPHA to 0.90 and to 0.995 and compare how jumpy and how slow the board becomes.
  • Add a "tilt alarm" that turns the bubble red when the board is more than 10° off level, for a shelf-hanging helper.
  • Send the accelerometer's total g to the page and draw a live graph: a tap on the table shows as a spike.
  • Make the page a game: steer a ball through a maze by tilting the breadboard.

Troubleshooting

  • i2cdetect shows nothing: check that I2C is switched on, swap SDA and SCL if you mixed them up, and make sure VCC goes to 3V3 (pin 1) and GND to a GND pin. Check the header is soldered: pins that only rest in the holes don't make contact.
  • It shows 69 instead of 68: the AD0 pin is connected to 3.3 V. Leave it unconnected, or change ADDR to 0x69.
  • ModuleNotFoundError: No module named 'flask_sock': Thonny isn't using the virtual environment. Set the interpreter as in Step 2, or run ~/mpu-env/bin/python3 mpu3d.py in a terminal.
  • The page says "Disconnected": the program stopped or crashed. Look at the Shell for the error, then reload the page after starting it again.
  • The board tilts the wrong way: your module may be mounted differently. Swap the sign in the page's transform, for example rotateY(${-s.roll}deg).
  • Roll and pitch slowly wander after you start: the sensor moved during calibration. Lay it flat, keep still and restart the program.

Previous project: Control your Raspberry Pi with an IR remote. Next project: Set up the Raspberry Pi Pico as an analog sensor hub for the Pi.