ArrowtronElectronics Store
Free shipping over ₹999
100% genuine components
Dispatch in 1–2 days
Secure payments · UPI, Cards

Obstacle-Avoiding Robot Car with HC-SR04 and L298N

The classic first robot: it drives forward, spots obstacles with an ultrasonic sensor mounted on a servo, and steers around them all by itself.

Intermediate~3 hours8 components

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

ComponentQtyPrice
Arduino Uno R3 CH340G Compatible Board1₹49
L298N1₹39
BO Motor2₹498
HC-SR04 Ultrasonic Distance Sensor1₹89
SG90 Micro Servo Motor 9G1₹89
Male to Female Jumper Wires 40pcs 20cm Multicolour1₹49
400 Point Breadboard1₹299
TP4056 Li-Ion Battery Charger Module with Protection1₹49
Total₹1,161

Step-by-step guide

  1. 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.
  2. Connect L298N inputs IN1–IN4 to Uno pins D5, D6, D9, D10, and the module’s 5V/GND to the Uno.
  3. Power the L298N motor supply from a battery pack (6–12V); the TP4056 lets you build a rechargeable Li-ion pack for it.
  4. Fix the SG90 servo at the front, signal wire to D3; mount the HC-SR04 on the servo horn (Trig D11, Echo D12).
  5. Upload the sketch, prop the wheels off the ground first, and check both motors spin forward.
  6. 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
Scroll to Top