Projects / Two-wheel self-balancing robot

Two-wheel self-balancing robot

Advanced4 hGuided buildReviewed

Build it step by step

0 of 6 done
  1. NANOMINI

    Set the buck converter

    Before connecting the Nano, set the buck output to 5.0 V with a multimeter.

  2. NANOMPU6050tilt 29°

    Mount the IMU

    Fix the MPU6050 firmly on the frame, near the axle, with its X axis pointing forward.

  3. NANO+

    Wire the driver

    TB6612 to D5-D10, STBY to 5V, VM to the battery, motors to A01/A02 and B01/B02.

  4. NANO

    Check the angle

    With the wheels off the ground, upload and open the serial monitor at 115200. Tilting forward must make the angle positive. Hold it upright and note the angle: put it in setpoint.

  5. NANO

    Check direction

    Tilt it forward: both wheels must spin forward (to drive under the fall). If not, swap that motor's wires.

  6. NANO

    Tune

    Ki and Kd to zero. Raise Kp until it oscillates, then add Kd until the shaking stops, then a little Ki to stop drifting.

In short

How do you build a two-wheel self-balancing robot?

An MPU6050 measures the robot's tilt 200 times a second and a PID controller drives two motors to keep it upright. You need Arduino Nano, MPU6050 IMU, TB6612FNG Motor Driver, Self-balancing robot kit, Battery holder 18650 2S (series), 18650 cell 2600 mAh (branded) × 2, Mini-360 buck converter, Rocker switch (KCD1, 2-pin), Potentiometer 10 kΩ × 3 and Jumper wires male to male (40 pcs, 20 cm). It takes 6 steps and about 240 minutes.

Level
Advanced
Time
About 240 min
Parts
10

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Battery + (through switch)TB6612 VM and buck converter IN+Motor supply 7.4 V
Buck OUT+ (set to 5.0 V)Nano 5V and TB6612 VCCLogic supply
All groundsBattery −, buck −, Nano GND, TB6612 GND, MPU GNDOne ground
TB6612 PWMA / AIN1 / AIN2Nano D5 / D7 / D8Left motor
TB6612 PWMB / BIN1 / BIN2Nano D6 / D9 / D10Right motor
TB6612 STBYNano 5VDriver always enabled
MPU6050 SDA / SCL / VCCNano A4 / A5 / 5VIMU, mounted on the axle line
Three pots (wipers)Nano A0 / A1 / A2Kp, Ki, Kd while tuning

Code

Arduino IDE, board "Arduino Nano". No libraries: the MPU6050 is read directly. Tune with the three pots, then write the values into the code. If the robot runs away from the tilt, swap the motor wires or the sign of out.

Runs on a virtual Arduino Nano in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

#include <Wire.h>

const int PWMA = 5, AIN1 = 7, AIN2 = 8, PWMB = 6, BIN1 = 9, BIN2 = 10;
const int MPU = 0x68;
float angle = 0, integral = 0, lastErr = 0;
float setpoint = 0;          // adjust until it stands still without drifting
unsigned long last;

void motors(int s) {
  s = constrain(s, -255, 255);
  digitalWrite(AIN1, s > 0); digitalWrite(AIN2, s < 0);
  digitalWrite(BIN1, s > 0); digitalWrite(BIN2, s < 0);
  analogWrite(PWMA, abs(s)); analogWrite(PWMB, abs(s));
}

void setup() {
  int outs[] = {PWMA, AIN1, AIN2, PWMB, BIN1, BIN2};
  for (int p : outs) pinMode(p, OUTPUT);
  Wire.begin(); Wire.setClock(400000);
  Wire.beginTransmission(MPU); Wire.write(0x6B); Wire.write(0); Wire.endTransmission();
  Serial.begin(115200);
  last = micros();
}

void loop() {
  if (micros() - last < 5000) return;          // 200 Hz loop
  float dt = (micros() - last) / 1e6; last = micros();
  Wire.beginTransmission(MPU); Wire.write(0x3B); Wire.endTransmission(false);
  Wire.requestFrom(MPU, 14);
  int16_t ax = Wire.read() << 8 | Wire.read(); Wire.read(); Wire.read();
  int16_t az = Wire.read() << 8 | Wire.read();
  Wire.read(); Wire.read();                    // temperature
  Wire.read(); Wire.read();                    // gyro X
  int16_t gy = Wire.read() << 8 | Wire.read();
  Wire.read(); Wire.read();
  float accAngle = atan2(-ax, az) * 180 / PI;  // tilt from gravity (noisy), same sign as the gyro
  float rate = gy / 131.0;                     // deg/s from the gyro (drifts)
  angle = 0.98 * (angle + rate * dt) + 0.02 * accAngle;   // complementary filter

  float kp = analogRead(A0) / 1023.0 * 60, ki = analogRead(A1) / 1023.0 * 300, kd = analogRead(A2) / 1023.0 * 3;
  float err = angle - setpoint;
  if (fabs(err) > 35) { motors(0); integral = 0; return; }   // fallen over: stop
  integral = constrain(integral + err * dt, -50, 50);
  float out = kp * err + ki * integral + kd * (err - lastErr) / dt;
  lastErr = err;
  motors((int)out);
  static int n = 0;
  if (++n % 40 == 0) { Serial.print(angle); Serial.print(" kp="); Serial.print(kp); Serial.print(" ki="); Serial.print(ki); Serial.print(" kd="); Serial.println(kd); }
}

What the serial monitor should show

Open the serial monitor at the baud rate in the code. This is what our simulator prints for a virtual Arduino Nano with its sensors at their default values. Your numbers will follow your real readings, but the format should match.

0.00 kp=30.03 ki=150.15 kd=1.50
0.00 kp=30.03 ki=149.85 kd=1.50
0.00 kp=30.03 ki=150.15 kd=1.50
0.00 kp=30.03 ki=150.44 kd=1.50
0.00 kp=30.03 ki=149.85 kd=1.50
0.00 kp=29.97 ki=150.15 kd=1.50

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Tilted forward off the groundAngle positive, wheels spin forward harder the more you tilt
Held uprightAngle within ±1° of setpoint
Tuned on the floorStands for over a minute and recovers from a light push
Tilted beyond 35°Motors stop

If it does not work

Falls over fast in one direction

The motors push the wrong way. Swap both motor's wires, or use motors(-out).

Shakes violently

Kd too low or Kp too high. Lower Kp, raise Kd.

Slowly drives off and falls

Setpoint is off the true balance point, or Ki is zero.

Resets when motors kick

Weak cells or the Nano is on the motor supply. Use the buck converter and charged cells.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the two-wheel self-balancing robot?

Arduino Nano, MPU6050 IMU, TB6612FNG Motor Driver, Self-balancing robot kit, Battery holder 18650 2S (series), 18650 cell 2600 mAh (branded) × 2, Mini-360 buck converter, Rocker switch (KCD1, 2-pin), Potentiometer 10 kΩ × 3 and Jumper wires male to male (40 pcs, 20 cm). Self-balancing robot kit: Frame with two geared motors and wheels. Mini-360 buck converter: 7.4 V to 5 V for the Nano. Potentiometer 10 kΩ × 3: For live PID tuning.

How long does the two-wheel self-balancing robot take to build?

About 240 minutes for a advanced maker, in 6 steps.

How do I know the two-wheel self-balancing robot works?

Tilted forward off the ground: Angle positive, wheels spin forward harder the more you tilt. Held upright: Angle within ±1° of setpoint. Tuned on the floor: Stands for over a minute and recovers from a light push.

Falls over fast in one direction: what should I check?

The motors push the wrong way. Swap both motor's wires, or use motors(-out).

Shakes violently: what should I check?

Kd too low or Kp too high. Lower Kp, raise Kd.

Slowly drives off and falls: what should I check?

Setpoint is off the true balance point, or Ki is zero.

Resets when motors kick: what should I check?

Weak cells or the Nano is on the motor supply. Use the buck converter and charged cells.