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.

What youβll need
- Arduino Uno R3 β the brain
- HC-SR04 Ultrasonic Sensor β detects obstacles
- SG90 Servo β sweeps the sensor left and right
- Smart Car Chassis Kit β frame, motors and wheels
- L298N Motor Driver β drives the motors
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 β