A ₹1,590 robot that stands on two wheels and keeps itself upright. An MPU6050 measures tilt, a complementary filter combines its gyroscope and accelerometer into one stable angle, and a PD loop drives the wheels toward the lean. It is a hard build to tune, so the page spends its words on the maths and on the order of testing.
Scope: advanced. This is a design worksheet with illustrative costs. It has not been bench-tested by this site. The filter and raw-count tables were computed by script. Balancing is sensitive to motors, wheels, weight height and battery, so the gains in the sketch are only a place to start and getting a robot to stand will take patient tuning. Expect to spend longer on this than on any other project in this series.
How it works
The accelerometer gives a tilt angle from gravity, but it is noisy when the robot jolts. The gyroscope gives a smooth turn rate, but its small offset adds up as drift. A complementary filter uses each where it is good: angle = 0.98 × (previous angle + gyro rate × dt) + 0.02 × accelerometer angle. With a 10 ms loop the filter time constant is 0.98 × 0.01 / 0.02 = 0.49 second, so the gyro dominates over short moments and the accelerometer slowly pulls out the drift.
The controller drives both wheels with Kp × angle + Kd × gyro rate. Leaning forward makes the wheels drive forward to get back under the body. Kp sets how hard it reacts to lean, and Kd resists the speed of the lean and does most of the damping. If the lean exceeds 35 degrees the sketch cuts the motors, because by then the robot has fallen.
Bill of materials
| Part | Qty | Unit | Total |
|---|---|---|---|
| Arduino Uno R3 (or compatible) | 1 | ₹550 | ₹550 |
| MPU6050 breakout (GY-521) | 1 | ₹150 | ₹150 |
| L298N motor driver board | 1 | ₹180 | ₹180 |
| 2WD chassis kit with two gear motors and wheels | 1 | ₹450 | ₹450 |
| Battery holder with two 18650 cells | 1 | ₹210 | ₹210 |
| Jumper wires | 1 | ₹50 | ₹50 |
| Parts total | ₹1,590 | ||
Scroll the table sideways to see every column.
Prices checked Nov 2026. Shipping and tools are not included.
Prices are illustrative figures for Indian sellers in November 2026, before shipping, and have not been checked against current listings.
The numbers
| Tilt | Accelerometer X count | Accelerometer Z count | Angle from atan2 |
|---|---|---|---|
| 2° | 572 | 16,374 | 2.0° |
| 5° | 1,428 | 16,322 | 5.0° |
| 10° | 2,845 | 16,135 | 10.0° |
| 20° | 5,604 | 15,396 | 20.0° |
A gyro offset of just 1 count is 0.0076 °/s, which would add up to 0.46 degrees after a minute if not corrected. The sketch averages 500 readings at start-up to remove the offset, so the robot must be held still while it powers up.
Power and wiring
| Part | Connects to | Note |
|---|---|---|
| MPU6050 VCC and GND | 5V and GND (check your breakout’s regulator) | |
| MPU6050 SDA / SCL | A4 / A5 | I2C, address 0x68 |
| L298N ENA / IN1 / IN2 | D5 / D7 / D8 | Left motor |
| L298N ENB / IN3 / IN4 | D6 / D9 / D4 | Right motor |
| Battery | L298N 12V input and Uno VIN | Check your pack voltage against the board limits |
The sketch
// Self-balancing robot: Uno + MPU6050 + L298N
// Design worksheet: gains are starting guesses; expect long tuning.
#include <Wire.h>
const int L_EN = 5, L_IN1 = 7, L_IN2 = 8;
const int R_EN = 6, R_IN3 = 9, R_IN4 = 4;
void drive(int left, int right) { // -255..255 per side
digitalWrite(L_IN1, left >= 0); digitalWrite(L_IN2, left < 0);
digitalWrite(R_IN3, right >= 0); digitalWrite(R_IN4, right < 0);
analogWrite(L_EN, constrain(abs(left), 0, 255));
analogWrite(R_EN, constrain(abs(right), 0, 255));
}
void motorsInit() {
pinMode(L_EN, OUTPUT); pinMode(L_IN1, OUTPUT); pinMode(L_IN2, OUTPUT);
pinMode(R_EN, OUTPUT); pinMode(R_IN3, OUTPUT); pinMode(R_IN4, OUTPUT);
}
const int MPU = 0x68;
const float ALPHA = 0.98;
const unsigned long LOOP_US = 10000UL; // 10 ms
const float FALL_LIMIT = 35.0; // degrees
const int MIN_PWM = 40; // overcomes motor dead zone
float Kp = 20.0, Kd = 0.8;
float setpoint = 0.0; // trim for the centre of balance
float angle = 0, gyroOffset = 0;
unsigned long lastLoop = 0;
void readMpu(int16_t &ax, int16_t &az, int16_t &gy) {
Wire.beginTransmission(MPU); Wire.write(0x3B); Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true);
ax = Wire.read() << 8 | Wire.read();
Wire.read(); Wire.read(); // skip ay
az = Wire.read() << 8 | Wire.read();
Wire.read(); Wire.read(); // skip temperature
Wire.read(); Wire.read(); // skip gx
gy = Wire.read() << 8 | Wire.read();
Wire.read(); Wire.read(); // skip gz
}
void setup() {
motorsInit();
Wire.begin();
Wire.setClock(400000);
Wire.beginTransmission(MPU); Wire.write(0x6B); Wire.write(0); Wire.endTransmission(true);
delay(1000); // hold the robot still
long sum = 0; int16_t ax, az, gy;
for (int i = 0; i < 500; i++) { readMpu(ax, az, gy); sum += gy; delay(2); }
gyroOffset = sum / 500.0;
readMpu(ax, az, gy);
angle = atan2((float)ax, (float)az) * 180.0 / PI;
lastLoop = micros();
}
void loop() {
if (micros() - lastLoop < LOOP_US) return;
float dt = (micros() - lastLoop) / 1e6;
lastLoop = micros();
int16_t ax, az, gy;
readMpu(ax, az, gy);
float rate = (gy - gyroOffset) / 131.0; // deg/s
float accAngle = atan2((float)ax, (float)az) * 180.0 / PI;
angle = ALPHA * (angle + rate * dt) + (1.0 - ALPHA) * accAngle;
if (fabs(angle) > FALL_LIMIT) { drive(0, 0); return; } // fallen: stop
float out = Kp * (angle - setpoint) + Kd * rate;
int pwm = (int)constrain(out, -255, 255);
if (pwm > 0) pwm += MIN_PWM; else if (pwm < 0) pwm -= MIN_PWM;
drive(pwm, pwm);
}Which sign drives the wheels toward the lean depends on how you mount the sensor: if the robot falls faster, swap the sign of out. The robot has to be lifted back upright after it falls and then restarted, because the sketch does not restart the balance on its own. The sketch has been proofread but not compiled on this site.
Test plan
- Read the sensor: print the raw counts and check that tilting the board changes X and Z as in the table.
- Check the filter: print the filtered angle while tilting by hand to known angles with a protractor.
- Motor direction: tilt the chassis forward and confirm the wheels drive forward; swap signs if not.
- Held test: hold the robot upright by hand and feel the wheels push back against the lean.
- Kp first, then Kd: raise Kp until it just starts to oscillate, then add Kd to calm it; lower both if the wheels shake.
- Trim the setpoint: adjust setpoint until it stands without creeping in one direction.
What usually goes wrong
| Symptom | Likely cause | Fix |
|---|---|---|
| Falls straight over | Wrong motor direction | Swap the sign of the output |
| Shakes violently | Kd or Kp too high | Lower the gains, reduce the dead-zone offset |
| Oscillates slowly | Kp too high and Kd too low | Raise Kd, lower Kp |
| Drifts across the floor | Setpoint not at the centre of balance | Trim the setpoint |
| Angle drifts over time | Gyro offset not removed | Hold still at power-up; recheck calibration |
| Weak recovery | Motors or wheels too weak or slippery | Use stronger motors and grippy wheels |
Upgrades
- Speed loop: add an encoder loop to stop the drift across the floor.
- Steering: add Bluetooth or a remote for driving.
- Library: use a library to read the MPU6050 digital motion processor.
- Stronger driver: replace the L298N, whose voltage drop wastes battery power.
Cost and parts notes
The ₹1,590 total is an illustration and does not include shipping. Use the cost calculator to compare sellers.
Common questions
Why a complementary filter and not just the accelerometer?
The accelerometer is noisy during motion. Combining it with the smooth gyro gives an angle that is both quick and stable.
Why is it so hard to tune?
The robot is an unstable system with delays in the motors. Gains that are slightly off make it oscillate or fall.
Does the L298N work?
It can, but it drops a couple of volts and gives little torque margin; many builders prefer a more efficient driver.
How fast must the loop run?
About 100 times a second is a common target, and the sketch uses a 10 ms loop.
Last reviewed: November 2026. This is a design worksheet with illustrative costs. It has not been bench-tested by this site; library names, pins and limits must be checked against your board and the current library versions, and measurements from your build are welcome.