The classic first robot: it drives forward, spots obstacles with an ultrasonic sensor mounted on a servo, and steers around them all by itself.
What you’ll build
An Arduino Uno drives two BO motors through an L298N driver. The HC-SR04 ultrasonic sensor sits on an SG90 servo that sweeps left and right; when something is closer than 25 cm the robot stops, looks both ways, and turns toward the clearer path.
Components you’ll need
| Component | Qty | Price |
|---|---|---|
| Arduino Uno R3 CH340G Compatible Board | 1 | ₹49 |
| L298N | 1 | ₹39 |
| BO Motor | 2 | ₹498 |
| HC-SR04 Ultrasonic Distance Sensor | 1 | ₹89 |
| SG90 Micro Servo Motor 9G | 1 | ₹89 |
| Male to Female Jumper Wires 40pcs 20cm Multicolour | 1 | ₹49 |
| 400 Point Breadboard | 1 | ₹299 |
| TP4056 Li-Ion Battery Charger Module with Protection | 1 | ₹49 |
| Total | ₹1,161 |
Step-by-step guide
- Mount the two BO motors on a chassis (any two-wheel robot chassis works) and wire them to the L298N outputs OUT1/OUT2 and OUT3/OUT4.
- Connect L298N inputs IN1–IN4 to Uno pins D5, D6, D9, D10, and the module’s 5V/GND to the Uno.
- Power the L298N motor supply from a battery pack (6–12V); the TP4056 lets you build a rechargeable Li-ion pack for it.
- Fix the SG90 servo at the front, signal wire to D3; mount the HC-SR04 on the servo horn (Trig D11, Echo D12).
- Upload the sketch, prop the wheels off the ground first, and check both motors spin forward.
- Set it on the floor — it should cruise, stop near obstacles, scan, and pick a direction.
The code
The logic is simple: measure distance ahead; if blocked, stop, look left and right with the servo, and turn toward whichever side is more open.
#include <Servo.h>
Servo neck;
const int trig=11, echo=12;
const int IN1=5, IN2=6, IN3=9, IN4=10;
long readCM(){
digitalWrite(trig,LOW); delayMicroseconds(2);
digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW);
return pulseIn(echo,HIGH,20000)*0.034/2;
}
void drive(int a,int b,int c,int d){ digitalWrite(IN1,a);digitalWrite(IN2,b);digitalWrite(IN3,c);digitalWrite(IN4,d);}
void setup(){
pinMode(trig,OUTPUT); pinMode(echo,INPUT);
for(int p:{IN1,IN2,IN3,IN4}) pinMode(p,OUTPUT);
neck.attach(3); neck.write(90);
}
void loop(){
long d = readCM();
if(d>0 && d<25){
drive(0,0,0,0); delay(200);
neck.write(150); delay(400); long left = readCM();
neck.write(30); delay(400); long right = readCM();
neck.write(90);
if(left>right) drive(0,1,1,0); else drive(1,0,0,1); // pivot
delay(450);
}
drive(1,0,1,0); // forward
}Build this project
Add all 8 required components to your cart in one click — total ₹1,161.
Add all components to cart