Self-Balancing Robot with Arduino: MPU6050, PID Tuning and Code
Build a self-balancing robot with Arduino and MPU6050: complementary filter, step-by-step PID tuning, stepper vs DC motors, why it falls and ESP32 Bluetooth.
A self-balancing robot with Arduino is a two-wheeled robot that keeps itself upright: the moment it starts to tip, it drives its wheels in that direction and catches itself. Segways and hoverboards work on exactly the same principle. With an Arduino, an MPU6050 accelerometer and gyroscope module, two motors and a motor driver you can build one on your desk; the secret is measuring the tilt angle accurately and tuning the PID gains patiently.
This guide first explains why the robot doesn't fall using the inverted pendulum model, then moves on to choosing parts (stepper or DC motor), the wiring diagram, reading the angle with the MPU6050 and the complementary filter. After that you get a compiled Arduino sketch that needs no libraries, a step-by-step tuning table for Kp, Ki and Kd, the effect of the center of mass, the most common reasons it falls and Bluetooth control from your phone with an ESP32. It's an intermediate project; having read the PID control and MPU6050 guides will make it easier.

How does a self-balancing robot work?
Physically, the robot is an inverted pendulum: most of its weight sits above the wheel axle, and left alone it tips over to one side. The only fix is to drive the wheels in the direction of the fall and bring the base back under the center of mass. It's exactly what you do when you balance a broom upright on your palm and move your hand toward the side it's falling to. The robot does this 200 times a second: measure the angle, compute the error, set the motor power, repeat.
A simple formula tells you how fast it must react. At small angles an inverted pendulum falls with a time constant τ = √(L / g), where L is the distance from the wheel axle to the center of mass. For L = 10 cm, τ is about 0.10 seconds; for L = 25 cm it's 0.16 seconds. So the tilt grows about 2.7 times every τ, and the control loop has to run at least 20 times in that window. That's why we lock the loop to 5 milliseconds (200 Hz) and keep delay() and frequent Serial printing out of it.
| Stage | What it does | Value in this project |
|---|---|---|
| Measure | Acceleration and rotation rate are read from the MPU6050 | 14 bytes, 400 kHz I2C, about 0.4 ms |
| Filter | Accelerometer and gyro are combined into a tilt angle | Complementary filter, α = 0.98 |
| PID | A motor command is computed from the angle error | Kp, Ki, Kd; output −255…255 |
| Motor | The command is applied to the wheels | PWM for DC motors, step rate for steppers |
| Loop | Everything repeats at a fixed interval | 5 ms (200 Hz) |
Parts list
| Part | Recommended | Note |
|---|---|---|
| Controller | Arduino Nano or Uno; ESP32 for remote control | The Nano is small and light, so it fits the chassis easily |
| Tilt sensor | MPU6050 (GY-521 module) | Mount it close to the wheel axle and firmly |
| Motors | 12 V, 200–350 rpm metal gear DC motors or NEMA 17 steppers | Yellow plastic TT gear motors are not recommended |
| Motor driver | L298N or TB6612FNG (DC); A4988 or DRV8825 (stepper) | Set the current limit (Vref) on stepper drivers |
| Wheels | 65–90 mm diameter, rubber | Bigger wheels correct faster at the same rpm |
| Battery | 3S LiPo (11.1 V) or three 18650 cells in series | A full pack gives 12.6 V |
| Regulator | LM2596 buck converter module | Step the battery down to 7 V and feed the Arduino VIN pin |
| Chassis | 2–3 decks of acrylic or PCB plate, M3 standoffs | It must be rigid, not flexible |
Stepper or DC motor?
Motor choice is the biggest factor in how easily the robot balances. A stepper turns a fixed angle per step, so it follows the speed command exactly, has no gear backlash and both wheels turn at the same speed; most of the steadiest hobby robots use NEMA 17 steppers with A4988 drivers. In return they're heavier, draw current even when standing still and skip steps if pushed to accelerate too hard. A geared DC motor is lighter and cheaper, but gear backlash and the dead zone where it doesn't turn at low PWM make the robot jitter in place. The code partly compensates for both; still, metal gears and at least 200 rpm are a must. For the general differences between motor types, see DC vs servo vs stepper motors.
| Feature | DC motor (geared) | Stepper motor (NEMA 17) |
|---|---|---|
| Speed accuracy | Varies with load and battery voltage | Exactly follows the step rate |
| Gear backlash | Yes, causes jitter | None |
| Driver | L298N, TB6612FNG | A4988, DRV8825 |
| Current | Very little at rest, 1–2 A while correcting | 0.5–1 A per motor even at rest |
| Weight (two motors) | About 150–200 g | About 550–700 g |
| Code | PWM, needs dead-zone compensation | Step generation with a timer interrupt |
| Best for | A light, cheap first robot | A steady, fast and quiet robot |
Wiring diagram: Arduino and ESP32 pins
| Connection | Arduino Uno / Nano | ESP32 |
|---|---|---|
| MPU6050 VCC | 5V | 3V3 |
| MPU6050 GND | GND | GND |
| MPU6050 SDA | A4 | GPIO 21 |
| MPU6050 SCL | A5 | GPIO 22 |
| L298N ENA (left motor speed, PWM) | D5 | GPIO 25 |
| L298N IN1, IN2 (left motor direction) | D7, D8 | GPIO 26, 27 |
| L298N ENB (right motor speed, PWM) | D6 | GPIO 13 |
| L298N IN3, IN4 (right motor direction) | D9, D10 | GPIO 33, 32 |
| L298N GND | GND (common) | GND (common) |
The battery's positive lead goes to the L298N 12V input and to the LM2596 input; set the LM2596 output to 7 V and connect it to the Arduino's VIN pin. The battery negative and the L298N, Arduino and MPU6050 grounds must all meet at one point; without a common ground the motor driver can't read the PWM signal correctly. Remove the jumpers on the L298N ENA and ENB pins, or the motors will always run at full speed. A 470 µF electrolytic capacitor across the driver's supply input keeps the voltage from collapsing during current spikes.
Tilt angle with the MPU6050 and the complementary filter
Because the accelerometer measures the direction of gravity, it gives the angle directly while the robot is still: angle = atan2(−ax, az). But as the robot speeds up and slows down, those motion accelerations leak into the reading, and motor vibration makes the value jump around. The gyroscope measures the rotation rate (°/s); add it up over time and you get a smooth, fast-reacting angle, but even a small zero error turns into several degrees of drift within minutes.
The complementary filter combines the best of both: angle = 0.98 × (angle + gyro × dt) + 0.02 × accel angle. It trusts the gyro in the short term and the accelerometer in the long term. With a 5 ms loop and α = 0.98, the filter's time constant is α × dt / (1 − α) = 0.245 seconds: the gyro handles faster changes and the accelerometer corrects slow drift. A Kalman filter can give a slightly cleaner result, but for a balancing robot the complementary filter is enough and costs very little processing on an Uno. For a comparison of methods, see filtering sensor data.
Arduino code: balancing with PID
- The sketch uses no external libraries; the MPU6050 is read directly with Wire. Select your board and upload.
- At power-up, lay the robot down and don't move it for the first two seconds: the code measures the gyro's zero error during that time.
- Set the Serial Monitor to 115200 baud and the line ending to Newline.
- Hold the robot by hand at the exact angle where it balances and send z; the current angle becomes the balance point (targetAngle).
- Send the p, d and i commands in the order of the tuning table (e.g. p25, d0.9, i40). Write the values you find into the Kp, Ki and Kd line so they're ready at every power-up.
1#include <Wire.h>
2
3// Pinler / Pins (L298N)
4const int ENA = 5, IN1 = 7, IN2 = 8; // sol motor / left motor
5const int ENB = 6, IN3 = 9, IN4 = 10; // sağ motor / right motor
6const int MPU_ADDR = 0x68; // AD0 GND'de / AD0 to GND
7
8// Ayarlar / Settings
9const unsigned long LOOP_US = 5000; // 200 Hz kontrol döngüsü / 200 Hz control loop
10const float GYRO_LSB = 65.5; // ±500 °/s aralığında 1 °/s / 1 °/s at ±500 °/s
11const float ALPHA = 0.98; // tamamlayıcı filtre katsayısı / complementary filter weight
12const int MIN_PWM = 35; // motorun dönmeye başladığı PWM / PWM where the motor starts turning
13const float FALL_ANGLE = 40.0; // bu eğimden sonra motorları kes / cut the motors beyond this tilt
14
15float Kp = 0.0, Ki = 0.0, Kd = 0.0; // ayar tablosuyla bul, buraya yaz / tune with the table, then write here
16float targetAngle = 0.0; // denge noktası, "z" komutuyla ölç / balance point, measure with "z"
17
18float angle = 0, gyroOffset = 0, iTerm = 0, out = 0;
19bool fallen = true; // robot yerde mi? / is the robot lying down?
20unsigned long lastLoop = 0, lastPrint = 0;
21char buf[12];
22byte len = 0;
23
24void writeReg(uint8_t reg, uint8_t val) {
25 Wire.beginTransmission(MPU_ADDR);
26 Wire.write(reg);
27 Wire.write(val);
28 Wire.endTransmission();
29}
30
31bool readImu(int16_t &ax, int16_t &az, int16_t &gy) {
32 Wire.beginTransmission(MPU_ADDR);
33 Wire.write(0x3B); // ACCEL_XOUT_H
34 if (Wire.endTransmission(false) != 0) return false;
35 if (Wire.requestFrom(MPU_ADDR, 14) != 14) return false;
36 uint8_t b[14];
37 for (int i = 0; i < 14; i++) b[i] = Wire.read();
38 ax = (int16_t)(((uint16_t)b[0] << 8) | b[1]); // X ivmesi: ileri yön / X accel: forward
39 az = (int16_t)(((uint16_t)b[4] << 8) | b[5]); // Z ivmesi: yukarı / Z accel: up
40 gy = (int16_t)(((uint16_t)b[10] << 8) | b[11]); // Y dönüşü: tekerlek ekseni / Y rate: wheel axle
41 return true;
42}
43
44void setMotor(int en, int inA, int inB, float value) {
45 int pwm = 0;
46 if (value > 0.5) pwm = (int)value + MIN_PWM; // ölü bölgeyi atla / skip the dead zone
47 else if (value < -0.5) pwm = (int)value - MIN_PWM;
48 pwm = constrain(pwm, -255, 255);
49 digitalWrite(inA, pwm > 0 ? HIGH : LOW);
50 digitalWrite(inB, pwm < 0 ? HIGH : LOW);
51 analogWrite(en, abs(pwm));
52}
53
54void readCommands() { // ör. / e.g. p22 i40 d1.1 z
55 while (Serial.available()) {
56 char c = Serial.read();
57 if (c != '\n' && c != '\r') {
58 if (len < sizeof(buf) - 1) buf[len++] = c;
59 continue;
60 }
61 if (len == 0) continue;
62 buf[len] = 0;
63 float v = atof(buf + 1);
64 if (buf[0] == 'p') Kp = v;
65 else if (buf[0] == 'i') Ki = v;
66 else if (buf[0] == 'd') Kd = v;
67 else if (buf[0] == 'z') targetAngle = angle; // şu anki açı denge noktası olsun / current angle becomes the balance point
68 len = 0;
69 Serial.print(F("Kp=")); Serial.print(Kp);
70 Serial.print(F(" Ki=")); Serial.print(Ki);
71 Serial.print(F(" Kd=")); Serial.print(Kd);
72 Serial.print(F(" hedef/target=")); Serial.println(targetAngle);
73 }
74}
75
76void setup() {
77 Serial.begin(115200);
78 int pins[] = {ENA, IN1, IN2, ENB, IN3, IN4};
79 for (int p : pins) pinMode(p, OUTPUT);
80 Wire.begin();
81 Wire.setClock(400000); // hızlı I2C / fast I2C
82 Wire.setWireTimeout(3000, true); // I2C takılırsa kurtul / recover from a stuck bus
83 writeReg(0x6B, 0x00); // uykudan uyandır / wake up
84 writeReg(0x1A, 0x03); // alçak geçiren filtre ~44 Hz / low-pass ~44 Hz
85 writeReg(0x1B, 0x08); // jiroskop ±500 °/s / gyro ±500 °/s
86 writeReg(0x1C, 0x00); // ivmeölçer ±2 g / accelerometer ±2 g
87 delay(100);
88
89 long sum = 0; // jiroskop sıfırı: robotu kıpırdatma / gyro zero: keep the robot still
90 int n = 0;
91 int16_t ax, az, gy;
92 for (int i = 0; i < 500; i++) {
93 if (readImu(ax, az, gy)) { sum += gy; n++; }
94 delay(2);
95 }
96 gyroOffset = n ? (float)sum / n : 0;
97 readImu(ax, az, gy);
98 angle = atan2(-(float)ax, (float)az) * RAD_TO_DEG; // başlangıç açısı / starting angle
99 lastLoop = micros();
100}
101
102void loop() {
103 readCommands();
104 unsigned long now = micros();
105 if (now - lastLoop < LOOP_US) return; // sabit döngü süresi / fixed loop time
106 float dt = (now - lastLoop) * 1e-6;
107 lastLoop = now;
108
109 int16_t ax, az, gy;
110 if (!readImu(ax, az, gy)) return;
111 float rate = (gy - gyroOffset) / GYRO_LSB; // °/s
112 float accAngle = atan2(-(float)ax, (float)az) * RAD_TO_DEG; // ivmeden açı / angle from accel
113 angle = ALPHA * (angle + rate * dt) + (1 - ALPHA) * accAngle; // tamamlayıcı filtre / complementary filter
114
115 float error = angle - targetAngle;
116 if (fallen && fabs(error) < 3) { fallen = false; iTerm = 0; } // dik tutunca başla / start when held upright
117 if (!fallen && fabs(error) > FALL_ANGLE) fallen = true; // düştü / fell over
118
119 out = 0;
120 if (!fallen) {
121 iTerm = constrain(iTerm + Ki * error * dt, -100, 100); // integral sınırı / anti-windup
122 out = constrain(Kp * error + iTerm + Kd * rate, -255, 255);
123 }
124 setMotor(ENA, IN1, IN2, out);
125 setMotor(ENB, IN3, IN4, out);
126
127 if (millis() - lastPrint >= 100) { // 10 Hz yazdır, döngüyü yavaşlatma / print at 10 Hz
128 lastPrint = millis();
129 Serial.print(angle, 2);
130 Serial.print('\t');
131 Serial.println(out, 0);
132 }
133}| Variable | Purpose | Typical value |
|---|---|---|
| LOOP_US | Length of the control loop | 5000 µs (200 Hz) |
| ALPHA | Share of the gyro in the complementary filter | 0.98 |
| MIN_PWM | PWM where the motor starts turning; skips the dead zone | 25–50 |
| FALL_ANGLE | Beyond this tilt the robot counts as fallen and the motors stop | 40° |
| Kp | Motor power per degree of angle error | 15–40 (DC motor) |
| Ki | Removes accumulated error, reduces drift | 0–100 |
| Kd | Brakes against rotation speed, damps oscillation | 0.4–1.5 |
| targetAngle | The angle at which the robot balances | −3…+3° |
How to tune Kp, Ki and Kd: a step-by-step table
PID tuning is the most time-consuming part of this project, and the values come out different on every robot: motor speed, wheel diameter, weight and battery voltage all change them. The rule is simple: change only one gain at a time, keep the robot on a soft surface and close to your hand, and use a charged battery. The code cuts the motors once the robot tilts beyond 40° and restarts by itself when you hold it upright again, so you don't need to re-upload between tries. Follow the order below and you'll usually have a balancing robot within half an hour.
| Step | What to do | What you'll see | When to stop |
|---|---|---|---|
| 1 | Kp, Ki and Kd at zero; hold the robot balanced and send z | Wheels don't turn, the target angle is saved | When the target angle appears in Serial |
| 2 | Raise Kp in steps of 5 (p5, p10, p15…) | At first the wheels are too weak, then the robot stays up for a few seconds with big back-and-forth swings | When it stays up, even while swinging |
| 3 | Raise Kd in steps of 0.1 (d0.1, d0.2…) | The swings shrink and the robot settles in place; too much causes a high-pitched jitter and buzz | When jitter starts, reduce the value by 25% |
| 4 | Raise Kp by 10–20%, raise Kd a little if needed | It rolls back less when pushed and recovers more quickly | If oscillation returns, go back to the previous value |
| 5 | Raise Ki in steps of 10 (i10, i20…) | The slow drift in one direction gets smaller | If a slow, growing wobble appears, halve it |
| 6 | Final test: push gently, try it on carpet and a slight slope | A well-tuned robot recovers with one or two small moves | Write the values into the code |
Center of mass and mechanical design
It sounds backwards, but a robot with a high center of mass balances more easily. As the formula above shows, the fall slows down as L grows, leaving the control loop more time; that's also why balancing a broom on your palm is easier than balancing a pencil. That's why the heaviest part, the battery, usually goes on the top deck. The price is that a high center of mass demands more torque from the motors to correct. Build a very tall body with weak motors and the robot falls slowly, but the wheels can't catch it.
- Height: a 3-deck body of 20–30 cm is a good start: battery on top, boards in the middle, motors at the bottom.
- Sensor position: put the MPU6050 close to the wheel axle; mounted high, every sway of the body is measured as extra acceleration.
- Left-right balance: the weight must sit evenly on both wheels, or the robot drifts while turning.
- Rigidity: a flexing chassis or a loose motor bracket acts like an extra spring for the PID and creates vibration that never dies out.
- Wheels: rubber wheels of 65–90 mm reduce slipping. The robot's top speed is rpm × π × diameter: for 300 rpm and 80 mm, about 1.26 m/s.
- Cables: tie the battery and motor wires to the chassis; a dangling cable keeps shifting the center of mass.
Stepper version: generating steps with the A4988
In a stepper robot the PID output is turned into a step rate instead of PWM: the bigger the output, the more frequent the steps. The 5 ms calculation in loop() can't produce evenly spaced step pulses, so we hand this job to a Timer1 interrupt. It runs every 40 µs and fires the STEP pin with a separate counter for each motor. Tie the MS1 and MS2 pins of the A4988s to 5 V to select 1/8 microstepping; that gives quiet and smooth motion at low speed. Add the snippet below to the main sketch, remove the L298N pin definitions and setMotor calls, and add setupSteppers() inside setup().
1// A4988 + step motor sürümü (Uno/Nano) / A4988 stepper version (Uno/Nano)
2// MS1, MS2 HIGH, MS3 LOW: 1/8 mikro adım, 1600 adım/tur / 1/8 microstep, 1600 steps/rev
3const int L_STEP = 2, L_DIR = 3, R_STEP = 4, R_DIR = 5, STEP_EN = 8;
4const float STEPS_PER_UNIT = 12.0; // çıkış 255 → ~3000 adım/s / output 255 → ~3000 steps/s
5volatile uint16_t lPeriod = 0, rPeriod = 0; // adım arası 40 µs'lik tik, 0 = dur / 40 µs ticks per step, 0 = stop
6volatile uint16_t lCount = 0, rCount = 0;
7
8void setupSteppers() { // setup() içinde çağır / call it in setup()
9 pinMode(L_STEP, OUTPUT); pinMode(L_DIR, OUTPUT);
10 pinMode(R_STEP, OUTPUT); pinMode(R_DIR, OUTPUT);
11 pinMode(STEP_EN, OUTPUT);
12 digitalWrite(STEP_EN, LOW); // A4988 EN aktif LOW / A4988 EN is active LOW
13 noInterrupts();
14 TCCR1A = 0;
15 TCCR1B = (1 << WGM12) | (1 << CS11); // CTC modu, 8 bölücü: 2 MHz / CTC mode, prescaler 8: 2 MHz
16 OCR1A = 79; // 2 MHz / 80 = 25 kHz, her 40 µs / every 40 µs
17 TIMSK1 = (1 << OCIE1A);
18 interrupts();
19}
20
21ISR(TIMER1_COMPA_vect) { // adım darbelerini üretir / generates the step pulses
22 if (lPeriod) {
23 if (++lCount >= lPeriod) { lCount = 0; digitalWrite(L_STEP, HIGH); }
24 else if (lCount == 1) digitalWrite(L_STEP, LOW);
25 }
26 if (rPeriod) {
27 if (++rCount >= rPeriod) { rCount = 0; digitalWrite(R_STEP, HIGH); }
28 else if (rCount == 1) digitalWrite(R_STEP, LOW);
29 }
30}
31
32void setStepper(int dirPin, volatile uint16_t &period, float value, bool mirrored) {
33 float sps = value * STEPS_PER_UNIT; // adım/s / steps per second
34 digitalWrite(dirPin, (sps > 0) != mirrored ? HIGH : LOW); // yön / direction
35 sps = fabs(sps);
36 uint16_t p = sps < 20 ? 0 : (uint16_t)(25000.0 / sps); // 25 kHz / adım hızı / 25 kHz / step rate
37 if (p == 1) p = 2; // en fazla 12,5 kHz / at most 12.5 kHz
38 noInterrupts();
39 period = p;
40 interrupts();
41}
42
43// loop() içinde setMotor yerine / in loop() instead of setMotor:
44// setStepper(L_DIR, lPeriod, out, false);
45// setStepper(R_DIR, rPeriod, out, true); // sağ motor ayna konumda / right motor is mirroredWith Timer1 used for this, analogWrite no longer works on the Uno's D9 and D10 pins; you don't need them in this version. With steppers the PID output is a direct speed command, so the gains come out different from the DC version; start the tuning table with Kp again. Set the A4988 current limit to about 70% of the rated current on the motor label; the Vref calculation is explained step by step in the A4988 stepper driver guide. Set it too low and the robot skips steps and falls on a hard push; too high and the motors and drivers heat up for nothing.
Bluetooth remote control with the ESP32
The obvious way to drive the robot from your phone is to shift the target angle a few degrees forward. But a constant forward lean means constant acceleration: holding a tilted pendulum up requires an acceleration of a = g × tan(angle), so even a 2° lean adds 0.34 m/s of speed every second. After a few seconds the motors hit full power and the robot falls. The fix is a second loop: the code estimates the robot's speed from the average motor command and changes the tilt angle by up to 6° based on the difference between target speed and estimate. If the robot goes faster than requested, it leans back and slows down; if it's slower, it leans forward. The same loop also reduces drift when you're not driving it.
1#include <Wire.h>
2#include <BluetoothSerial.h>
3
4BluetoothSerial SerialBT;
5
6const int ENA = 25, IN1 = 26, IN2 = 27; // sol motor / left motor
7const int ENB = 13, IN3 = 33, IN4 = 32; // sağ motor / right motor
8const int PWM_FREQ = 1000, PWM_BITS = 8; // 1 kHz, 0-255
9const int MPU_ADDR = 0x68;
10const unsigned long LOOP_US = 5000; // 200 Hz
11const float GYRO_LSB = 65.5, ALPHA = 0.98, FALL_ANGLE = 40.0;
12const int MIN_PWM = 35;
13const float DRIVE = 60, TURN = 40; // ileri hız ve dönüş farkı / forward speed and turn difference
14
15float Kp = 0.0, Ki = 0.0, Kd = 0.0; // Uno'da bulduğun değerler / the values you found
16float Ks = 0.02; // hız döngüsü, derece / PWM / speed loop, degrees per PWM
17float balanceAngle = 0.0; // mekanik denge noktası / mechanical balance point
18float angle = 0, gyroOffset = 0, iTerm = 0, out = 0, speedEst = 0;
19float driveTarget = 0, drive = 0, turn = 0;
20bool fallen = true;
21unsigned long lastLoop = 0;
22char buf[12];
23byte len = 0;
24
25void writeReg(uint8_t reg, uint8_t val) {
26 Wire.beginTransmission(MPU_ADDR);
27 Wire.write(reg);
28 Wire.write(val);
29 Wire.endTransmission();
30}
31
32bool readImu(int16_t &ax, int16_t &az, int16_t &gy) {
33 Wire.beginTransmission(MPU_ADDR);
34 Wire.write(0x3B);
35 if (Wire.endTransmission(false) != 0) return false;
36 if (Wire.requestFrom((uint8_t)MPU_ADDR, (uint8_t)14) != 14) return false;
37 uint8_t b[14];
38 for (int i = 0; i < 14; i++) b[i] = Wire.read();
39 ax = (int16_t)(((uint16_t)b[0] << 8) | b[1]);
40 az = (int16_t)(((uint16_t)b[4] << 8) | b[5]);
41 gy = (int16_t)(((uint16_t)b[10] << 8) | b[11]);
42 return true;
43}
44
45void pwmWrite(int pin, int channel, int duty) {
46#if ESP_ARDUINO_VERSION_MAJOR >= 3
47 ledcWrite(pin, duty); // çekirdek 3.x: pin ile / core 3.x: by pin
48#else
49 ledcWrite(channel, duty); // çekirdek 2.x: kanal ile / core 2.x: by channel
50#endif
51}
52
53void setMotor(int en, int channel, int inA, int inB, float value) {
54 int pwm = 0;
55 if (value > 0.5) pwm = (int)value + MIN_PWM;
56 else if (value < -0.5) pwm = (int)value - MIN_PWM;
57 pwm = constrain(pwm, -255, 255);
58 digitalWrite(inA, pwm > 0 ? HIGH : LOW);
59 digitalWrite(inB, pwm < 0 ? HIGH : LOW);
60 pwmWrite(en, channel, abs(pwm));
61}
62
63void handleChar(char c) { // F B L R S tek harf, p i d k z satır / single letters, lines for tuning
64 if (c == 'F') { driveTarget = DRIVE; turn = 0; return; }
65 if (c == 'B') { driveTarget = -DRIVE; turn = 0; return; }
66 if (c == 'L') { turn = -TURN; return; }
67 if (c == 'R') { turn = TURN; return; }
68 if (c == 'S') { driveTarget = 0; turn = 0; return; }
69 if (c != '\n' && c != '\r') {
70 if (len < sizeof(buf) - 1) buf[len++] = c;
71 return;
72 }
73 if (len == 0) return;
74 buf[len] = 0;
75 float v = atof(buf + 1);
76 if (buf[0] == 'p') Kp = v;
77 else if (buf[0] == 'i') Ki = v;
78 else if (buf[0] == 'd') Kd = v;
79 else if (buf[0] == 'k') Ks = v;
80 else if (buf[0] == 'z') balanceAngle = angle;
81 len = 0;
82 SerialBT.printf("Kp=%.2f Ki=%.2f Kd=%.2f Ks=%.3f denge/balance=%.2f\n", Kp, Ki, Kd, Ks, balanceAngle);
83}
84
85void setup() {
86 Serial.begin(115200);
87 SerialBT.begin("BlueGrays-Balance"); // telefonda görünen ad / name shown on the phone
88 int pins[] = {IN1, IN2, IN3, IN4};
89 for (int p : pins) pinMode(p, OUTPUT);
90#if ESP_ARDUINO_VERSION_MAJOR >= 3
91 ledcAttach(ENA, PWM_FREQ, PWM_BITS);
92 ledcAttach(ENB, PWM_FREQ, PWM_BITS);
93#else
94 ledcSetup(0, PWM_FREQ, PWM_BITS); ledcAttachPin(ENA, 0);
95 ledcSetup(1, PWM_FREQ, PWM_BITS); ledcAttachPin(ENB, 1);
96#endif
97 Wire.begin(21, 22); // SDA, SCL
98 Wire.setClock(400000);
99 writeReg(0x6B, 0x00);
100 writeReg(0x1A, 0x03);
101 writeReg(0x1B, 0x08);
102 writeReg(0x1C, 0x00);
103 delay(100);
104 long sum = 0;
105 int n = 0;
106 int16_t ax, az, gy;
107 for (int i = 0; i < 500; i++) {
108 if (readImu(ax, az, gy)) { sum += gy; n++; }
109 delay(2);
110 }
111 gyroOffset = n ? (float)sum / n : 0;
112 readImu(ax, az, gy);
113 angle = atan2(-(float)ax, (float)az) * RAD_TO_DEG;
114 lastLoop = micros();
115}
116
117void loop() {
118 while (SerialBT.available()) handleChar(SerialBT.read());
119 if (!SerialBT.hasClient()) { driveTarget = 0; turn = 0; } // bağlantı koptu: dur / link lost: stop
120
121 unsigned long now = micros();
122 if (now - lastLoop < LOOP_US) return;
123 float dt = (now - lastLoop) * 1e-6;
124 lastLoop = now;
125
126 int16_t ax, az, gy;
127 if (!readImu(ax, az, gy)) return;
128 float rate = (gy - gyroOffset) / GYRO_LSB;
129 float accAngle = atan2(-(float)ax, (float)az) * RAD_TO_DEG;
130 angle = ALPHA * (angle + rate * dt) + (1 - ALPHA) * accAngle;
131
132 drive += constrain(driveTarget - drive, -0.5f, 0.5f); // hızı yumuşak değiştir / ramp the speed
133 speedEst = 0.98 * speedEst + 0.02 * out; // motor komutundan hız tahmini / speed estimate from motor command
134 float target = balanceAngle + constrain(Ks * (drive - speedEst), -6.0f, 6.0f); // hız döngüsü / speed loop
135 float error = angle - target;
136
137 if (fallen && fabs(angle - balanceAngle) < 3) { fallen = false; iTerm = 0; speedEst = 0; }
138 if (!fallen && fabs(angle - balanceAngle) > FALL_ANGLE) fallen = true;
139
140 out = 0;
141 if (!fallen) {
142 iTerm = constrain(iTerm + Ki * error * dt, -100.0f, 100.0f);
143 out = constrain(Kp * error + iTerm + Kd * rate, -255.0f, 255.0f);
144 }
145 float t = fallen ? 0 : turn;
146 setMotor(ENA, 0, IN1, IN2, out + t); // sağa dönüşte sol teker hızlı / left wheel faster when turning right
147 setMotor(ENB, 1, IN3, IN4, out - t);
148}The classic Bluetooth (SPP) on the original ESP32 pairs directly with Android phones; connect to the "BlueGrays-Balance" device with any Bluetooth serial terminal or controller app and send single-letter commands. Send the tuning commands with a line ending (newline). The ESP32-S3 and C3 have no classic Bluetooth and iPhones only talk BLE; in that case use the BLE example from the ESP32 Bluetooth and BLE guide with the same commands. Because the Bluetooth library is large, this sketch fills about 80% of the default app partition; if you also want Wi-Fi, you'll need a larger partition scheme.
| Command | What it does |
|---|---|
| F / B | Drives forward / backward (target speed ±60) |
| L / R | Turns left / right (wheel difference ±40) |
| S | Stops; target speed and turn are reset |
| p25, i40, d0.9 | Changes Kp, Ki and Kd from the phone |
| k0.02 | Speed loop gain Ks |
| z | Makes the current angle the balance point |
Why it keeps falling: common causes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| The robot falls to one side right away, wheels turn the wrong way | Motor direction or angle sign reversed | Swap the motor wires (OUT1-OUT2), repeat the angle test |
| The wheels can't keep up with the fall | Kp too low, slow motors or a weak battery | Raise Kp; use motors above 200 rpm and a charged battery |
| Fast jitter and buzzing in place | Kd too high or the sensor is loose | Lower Kd, screw the sensor down |
| A slow oscillation that keeps growing | Too much Ki or large gear backlash | Halve Ki, use metal-gear motors |
| Balances but drifts in one direction | Wrong target angle or weight off to one side | Re-measure the balance angle with z, raise Ki slightly |
| Falls at random, the Arduino restarts | Motor current spikes collapse the voltage | Power the Arduino from a separate regulator, add a 470 µF capacitor |
| Freezes after a while and falls | The I2C bus got stuck | Shorten the wires, keep the setWireTimeout line |
| Works on USB, not on battery | No common GND or low battery voltage | Join all grounds, measure the battery with a multimeter |
Next steps and project ideas
- Speed control with encoders: measure the real speed with motor encoders and feed the speed loop with measurements instead of an estimate; the robot will hold its spot with almost no drift.
- Obstacle-avoiding balancer: add an HC-SR04 distance sensor at the front and make it back off when it sees an obstacle.
- Joystick remote: build a low-latency remote with a second ESP32 and a joystick over ESP-NOW.
- Body with a display: put an OLED display on the top deck to show the angle, PID values and battery voltage.
- Line-following balancer: add infrared sensors underneath and tie the line follower robot logic to the turn command.
A self-balancing robot brings sensor reading, filtering, control theory and mechanics together in one project, which makes it one of the most educational builds there is, and the first time it stands up on its own is hard to forget. In the BlueGrays app you'll find the Bluetooth-controlled L298N car, the obstacle-avoiding robot and the stepper motor projects with wiring diagrams and commented code, step by step, so you can prepare your robot's motor and remote-control side there.
Frequently asked questions
Why does my self-balancing robot keep falling over?
The most common causes are wrong PID gains, a reversed motor direction or angle sign, a wrong balance angle and motors that are too slow. First tilt the robot forward and check that the angle increases and the wheels turn forward, then tune Kp, Kd and Ki in that order. If motor current spikes reset the Arduino, the robot falls at random; power the Arduino from a separate regulator.
What motors are best for a self-balancing robot?
The easiest choice is NEMA 17 steppers with A4988 drivers; with no gear backlash the robot stands steadier. If you go with DC motors, use 12 V, 200–350 rpm metal-gear motors such as the JGA25-370. Yellow plastic TT motors usually aren't good enough because of their backlash.
How do I tune the PID of a self-balancing robot?
There are no universal values; motors, wheel size, weight and battery voltage all change the result. Raise Kp until the robot stays up while oscillating, damp the oscillation with Kd, and finally add just enough Ki to stop the drift. With the DC motor sketch in this guide, Kp usually lands between 15 and 40 and Kd between 0.4 and 1.5.
Can I use an MPU9250 or BNO055 instead of the MPU6050?
Yes. Sensors like the MPU9250, ICM-20948 or BNO055 work too, and the BNO055 even computes the angle on-chip. Still, the MPU6050 is cheap, widely available and more than good enough for a balancing robot. An accelerometer or a gyroscope alone isn't enough; you need both.
Kalman filter or complementary filter?
A Kalman filter statistically balances noise and drift and can give a slightly cleaner angle, but the math and tuning are more complex. The complementary filter is one line, runs very fast on an Uno and is enough for a balancing robot with a well-mounted sensor. Start with the complementary filter and try Kalman only if the problem isn't mechanical.
Can I control a self-balancing robot from my phone?
Yes. With the ESP32's classic Bluetooth or an HC-05 module on the Arduino, you can send forward, backward and turn commands from an Android phone. The key is to use a speed loop instead of shifting the target angle directly; otherwise the robot keeps accelerating and falls. For an iPhone you'll need BLE.
Projects to build after reading this
See all projects
Bluetooth Controlled Car with L298N
Turn your phone into a remote and drive your own robot car. The Arduino receives commands from a remote-control app on your phone through a Bluetooth module and spins the wheels with a motor driver…

Obstacle Avoidance Robot
How about building a smart vehicle that finds its own way? The Obstacle Avoidance Robot constantly scans its surroundings thanks to the ultrasonic sensor in front of it.

Using a Stepper Motor
A motor that turns step by step, exactly as far as you want, like the hand of a clock.

360-Degree Servo from a Stepper Motor
Teach an ordinary stepper motor to go to any angle you want, all the way around the circle.

Control an LED from Your Phone via Bluetooth
A small rehearsal for switching the lights in your room on and off from your phone.

Servo Control with Joystick
Steer two motors with a joystick, just like turning a security camera. Push the stick left or right and the bottom servo motor slowly turns, push it up or down and the top servo tilts up and down…

ESP32 LED Fade with PWM
Smoothly changing the brightness of the LED from 0 to max, from max to 0. We control PWM with analogWrite() as in Arduino - the same syntax as ESP32 Arduino Core 3.0+ works without problems. Pin definition + pinMode + analogWrite is enough.

ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)
In this project, we control the brightness of an LED analogically using a potentiometer. The ESP32's ADC pin reads the 0-3.3V voltage from the potentiometer, and this value is then converted into a PWM (Pulse Width Modulation) signal and sent to the LED. As a result, as you turn the potentiometer, the LED gradually brightens and dims. With Arduino Core 3.0+, analogWrite() can be used directly; on the ESP32-S2/S3, the ADC resolution is fixed at 12-bit.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

