0

Build an Obstacle-Avoiding Robot with Arduino and an Ultrasonic Sensor

A robot that drives itself and dodges obstacles using an ultrasonic sensor on a servo β€” with the core Arduino logic and a full parts list.

An obstacle-avoiding robot drives around on its own and turns away whenever something blocks its path. It uses an ultrasonic sensor on a servo to β€œlook” left and right β€” a brilliant next step after the line follower.

HC-SR04 ultrasonic sensor
The HC-SR04 measures the distance to obstacles.

What you’ll need

How it works

The robot drives forward while the ultrasonic sensor watches ahead. When an obstacle comes within, say, 20 cm, the Arduino stops, turns the servo to look left and right, compares the two distances, and turns toward the clearer side.

Core logic

long readCm(){
  digitalWrite(trig,LOW); delayMicroseconds(2);
  digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW);
  return pulseIn(echo,HIGH)*0.0343/2;
}
void loop(){
  if(readCm() > 20){ forward(); }
  else {
    stopBot();
    servo.write(150); delay(300); long left  = readCm();
    servo.write(30);  delay(300); long right = readCm();
    servo.write(90);
    if(left > right) turnLeft(); else turnRight();
    delay(400);
  }
}

(Use the motor-driver helper functions from our line-following robot guide.)

Get the parts

Everything for this build is in stock at Smart Home | Arduino Corner — Shaheen Market, DAV College Road, Rawalpindi — with cash-on-delivery across Pakistan. Start with an HC-SR04, an SG90 servo and a chassis kit. Browse the store β†’

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us on WhatsApp