Line follower robot with L298N and TCRT5000
The classic robotics starter: a two-wheeled car that tracks a black line on its own.
Shop by category
Shop all componentsThe classic control-engineering robot. The MPU6050 measures how far the robot leans and how fast it is falling; a complementary filter blends the two into a clean angle, and a PID controller turns that into wheel speed. Lean forward and the wheels roll forward to catch it. Getting it to stand is a lesson in tuning: start with KP alone, add KD to calm the wobble, then a little KI to stop it drifting.
Tick anything you already have and the total updates.
Connects the Uno to your computer to upload code and power it
Six-axis motion sensor: a three-axis accelerometer that feels gravity and bumps, and a three-axis gyro that measures how fast it turns.
Dual H-bridge that lets the board drive two DC motors forwards, backwards and at variable speed.
Raises the cell's 3.0–4.2 V to a steady 5 V for the board
Follow the colours: red is power, dark grey is ground, blue is a signal.
Battery + goes to the L298N 12V terminal and battery − to GND; join that GND to the board GND. Power the Uno from the L298N 5 V output or its own USB power bank. Set the boost converter to 5.0 V with a multimeter before connecting the board. Cell + → boost IN+, cell − (TP4056 OUT−) → boost IN−, then boost OUT+ → board 5V pin and OUT− → GND. A bare 18650 (3.0–4.2 V) cannot run a 5 V board by itself.
self_balancing_robot.inoVerify & upload in Electrolark// Two-wheel self-balancing robot
// Geekobot project library · board: Arduino Uno
// Wiring diagram, parts list and build steps: Geekobot project page "self-balancing-robot"
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
// ---- pins ----
const uint8_t ENA = 3;
const uint8_t IN1 = 2;
const uint8_t IN2 = 4;
const uint8_t IN3 = 6;
const uint8_t IN4 = 7;
const uint8_t ENB = 5;
Adafruit_MPU6050 mpu;
sensors_event_t accEvt, gyrEvt, tmpEvt;
// ---- latest readings ----
float pitchDeg = 0;
float rollDeg = 0;
float shakeG = 0;
// tune in this order: KP until it oscillates, then KD to calm it, then a little KI
float KP = 22.0, KI = 0.8, KD = 0.9;
float SETPOINT = 0.0; // pitch angle at which the robot balances (find it by hand)
const float FALL_DEG = 40; // past this the robot has fallen: stop the motors
float angle = 0, integral = 0, lastErr = 0;
unsigned long lastUs = 0;
void readImu() { mpu.getEvent(&accEvt, &gyrEvt, &tmpEvt); }
float pitchDegNow() { return atan2(accEvt.acceleration.x, sqrt(accEvt.acceleration.y * accEvt.acceleration.y + accEvt.acceleration.z * accEvt.acceleration.z)) * 57.3f; }
float rollDegNow() { return atan2(accEvt.acceleration.y, accEvt.acceleration.z) * 57.3f; }
float shakeGNow() { float a = sqrt(accEvt.acceleration.x * accEvt.acceleration.x + accEvt.acceleration.y * accEvt.acceleration.y + accEvt.acceleration.z * accEvt.acceleration.z) / 9.81f; return fabs(a - 1.0f); }
float gyroZNow() { return gyrEvt.gyro.z * 57.3f; } // turning speed in degrees per second
// speed: -255 (full reverse) to 255 (full forward)
void drive(int left, int right) {
digitalWrite(IN1, left >= 0 ? HIGH : LOW);
digitalWrite(IN2, left >= 0 ? LOW : HIGH);
analogWrite(ENA, constrain(abs(left), 0, 255));
digitalWrite(IN3, right >= 0 ? HIGH : LOW);
digitalWrite(IN4, right >= 0 ? LOW : HIGH);
analogWrite(ENB, constrain(abs(right), 0, 255));
}
void setup() {
Serial.begin(115200);
if (!mpu.begin()) Serial.println(F("MPU6050 not found"));
mpu.setAccelerometerRange(MPU6050_RANGE_4_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
readImu(); angle = pitchDegNow(); lastUs = micros();
}
void loop() {
unsigned long now = micros();
if (now - lastUs < 5000) return; // 200 updates a second
float dt = (now - lastUs) / 1e6f; lastUs = now;
readImu();
float accAngle = pitchDegNow();
float rate = gyrEvt.gyro.y * 57.3f; // degrees per second around the wheel axle
angle = 0.98f * (angle + rate * dt) + 0.02f * accAngle; // complementary filter: gyro for speed, accelerometer for drift
if (fabs(angle - SETPOINT) > FALL_DEG) { drive(0, 0); integral = 0; return; }
float err = angle - SETPOINT;
integral = constrain(integral + err * dt, -40, 40);
float out = KP * err + KI * integral + KD * rate;
int pwm = constrain((int)out, -255, 255);
if (pwm > 0 && pwm < 35) pwm = 35; else if (pwm < 0 && pwm > -35) pwm = -35; // overcome gearbox friction
drive(pwm, pwm);
static unsigned long lastLog = 0;
if (millis() - lastLog > 200) { lastLog = millis(); Serial.print(angle, 1); Serial.print(F(" deg, pwm ")); Serial.println(pwm); }
}
The sketch above runs here on a simulated Arduino Uno. Move the sliders for the sensors and buttons it reads, and watch the Serial monitor, display and outputs change.
Check SDA and SCL are not swapped. An I²C scanner should show 0x68 (0x69 if AD0 is tied high).
Keep I²C wires short, add a 100 nF capacitor across VCC and GND, and mount the board away from motor wires.
The ENA/ENB jumpers must be removed and wired to PWM pins, and the battery GND must connect to the board GND.
Swap that motor's two wires on the screw terminal.
SETPOINT is wrong, or the motors are wired so they drive away from the fall. Swap both motor leads if it runs away instead of catching itself.
KP or KD is too high. Lower KD first.
Open the Serial Monitor at 115200 baud and check for messages. Make sure you chose the right board and port in the Arduino IDE.
Close other programs using the serial port, try another USB cable (some are charge-only) and press reset just before uploading.
Yes. Most of the code works unchanged on an ESP32 with the ESP32 board package. Watch for 5 V modules: ESP32 pins are 3.3 V, so 5 V output signals need a resistor divider.
Use a 5 V USB phone charger or a power bank into the board's USB port. Loads such as pumps, fans and solenoids need their own supply.
10 parts: Uno R3 CH340G ATmega328p Compatible Development Board, Arduino USB-A to USB-B Data Cable for UNO/MEGA, GY-521 MPU6050 6-Axis Gyro and Accelerometer Module, L298N Dual H-Bridge Motor Driver Module, 2WD Smart Robot Car Chassis Kit, 2 × 18650 Battery Holder, 2 × 18650 Li-ion Rechargeable Cell 2600mAh, MT3608 Mini Boost Converter Module, Solderless Breadboard (830 points) and Dupont Jumper Wires (40 pcs). Tools: Digital Multimeter and Wire Stripper and Cutter. On this page you can tick the parts you already have and add only the rest to your cart.
It is a advanced project and takes about 5–6 hours. The build on this page has 9 steps.
No. This page has the complete, tested code (self_balancing_robot.ino). Install these libraries first: Adafruit MPU6050 and Adafruit Unified Sensor.
Yes. The Run it panel under the code runs this exact sketch on a simulated board. Move the sliders or press the buttons for the sensors it reads, and the Serial monitor, display and outputs react as they will on the real build. It is a simulation, so real readings depend on your parts and wiring.
About ₹1,303 for the parts at the prices on this page, plus tools if you do not have them. Quantity price breaks lower the cost when you build several.
Accelerometers, gyros and tilt angles; H-bridges and PWM speed control.
Ideas that reuse this build: Gyro square-path robot and Obstacle-avoiding robot. They are listed under Take it further on this page.
The classic robotics starter: a two-wheeled car that tracks a black line on its own.
A robot that looks left and right with its ultrasonic "head" and picks the clearest way.
Roams a tabletop without ever driving off the edge.
Drive a 4WD car from your Android phone over Bluetooth.
Learning project. Check every circuit and the datasheet of each part before you power it up.
0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0 0.0 deg, pwm 0
A simulation of the sketch above, so you know what to expect. Real readings vary with your parts and wiring.