A self-balancing robot stays upright. A drone stays level. A phone knows which way you hold it. All three use the same two sensors: an accelerometer and a gyroscope.
The short answer: an accelerometer measures acceleration along a line, including the effect of gravity. A gyroscope measures how fast something rotates. The accelerometer knows which way is down but is noisy. The gyroscope is smooth but slowly drifts. Good robots use both.
In this guide we look inside both sensors, connect an MPU6050 to an ESP32, read real values from my own board and build a small motion indicator with three LEDs.
Loads from YouTube when you press play, and YouTube may then set cookies. Watch on YouTube
First: X, Y, Z and roll, pitch, yaw
The MPU6050 is called a six-axis sensor. It has a three-axis accelerometer and a three-axis gyroscope in one chip. Both use the same three directions:

Small arrows on the module show where X and Y point. Z comes straight out of the top of the chip. Always check those arrows before you mount the board on a robot.

How an accelerometer works
Inside the chip is a tiny structure, so small that you need a microscope to see it. This kind of device is called MEMS: a micro-electromechanical system. In the accelerometer, a very small proof mass hangs on silicon springs.
When the chip speeds up, the mass tends to stay where it was. That’s inertia, the same thing that pushes you back in your seat when a bus starts. The mass moves a little relative to the chip, and the springs pull it back.

How does the chip measure such a small movement? The mass carries tiny plates that sit next to fixed plates. Two plates facing each other form a capacitor, and their capacitance changes when the gap changes. The chip measures that and turns it into a number.
Why does it show 1 g when nothing moves?
Put the sensor flat on a table. X and Y show about 0, but Z shows about 1 g, or 9.8 m/s². Nothing is accelerating, so why?
Because an accelerometer doesn’t really measure movement. It measures the force that holds its mass in place. On a table, the springs must hold the mass up against gravity, and the sensor reports that as +1 g. In free fall nothing holds the mass, so the sensor would show about 0 g, even though it’s falling faster and faster.
This is useful. Tilt the board, and the 1 g is shared between the axes. From that share you can calculate the tilt:
Roll = atan2(ay, az)
Pitch = atan2(−ax, √(ay² + az²))
Yaw is missing, and it can’t be calculated this way. If you turn the board like a steering wheel lying flat on a table, gravity stays on Z all the time. The accelerometer sees no change at all.
How a gyroscope works
A gyroscope doesn’t measure an angle. It measures angular velocity: how many degrees per second the chip is turning.
Imagine that you walk on a merry-go-round. While it stands still, you walk straight. When it turns, you feel pushed to the side, although you’re walking straight ahead. That sideways effect is the Coriolis effect.

A MEMS gyroscope makes its own “walker”. A tiny mass is kept vibrating back and forth all the time. When the chip rotates, the Coriolis effect pushes the mass sideways, and capacitive plates measure that movement. The faster the rotation, the bigger the movement.
From speed to angle
To get an angle, the code multiplies the speed by the time between two readings and adds it up:
angle = angle + angular velocity × time
This is called integration. It works for roll, pitch and yaw. But it has a weakness.
Why the gyroscope drifts
No gyroscope shows exactly 0 when it’s still. Suppose that yours shows just 0.5 °/s. The code believes it and keeps adding:
| Time standing still | Error from a 0.5 °/s bias |
|---|---|
| 1 second | 0.5° |
| 10 seconds | 5° |
| 1 minute | 30° |
| 5 minutes | 150° |
These values are calculated, but the effect is real. It’s the reason why you calibrate a gyroscope: keep it still, average many readings and subtract that average. It makes the drift much smaller, but never zero.
Accelerometer vs gyroscope
| Accelerometer | Gyroscope | |
|---|---|---|
| Measures | Acceleration along X, Y, Z, including gravity | Rotation speed around X, Y, Z |
| Unit | g or m/s² | °/s or rad/s |
| Works by | A mass on springs | A vibrating mass and the Coriolis effect |
| Roll and pitch | Yes, from gravity | Yes, by adding up |
| Yaw | No | Yes, but it drifts |
| Strength | Always knows which way is down | Smooth and fast |
| Weakness | Vibration and movement disturb it | Small errors grow with time |
Connect an MPU6050 to an ESP32
| Part | Where to find it |
|---|---|
| ESP32 development board | Amazon |
| MPU6050 module | Amazon |
| Breadboard | Amazon |
| Jumper wires | Amazon |
| 3 LEDs and 3 resistors (I used 337 Ω; 220–470 Ω is fine) | Amazon |

The module talks over I²C, which needs only two signal wires: SCL is the clock and SDA is the data. I powered it from 3.3 V, so its signals match the ESP32.
Both sketches from the video are on GitHub: mpu6050-esp32-tutorial. In the Arduino IDE, install Adafruit MPU6050 from the Library Manager and accept its dependencies. The Adafruit guide explains the library in detail.
The important part of sketch 1
The sketch sets the ranges to ±2 g and ±250 °/s, averages 1,000 readings to calibrate the gyroscope, and then runs this in the loop:
// Accelerometer angles
float accelRoll = atan2(ay, az) * 180.0 / PI;
float accelPitch = atan2(-ax, sqrt(ay * ay + az * az)) * 180.0 / PI;
// Gyroscope: rad/s -> deg/s, then remove the measured bias
float gx = gyro.gyro.x * 180.0 / PI - gyroX_offset;
float gy = gyro.gyro.y * 180.0 / PI - gyroY_offset;
float gz = gyro.gyro.z * 180.0 / PI - gyroZ_offset;
// Time since the last loop, in seconds
unsigned long currentTime = micros();
float dt = (currentTime - previousTime) / 1000000.0;
previousTime = currentTime;
// Gyroscope angles: speed x time, added up
gyroRoll += gx * dt;
gyroPitch += gy * dt;
gyroYaw += gz * dt;Keep the board completely still while it calibrates. If you move it, the wrong offset is subtracted from every reading afterwards.
What my sensor really showed
These lines are from my Serial Monitor in the video. I was holding the board in my hand, roughly level:

Here are eight lines in a row, only for pitch:
| Line | Pitch from accelerometer | Pitch from gyroscope |
|---|---|---|
| 1 | 7.1° | 2.7° |
| 2 | 6.6° | 2.8° |
| 3 | 4.3° | 2.7° |
| 4 | 4.8° | 2.6° |
| 5 | 4.9° | 2.6° |
| 6 | 3.2° | 2.6° |
| 7 | 2.2° | 2.7° |
| 8 | 3.6° | 2.6° |
This small table shows the whole story:
The accelerometer is noisy. It jumped between 2.2° and 7.1°. Small hand movements and sensor noise both show up here.
The gyroscope is smooth. It stayed between 2.6° and 2.8°.
Smooth doesn’t mean correct. In the same lines, the gyroscope said that the roll was about −6.5° while the accelerometer said about 0°. A gyroscope angle starts from 0 wherever the board is when it’s switched on, and then it collects errors.
Z wasn’t exactly 1 g. It moved between 0.88 and 1.02 g. The sensor has its own offset, and my hand wasn’t perfectly still.
Use both: the complementary filter
The usual solution is to trust the gyroscope for fast changes and let the accelerometer slowly pull the angle back. The simplest version is one line for each angle:
// Start from the accelerometer once, after calibration:
// roll = accelRoll; pitch = accelPitch;
roll = 0.98 * (roll + gx * dt) + 0.02 * accelRoll;
pitch = 0.98 * (pitch + gy * dt) + 0.02 * accelPitch;This step isn’t in the video or the repository. It’s the standard next one, so treat the 0.98 as a starting value: closer to 1 is smoother, and lower corrects faster. Yaw still drifts, because gravity can’t correct it. For a real heading you need a magnetometer. That’s what a phone’s compass uses, together with the gyroscope.
Mini project: a motion indicator
The second sketch turns movement into a score from 0 to 100 and lights one of three LEDs.

// How far the total acceleration is from 1 g
float magnitude = sqrt(ax * ax + ay * ay + az * az);
float dynamicG = fabs(magnitude - 9.81) / 9.81;
// How fast it rotates, in any direction
float rotation = sqrt(gx * gx + gy * gy + gz * gz);
// 1 g extra = 100 points, 180 deg/s = 100 points; the stronger one wins
float motionScore = max(dynamicG * 100.0f, rotation / 180.0f * 100.0f);
motionScore = constrain(motionScore, 0, 100);This is a shortened version of the logic, so it won’t compile on its own. Use the full sketch from GitHub.
| Motion score | LED | GPIO |
|---|---|---|
| 5 or less | All off | — |
| More than 5 | Gentle | 13 |
| More than 30 | Medium | 14 |
| More than 70 | Strong | 26 |

You can check the formula with my readings. At 149.8 °/s the score was 83.2, because 149.8 ÷ 180 = 0.832. In another line the acceleration was 0.71 g, and the score was 71.0.
My LEDs were white, green and blue. The GitHub code calls them blue, green and red. The colours don’t matter; the pins do.
Two limits of this project
It can clip. In the ±250 °/s range, anything faster than that on one axis looks like 250. For quick robots use ±500 or ±1000 °/s.
It only compares the total with 1 g. A slow, smooth movement changes the total very little, so it may not light anything.
Common problems
| Problem | Likely cause | Fix |
|---|---|---|
| “MPU6050 not found!” | SDA and SCL swapped, or a loose header | SCL to GPIO 22, SDA to GPIO 21; solder the header pins |
| Still not found | Different I²C address | The address is 0x68, or 0x69 if AD0 is high: use mpu.begin(0x69) |
| The angle runs away while still | The board moved during calibration | Reset it and keep it still |
| Angles jump when motors run | Vibration | Use soft mounting, the low-pass filter and a complementary filter |
| Roll and pitch are swapped | The module is mounted differently | Follow the arrows on the module |
| Arduino IDE won’t open the file | The GitHub file name ends in .ino.ino | Rename it so that it matches its folder and ends in one .ino |
Where you will use this
Self-balancing robots: pitch tells the motors how to catch the fall.
Drones: the flight controller uses roll, pitch and yaw speed many times per second.
Gesture control: tilt your hand to move a robot. I plan to use an ESP32 and an MPU6050 for the handheld controller of my robotic arm.
Robot cars: gyro yaw helps a car turn by a set angle or drive straight. It would be a good upgrade for my ESP32 RC car.
What to remember
An accelerometer feels forces, so it always feels gravity.
A gyroscope feels rotation speed, and its angle drifts.
Neither is enough alone. Combined, they’re excellent.
Start with the first sketch, tilt the board slowly and watch the two angles disagree. It’s the fastest way to understand both sensors. For chip details, see the MPU-6050 page from TDK.
Frequently Asked Questions
What is the difference between an accelerometer and a gyroscope?
An accelerometer measures acceleration along an axis, including the effect of gravity. A gyroscope measures how fast something rotates around an axis.
Can an accelerometer measure rotation?
Not directly. It can work out roll and pitch from gravity when the board is nearly still. It can’t measure yaw.
Why does a gyroscope drift?
It always has a small error. When the code adds up the speed to get an angle, it adds up that error too. Calibration and a filter reduce it.
What is an IMU?
An inertial measurement unit: a chip that combines motion sensors. The MPU6050 is a six-axis IMU. Nine-axis ones add a magnetometer.
Can I use the MPU6050 with an Arduino Uno?
Yes. Connect SDA to A4 and SCL to A5, and use Wire.begin() without pin numbers. Check your module’s voltage first, because the chip itself is a 3.3 V part.
Affiliate disclosure
Some links in this post are affiliate links. If you buy through them, I may earn a small commission at no extra cost to you. It helps support Roborear.


Comments (0)
No comments yet. Start the discussion.