Introduction
An obstacle-avoiding robot uses an ultrasonic sensor to detect objects in its path and autonomously navigates around them. This project combines distance sensing with motor control logic.
Components Required
- Arduino Uno
- HC-SR04 Ultrasonic Sensor
- L298N Motor Driver
- 2× DC Gear Motors (with wheels)
- SG90 Servo Motor (to scan left/right)
- Robot chassis
- 9V battery or 7.4V Li-Po
- Jumper wires
How It Works
- The ultrasonic sensor continuously measures the distance ahead
- If an obstacle is detected within 25cm, the robot stops
- The servo sweeps the sensor left and right to scan both directions
- The robot turns toward the direction with more clearance
- It continues forward until the next obstacle
The Code
#include <Servo.h>
// Motor pins
const int ENA = 3, IN1 = 5, IN2 = 6;
const int ENB = 11, IN3 = 9, IN4 = 10;
// Ultrasonic
const int trigPin = 7, echoPin = 8;
Servo scanServo;
int speed = 180;
long getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000);
return duration * 0.034 / 2;
}
void moveForward() {
analogWrite(ENA, speed); analogWrite(ENB, speed);
digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);
}
void turnLeft() {
analogWrite(ENA, speed); analogWrite(ENB, speed);
digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);
}
void turnRight() {
analogWrite(ENA, speed); analogWrite(ENB, speed);
digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW); digitalWrite(IN4, HIGH);
}
void stopMotors() {
analogWrite(ENA, 0); analogWrite(ENB, 0);
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
scanServo.attach(12);
scanServo.write(90); // center
delay(1000);
}
void loop() {
long dist = getDistance();
if (dist > 25 || dist == 0) {
moveForward();
} else {
stopMotors();
delay(300);
// Scan right
scanServo.write(30);
delay(500);
long rightDist = getDistance();
// Scan left
scanServo.write(150);
delay(500);
long leftDist = getDistance();
// Re-center
scanServo.write(90);
delay(300);
if (rightDist > leftDist) {
turnRight();
delay(400);
} else {
turnLeft();
delay(400);
}
stopMotors();
}
delay(50);
}Testing & Calibration
- Adjust
speedvalue (0-255) for your motors - Modify the 25cm threshold based on your needs
- Tune the turn
delay(400)to get approximately 90° turns