Advertisement
Beginner Time: 1–2 weeks Robotics

Obstacle Avoidance Robot

Build an autonomous robot that detects and navigates around obstacles using ultrasonic and IR sensors.

UltrasonicServoArduinoIR SensorAutonomous NavigationMotor Control
DifficultyBeginner
Duration1–2 weeks
Components10 items
Steps6 steps

Introduction

Build an autonomous robot that detects and navigates around obstacles using ultrasonic and IR sensors. This comprehensive guide covers everything from design through implementation, testing, and deployment.

Theory & Background

Send a 10µs trigger pulse to TRIG pin. HC-SR04 transmits 8 cycles of 40kHz ultrasonic burst and listens for echo. ECHO pin goes HIGH when echo is received. Distance = (pulseIn(ECHO_PIN, HIGH) × 343m/s) / 2 (divide by 2 for round-trip). Effective range: 2–400cm, ±3mm accuracy. Temperature affects speed of sound — apply correction: speed = 331.3 + 0.606 × T(°C). Mount sensor at 15–20cm height to avoid floor reflections.

Advertisement

Components & Requirements

10 components required for this project.

#ComponentPurposeQty
1Arduino UnoMain controllerx1
2HC-SR04 Ultrasonic SensorFront obstacle distance measurementx1
3Servo Motor (SG90)Rotating ultrasonic sensor for scanningx1
4Sharp IR Sensor (GP2Y0A21)Left and right side obstacle detectionx2
5L298N Motor DriverDual drive motor controlx1
6DC Gear Motors + WheelsDrive systemx2
79V Li-ion Battery PackPower supplyx1
8Robot Chassis (2-wheel differential)Physical platformx1
9LED Indicators (Red/Green)Status visualizationx2
10BuzzerObstacle detection alertx1

Step-by-Step Implementation

Follow these 6 steps carefully.

1
HC-SR04 Distance Measurement

Send a 10µs trigger pulse to TRIG pin. HC-SR04 transmits 8 cycles of 40kHz ultrasonic burst and listens for echo. ECHO pin goes HIGH when echo is received. Distance = (pulseIn(ECHO_PIN, HIGH) × 343m/s) / 2 (divide by 2 for round-trip). Effective range: 2–400cm, ±3mm accuracy. Temperature affects speed of sound — apply correction: speed = 331.3 + 0.606 × T(°C). Mount sensor at 15–20cm height to avoid floor reflections.

2
Servo Scanner Implementation

Mount HC-SR04 on servo at front center. Scan 15°–165° in 15° increments, taking distance readings at each angle. Build a distance map array: distances[12]. After each scan, find the maximum distance (clearest direction) and steer toward it. Scanning frequency: one full sweep every 300ms while moving. Stop motion during scan for more accurate readings, or continue moving at reduced speed.

3
Navigate and Avoid Algorithm

State machine: FORWARD (straight ahead), SCAN (obstacle detected, perform sweep), TURN (rotating to clear direction), REVERSE (if trapped). Trigger SCAN when front distance < 30cm. Find best direction from scan map. If best direction is left, turn left. If right, turn right. If all directions blocked (distance < 20cm), reverse 30cm then rescan. Use hysteresis: must see > 40cm clearance before resuming forward motion.

4
Side IR Sensors for Wall Following

Sharp IR sensors provide analog distance output (inversely proportional). Calibrate using lookup table: measure actual distance vs ADC reading at 5cm increments. Use side sensors for corridor navigation: maintain equal distance from both walls (wall-following behavior). If left wall < 15cm → steer right. If right wall < 15cm → steer left. This enables the robot to navigate hallways and maze corridors efficiently.

5
Speed Control and Smooth Turning

Implement variable speed: full speed on clear path, 50% speed when obstacle detected at 60cm, 25% when at 30cm. For smooth turning, don't stop one motor completely — set one motor to 60% forward and other to 60% reverse (spin-turn) for sharp obstacles, or 100%/40% (arc turn) for gradual course correction. Arc turns are smoother and faster for wide corridors.

6
Testing in Different Environments

Test in: narrow corridors (< 60cm width — robot must navigate precisely), open room with scattered objects, maze structure, and dynamic obstacles (moving person). Note failure cases: transparent obstacles (glass), very dark or very reflective surfaces (ultrasonic gives false readings), obstacles below sensor height (table legs, raised floors). Add IR sensors lower down to detect low obstacles not seen by ultrasonic.

Code & Implementation

Core code for obstacle_avoidance.ino:

obstacle_avoidance.ino C/C++
#include <Servo.h>
Servo scanServo;
#define TRIG 7 #define ECHO 8
#define IN1 4 #define IN2 5 #define ENA 9 #define IN3 6 #define IN4 11 #define ENB 10
#define SAFE_DIST 30 // cm

long getDistance() {
  digitalWrite(TRIG, LOW); delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  return pulseIn(ECHO, HIGH) * 0.0343 / 2;
}

int scanAndFindBest() {
  int bestAngle = 90; long maxDist = 0;
  for(int a = 15; a <= 165; a += 15) {
    scanServo.write(a); delay(200);
    long d = getDistance();
    if(d > maxDist) { maxDist = d; bestAngle = a; }
  }
  scanServo.write(90);
  return bestAngle; // <90=left, 90=straight, >90=right
}

void setMotors(int L, int R) {
  analogWrite(ENA, abs(L)); analogWrite(ENB, abs(R));
  digitalWrite(IN1, L>0); digitalWrite(IN2, L<=0);
  digitalWrite(IN3, R>0); digitalWrite(IN4, R<=0);
}

void loop() {
  long dist = getDistance();
  if(dist > SAFE_DIST) {
    setMotors(200, 200); // Forward
  } else {
    setMotors(0, 0); // Stop
    int best = scanAndFindBest();
    if(best < 90)      { setMotors(-150, 150); delay(400); } // Turn left
    else if(best > 90) { setMotors(150, -150); delay(400); } // Turn right
    else               { setMotors(-150, -150); delay(600); } // Reverse
  }
}

Testing & Troubleshooting

Test Obstacle Avoidance Robot by verifying each subsystem individually before full integration.

!
Troubleshooting Tips

Verify power voltages, check ground connections, use serial monitor for debug.

Real-World Applications

*Autonomous vacuum cleaners
*Warehouse navigation robots
*Search and rescue robot base
*Home delivery robot
*Museum tour guide
*Security patrol robot
*Elderly care assistance robot
*Educational robotics platform

Extensions & Next Steps

  • Add SLAM using RPLidar for full map building
  • Implement A* pathfinding algorithm
  • Add computer vision for semantic obstacle classification
  • Build multi-robot coordination to explore space without overlap
  • Add memory to learn and map recurring obstacle positions

Interactive Playground

Coming Soon

An interactive simulator will be available here — simulate circuits and run code in-browser without hardware.

Frequently Asked Questions

What is the minimum obstacle size the robot can detect reliably?
HC-SR04 reliably detects objects with frontal area larger than approximately A4 paper (21cm × 29.7cm) at 1m distance. Thinner objects like broom handles or thin poles are often missed because the ultrasonic beam (15–30° cone) only partially hits them. For detecting narrow obstacles, use a wider-angle sensor (LIDAR) or multiple ultrasonic sensors angled outward. The Sharp IR sensors are better for detecting small objects at close range (<80cm).
Why does the robot sometimes detect false obstacles?
False positives occur from: multiple reflections (signal bouncing between two surfaces before returning), soft surfaces absorbing ultrasound (fabric, foam — giving readings as if no obstacle when one exists), highly angled surfaces reflecting beam away (robot detects nothing approaching a wall at 45° angle), and electrical interference from motors (add 100nF bypass capacitors on motor power lines, run sensor cables away from motor wires).
How does the algorithm handle a dead-end (trapped situation)?
A dead-end with all directions blocked is handled by: (1) reversing a fixed distance (30–50cm) to create space, (2) performing a full 180° scan after reversing, (3) choosing the maximum distance direction (should now be the direction the robot came from), (4) executing the turn. If still trapped after 3 attempts, the robot should stop and signal for human assistance via buzzer or LED alarm.
Can I use LIDAR instead of ultrasonic for better performance?
Yes — single-point LIDAR (VL53L0X, $3–5) offers 1.2m range with 1mm accuracy and tiny form factor. Multi-point LIDAR (RPLidar A1, $100) scans 360° providing a full environment map, enabling SLAM (Simultaneous Localization and Mapping) and sophisticated path planning. However, for a beginner obstacle avoidance project, HC-SR04 is sufficient and much cheaper. Upgrade to LIDAR when implementing mapping and navigation algorithms.
Advertisement