11:07:25 AM NPT Arduino, Robotics & IoT tutorials for Nepal
Beginner

Obstacle Avoiding Robot Car with Arduino and HC-SR04

Build an obstacle avoiding robot car with Arduino, HC-SR04, servo scanning and L298N. Parts, wiring, commented code, testing and fixes.

On this page
Obstacle Avoiding Robot Car with Arduino and HC-SR04

An obstacle avoiding car drives forward until it sees something in the way, then looks left and right and chooses the freer direction. It is a favourite for first robotics projects, science exhibitions and BE minor projects because the idea is easy to explain and the result is fun to watch.

You will use an HC-SR04 ultrasonic sensor on a small servo so the "eye" can turn, an L298N driver and two gear motors. If you built the distance meter in our HC-SR04 tutorial, the sensor part will already feel familiar.

What you need

Scroll sideways to see all columns.

Item Qty Notes
Arduino Uno 1
HC-SR04 ultrasonic sensor 1 5 V module with Trig and Echo
SG90 micro servo 1 Rotates the sensor left and right
L298N motor driver module 1
BO gear motors with wheels 2
Caster wheel and chassis 1 set Two-wheel-drive kit
Battery pack for motors 1 A protected battery pack or AA pack sized for the motors and driver
USB power bank 1 Powers the Arduino through USB
Regulated 5 V supply for the servo 1 Sized for its peak current
Electrolytic capacitor 470 uF, 10 V or higher 1 Across the servo supply to reduce noise
Jumper wires, switch, small bracket for the sensor 1 set

Connection table

Power rule: the motors run from their own battery through the L298N. The Arduino and servo run from the power bank. All grounds are joined.

Scroll sideways to see all columns.

Pin or terminal Connects to
HC-SR04 VCC / GND Arduino 5 V / GND
HC-SR04 Trig Arduino D2
HC-SR04 Echo Arduino D3
Servo signal (orange or yellow) Arduino D11
Servo VCC (red) / GND (brown) External 5 V / GND, with 470 µF across them and GND shared with the Arduino
L298N ENA / ENB Arduino D5 / D6 (PWM), jumper caps removed
L298N IN1, IN2 Arduino D7, D8
L298N IN3, IN4 Arduino D9, D10
L298N OUT1, OUT2 Left motor
L298N OUT3, OUT4 Right motor
L298N 12V terminal Motor battery +
L298N GND Motor battery -, and Arduino GND
L298N 5V terminal Arduino 5 V for driver logic, with the 5V-EN jumper removed

The Arduino Servo library uses a timer that disables PWM on pins 9 and 10 on an Uno. That is why the speed pins are D5 and D6 and the servo is on D11, so nothing conflicts.

How it works

The HC-SR04 sends a short burst of 40 kHz ultrasound and measures the time until the echo returns. Distance in cm is the echo time in microseconds divided by about 58 (sound travels about 343 m/s in air, and the pulse goes out and back).

The robot logic is a small state machine:

  1. Look ahead with the servo at 90 degrees and read the distance.
  2. If the reading is over 25 cm, drive forward. This demo also treats a missed echo as out of range, so it can miss soft, angled or very close objects. Test at low speed on a clear floor.
  3. If something is 25 cm away or closer, stop, back up briefly, scan at 30 degrees (right) and 150 degrees (left), read both distances.
  4. Turn toward the side with the greater distance, then go back to step 1.

Reading the sensor several times and taking the median removes most random bad readings, which is important because soft or angled objects (a cloth, a sofa corner) reflect sound badly.

Step-by-step build

  1. Assemble the chassis, motors and caster wheel.
  2. Glue or screw the servo at the front. Mount the HC-SR04 on the servo horn so that it faces forward at 90 degrees.
  3. Fix the L298N, Arduino and batteries. Keep the battery low and centred.
  4. Wire according to the table. Add the 470 uF capacitor across the servo supply, with the longer leg to the positive side.
  5. Upload the code with the wheels lifted off the ground. Check the direction of each motor, then place the car on the floor.

Complete code

sketch-1.inoDownload code
// Obstacle avoiding car - not compiled yet
#include <Servo.h>

const int TRIG = 2, ECHO = 3, SERVO_PIN = 11;
const int ENA = 5, IN1 = 7, IN2 = 8;
const int IN3 = 9, IN4 = 10, ENB = 6;

const int SAFE_CM  = 25;   // stop if closer than this
const int SPEED    = 140;  // 0-255
const int TURN_MS  = 450;  // tune: time to turn about 90 degrees

Servo eye;

long readCm() {
  digitalWrite(TRIG, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG, LOW);
  unsigned long us = pulseIn(ECHO, HIGH, 25000UL);
  delay(60);                            // let echoes clear before the next ping
  if (us == 0 || us > 23200UL) return 401; // no usable echo; treat as beyond range
  return us / 58;
}

// median of 3 readings to remove spikes
long distance() {
  long a = readCm(), b = readCm(), c = readCm();
  if ((a >= b && a <= c) || (a <= b && a >= c)) return a;
  if ((b >= a && b <= c) || (b <= a && b >= c)) return b;
  return c;
}

void drive(int left, int right) {
  digitalWrite(IN1, left  > 0); digitalWrite(IN2, left  < 0);
  digitalWrite(IN3, right > 0); digitalWrite(IN4, right < 0);
  analogWrite(ENA, abs(left));
  analogWrite(ENB, abs(right));
}

void setup() {
  pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);
  pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  eye.attach(SERVO_PIN);
  eye.write(90);
  delay(500);
}

void loop() {
  eye.write(90);
  long front = distance();

  if (front > SAFE_CM) {
    drive(SPEED, SPEED);                 // clear: forward
  } else {
    drive(0, 0);                         // stop
    delay(200);
    drive(-SPEED, -SPEED);               // back up a little
    delay(300);
    drive(0, 0);

    eye.write(30);  delay(500);          // look right
    long right = distance();
    eye.write(150); delay(500);          // look left
    long left = distance();
    eye.write(90);  delay(300);

    if (right > left) {
      drive(SPEED, -SPEED);              // turn right in place
    } else {
      drive(-SPEED, SPEED);              // turn left in place
    }
    delay(TURN_MS);
    drive(0, 0);
  }
}

If the servo turns the wrong way for your mounting, swap the 30 and 150 values.

Testing

  • Sensor only. Print distance() to the Serial Monitor and move a book in front. The reading should track within a couple of centimetres.
  • Servo sweep. Run the servo to 30, 90 and 150 and confirm the sensor points where you expect.
  • Motors. With the car lifted, check forward, backward and both turns.
  • Floor test. Place a box about 1 m ahead. The car should stop, look around, turn and continue.
  • Tune TURN_MS. Change it until the car turns about 90 degrees on your floor.

Troubleshooting

Scroll sideways to see all columns.

Symptom Likely cause Fix
Car hits soft objects Sound absorbed by cloth or foam Raise SAFE_CM; add a second sensor
Distance jumps randomly Noise or poor echo Use the median function; keep the sensor level
Arduino resets when motors start Shared power Separate motor battery and power bank, common GND
Servo jitters or buzzes Weak supply or no capacitor Add the 470 µF capacitor and check the servo supply under load
Always turns the same way Left and right readings swapped Swap servo angles 30 and 150
Car does not move but motors hum PWM too low Raise SPEED to 160 or more
Distance always 401 Trig and Echo wires swapped or no 5 V Check wiring and power

Make it better

  • Add a second sensor at the back so the car does not reverse into walls.
  • Replace the stop-scan-turn pause with a slow arc away from the obstacle.
  • Add an LED or buzzer that signals when an obstacle is detected.
  • Log distance readings to the Serial Plotter for your report.

FAQ

Can I use two sensors instead of a servo?

Yes. A left sensor and a right sensor angled outward let you compare distances without a servo, and the code gets simpler.

What is the range of the HC-SR04?

The commonly stated working range is about 2 cm to 400 cm, with the best accuracy at shorter distances and on flat surfaces.

Why does my car turn too far or too little?

The turn time depends on battery charge, floor friction and motor speed, so tune TURN_MS after the battery is fully charged.

Can I power everything from one battery?

It is possible with a regulator, but motor noise often resets the Arduino. A separate power bank for the Arduino is the easiest reliable fix.

Related tutorials

See all Robotics →