Arduino-Powered Autonomous Obstacle Avoidance Robot with Servo Control

Arduino Obstacle Avoidance Robot with Servo Control – MakeMindz
Robotics Arduino UNO HC-SR04 Beginner–Intermediate

Arduino-Powered Autonomous Obstacle Avoidance Robot with Servo Control

Build a self-navigating robot that scans its environment with a servo-mounted ultrasonic sensor, detects obstacles in real time, and intelligently chooses the clearest path — no remote control needed.

What You'll Build

A 4-wheeled autonomous robot that uses an HC-SR04 sensor mounted on a servo to scan 180° and navigate around obstacles — completely hands-free.

Difficulty

Beginner – Intermediate

⏱️

Build Time

2 – 3 Hours

💰

Est. Cost

₹600 – ₹1,200

📡

Range Threshold

15 cm detection

How It Works

01
Continuous distance measurement

The HC-SR04 ultrasonic sensor pings every loop cycle, measuring the distance to the nearest obstacle in cm.

02
Obstacle detected ≤ 15 cm → Stop & back up

If the measured distance falls below 15 cm, all four motors stop, then reverse briefly to create clearance.

03
Servo scans right → then left

The servo rotates the sensor to 50° (right) and 170° (left), reading the distance in each direction to find the clearer path.

04
Turn toward the clearer side

The Arduino compares both readings. If the right distance ≥ left distance → turn right; otherwise → turn left.

05
Path clear → Move forward (ramped acceleration)

If no obstacle is detected, all motors ramp up smoothly from 0 → 190 to avoid wheel slip and jerky starts.

Components Required

Component Qty Purpose
Arduino UNO (R3)×1Main microcontroller — runs all logic
HC-SR04 Ultrasonic Sensor×1Measures distance to obstacles (2–400 cm)
SG90 Servo Motor×1Rotates the sensor for 180° scanning
L298N Motor Driver Module×1Controls 4 DC motors via PWM
DC Gear Motors + Wheels×4Drive the robot chassis
4WD Robot Chassis×1Structural frame for all components
7.4V Li-ion Battery Pack×1Powers motors and Arduino
Jumper Wires (M-M, M-F)×30+All connections
📦
Library dependencies: Install AFMotor.h (Adafruit Motor Shield), NewPing.h, and Servo.h from the Arduino Library Manager before uploading the sketch.

Circuit Connections

obstacle_avoidance_robot.json — Wiring Overview
Arduino Obstacle Avoidance Robot — Wiring Overview ARDUINO UNO A0 (TRIG) A1 (ECHO) D3-D8 (Motors) D10 (Servo) 5V / GND HC-SR04 Ultrasonic Sensor VCC → 5V GND → GND TRIG → A0 | ECHO → A1 SG90 SERVO Sensor Mount Red → 5V Brown → GND Orange → D10 L298N Motor Driver IN1-IN4 → D3,D4,D5,D7 ENA → D6 | ENB → D8 12V → Battery+ GND → Battery− + Arduino 5V out → Arduino 5V Motor 1 & 2 (Left) Motor 3 & 4 (Right) BATTERY PACK 7.4V Li-ion + → L298N 12V IN − → Common GND LEGEND HC-SR04 Connections Servo Connections Motor Driver Control Power Rail

Pin Connection Map

HC-SR04 Ultrasonic

VCC→ Arduino 5V
GND→ Arduino GND
TRIG→ Arduino A0
ECHO→ Arduino A1

SG90 Servo Motor

Red→ Arduino 5V
Brown→ Arduino GND
Orange→ Arduino D10 (PWM)

L298N Motor Driver

IN1-IN4→ D3, D4, D5, D7
ENA→ D6 (PWM speed)
ENB→ D8 (PWM speed)
12V→ Battery positive
GND→ Battery − & Arduino GND
5V out→ Arduino VIN (optional)

Motors (via L298N)

OUT1-2→ Motor 1 & Motor 2 (Left)
OUT3-4→ Motor 3 & Motor 4 (Right)

Step-by-Step Instructions

1

Assemble the Robot Chassis

Mount all four DC gear motors onto the chassis frame using the included hardware. Attach the wheels securely. Place the Arduino UNO and L298N motor driver on the top deck using double-sided tape or standoffs.

2

Mount the Servo + Sensor

Glue or screw the SG90 servo at the front-centre of the chassis. Fix the HC-SR04 sensor on the servo horn so it rotates freely. Ensure it has a clear line-of-sight forward — no wires blocking the path.

3

Wire the HC-SR04 to Arduino

  • VCC → Arduino 5V
  • GND → Arduino GND
  • TRIG → Arduino A0
  • ECHO → Arduino A1
4

Wire the Servo Motor

  • Red (VCC) → Arduino 5V
  • Brown (GND) → Arduino GND
  • Orange (Signal) → Arduino D10
5

Wire the L298N Motor Driver

  • IN1 → D3 | IN2 → D4 | IN3 → D5 | IN4 → D7
  • ENA → D6 (PWM) | ENB → D8 (PWM)
  • OUT1 & OUT2 → Motor 1 & 2 (left side)
  • OUT3 & OUT4 → Motor 3 & 4 (right side)
  • 12V → Battery positive | GND → Battery negative + Arduino GND
6

Install Arduino Libraries

Open the Arduino IDE. Go to Sketch → Include Library → Manage Libraries and install:

  • AFMotor (Adafruit Motor Shield library)
  • NewPing by Tim Eckel
  • Servo (built-in, no install needed)
7

Upload the Code

Copy the full Arduino sketch from the section below. Connect your Arduino UNO via USB, select the correct Port and Board (Arduino UNO), then click Upload.

8

Test on a Clear Surface

Power the robot via the battery pack. Place it on a flat surface with objects around. The servo should sweep to 115° (centre), then the robot should begin moving forward and avoiding obstacles automatically.

⚠️
If the robot turns the wrong way, swap the motor wire polarity on the L298N output terminals (OUT1/OUT2 or OUT3/OUT4) until forward motion is correct.

Full Source Code

obstacle_avoidance_robot.ino
// ─────────────────────────────────────────────────────
// Arduino Autonomous Obstacle Avoidance Robot
// MakeMindz.com | HC-SR04 + Servo + L298N (AFMotor)
// ─────────────────────────────────────────────────────

#include <AFMotor.h>   // Adafruit Motor Shield library
#include <NewPing.h>   // Ultrasonic ping library
#include <Servo.h>     // Servo control

// ── Pin Definitions ──────────────────────────────────
#define TRIG_PIN        A0
#define ECHO_PIN        A1
#define MAX_DISTANCE   200   // Max sensor range (cm)
#define MAX_SPEED      190   // Top motor speed (0-255)
#define MAX_SPEED_OFFSET 20

// ── Object Initialisation ────────────────────────────
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);   // Motor 1 (left front)
AF_DCMotor motor2(2, MOTOR12_1KHZ);   // Motor 2 (left rear)
AF_DCMotor motor3(3, MOTOR34_1KHZ);   // Motor 3 (right front)
AF_DCMotor motor4(4, MOTOR34_1KHZ);   // Motor 4 (right rear)
Servo myservo;

// ── Global Variables ─────────────────────────────────
boolean goesForward = false;
int distance = 100;
int speedSet  = 0;

// ─────────────────────────────────────────────────────
void setup() {
  myservo.attach(10);     // Servo on pin 10
  myservo.write(115);     // Centre position (forward)
  delay(2000);            // Stabilise on power-up

  // Take 4 readings to initialise distance
  for (int i = 0; i < 4; i++) {
    distance = readPing();
    delay(100);
  }
}

// ─────────────────────────────────────────────────────
void loop() {
  int distanceR = 0;
  int distanceL = 0;
  delay(40);

  if (distance <= 15) {         // Obstacle within 15 cm
    moveStop();
    delay(100);
    moveBackward();
    delay(300);
    moveStop();
    delay(200);

    distanceR = lookRight();    // Scan right
    delay(200);
    distanceL = lookLeft();     // Scan left
    delay(200);

    if (distanceR >= distanceL) {
      turnRight();
    } else {
      turnLeft();
    }
    moveStop();

  } else {
    moveForward();              // Path clear — go!
  }

  distance = readPing();        // Refresh distance
}

// ── Servo Scanning Functions ─────────────────────────
int lookRight() {
  myservo.write(50);           // Rotate sensor right
  delay(500);
  int d = readPing();
  delay(100);
  myservo.write(115);          // Return to centre
  return d;
}

int lookLeft() {
  myservo.write(170);          // Rotate sensor left
  delay(500);
  int d = readPing();
  delay(100);
  myservo.write(115);          // Return to centre
  return d;
}

// ── Ultrasonic Read ───────────────────────────────────
int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if (cm == 0) cm = 250;      // 0 = out of range → treat as clear
  return cm;
}

// ── Motor Control Functions ───────────────────────────
void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
}

void moveForward() {
  if (!goesForward) {
    goesForward = true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    // Ramp up speed smoothly
    for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) {
      motor1.setSpeed(speedSet);
      motor2.setSpeed(speedSet);
      motor3.setSpeed(speedSet);
      motor4.setSpeed(speedSet);
      delay(5);
    }
  }
}

void moveBackward() {
  goesForward = false;
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
  }
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  delay(500);
  // Resume all forward after turn
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

Test Without Hardware

🧪

Run it in your browser — no robot required

Use Wokwi or Tinkercad to simulate the full circuit. Load the diagram.json above into Wokwi, paste the Arduino code, and click Run to watch the robot logic execute live.

💡
Wokwi tip: After importing diagram.json, create a new file called sketch.ino and paste the full code. The AFMotor library is automatically available in Wokwi — no manual install needed.

Key Features

🤖

Fully Autonomous

Zero human input required — the robot decides everything on its own.

🔄

180° Scanning

Servo sweeps the sensor left and right for intelligent path selection.

📈

Smooth Acceleration

Speed ramps from 0 → 190 in increments to prevent wheel slip.

📶

Expandable

Add Bluetooth (HC-05), WiFi (ESP8266), or a camera module easily.

More Robotics Projects

© 2026 MakeMindz — Arduino, IoT & Robotics Tutorials

Built with ❤️ for makers, students, and engineers.

Comments

try for free