Self-balancing robot with an MPU6050 and complementary filter: design worksheet and code

A ₹1,590 design worksheet for a two-wheel self-balancing robot: reading the MPU6050 over I2C, fusing gyro and accelerometer with a complementary filter, and balancing with a PD loop, with the maths and expected difficulty set out honestly.

About the author · Editorial & verification standards

  • Parts₹1,590
  • Bench time10–20 h
  • LevelAdvanced
  • ReviewedNov 2026

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

PartQtyUnitTotal
Arduino Uno R3 (or compatible)1₹550₹550
MPU6050 breakout (GY-521)1₹150₹150
L298N motor driver board1₹180₹180
2WD chassis kit with two gear motors and wheels1₹450₹450
Battery holder with two 18650 cells1₹210₹210
Jumper wires1₹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

TiltAccelerometer X countAccelerometer Z countAngle from atan2
2°57216,3742.0°
5°1,42816,3225.0°
10°2,84516,13510.0°
20°5,60415,39620.0°
At the ±2 g range the scale is 16,384 counts per g, so X = 16,384 × sin(tilt) and Z = 16,384 × cos(tilt). The gyro at ±250 °/s gives 131 counts per °/s.

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

PartConnects toNote
MPU6050 VCC and GND5V and GND (check your breakout’s regulator)
MPU6050 SDA / SCLA4 / A5I2C, address 0x68
L298N ENA / IN1 / IN2D5 / D7 / D8Left motor
L298N ENB / IN3 / IN4D6 / D9 / D4Right motor
BatteryL298N 12V input and Uno VINCheck your pack voltage against the board limits
Mount the MPU6050 firmly and square to the chassis near the wheel axle; a loose board gives a false tilt reading.

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

  1. Read the sensor: print the raw counts and check that tilting the board changes X and Z as in the table.
  2. Check the filter: print the filtered angle while tilting by hand to known angles with a protractor.
  3. Motor direction: tilt the chassis forward and confirm the wheels drive forward; swap signs if not.
  4. Held test: hold the robot upright by hand and feel the wheels push back against the lean.
  5. Kp first, then Kd: raise Kp until it just starts to oscillate, then add Kd to calm it; lower both if the wheels shake.
  6. Trim the setpoint: adjust setpoint until it stands without creeping in one direction.

What usually goes wrong

SymptomLikely causeFix
Falls straight overWrong motor directionSwap the sign of the output
Shakes violentlyKd or Kp too highLower the gains, reduce the dead-zone offset
Oscillates slowlyKp too high and Kd too lowRaise Kd, lower Kp
Drifts across the floorSetpoint not at the centre of balanceTrim the setpoint
Angle drifts over timeGyro offset not removedHold still at power-up; recheck calibration
Weak recoveryMotors or wheels too weak or slipperyUse 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

The accelerometer is noisy during motion. Combining it with the smooth gyro gives an angle that is both quick and stable.

The robot is an unstable system with delays in the motors. Gains that are slightly off make it oscillate or fall.

It can, but it drops a couple of volts and gives little torque margin; many builders prefer a more efficient driver.

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.

More builds

Next builds to try

Free: the final-year project pack

A shortlist with BOMs, a report outline that matches the usual chapter scheme, a costing sheet and 40 viva questions. Built for the February–April submission season.

The Build Note

One short email when something is worth your bench time.

A new build sheet, a part price that moved, or a mistake worth avoiding. No daily drip, no recycled news.

One short email when a build or a price is worth your time. Unsubscribe in one click.