Arque Technologies STEM Robotics Series

ObstacleAvoiding Robot

Build a robot that measures the distance ahead with ultrasonic sound and, when something comes within 20 cm, stops, reverses and turns to find a clear path.

You’ll use
  • Arduino UNO
  • HC-SR04 ultrasonic sensor
  • L298N motor driver
  • 2 × 18650 cells
Watch the code drive Tap the floor to add a box, tap a box to remove it
Distance –
Motors forward

How it works

The HC-SR04 works like a bat. It sends a short burst of sound too high for us to hear and times how long the echo takes to come back. The Arduino turns that time into a distance.

The HC-SR04 sends a sound pulse from one eye and hears the echo in the other TR HC-SR04 TRIGD4ECHOD7 1. 40 kHz sound burst goes out 2. the echo comes back Obstacle distance
The Arduino pulses TRIG for 10 µs. ECHO then stays HIGH for as long as the sound took to travel there and back.
Distance (cm) = echo time (µs) × 0.0343 ÷ 2
Example: 1166 µs × 0.0343 ÷ 2 = 20.0 cm. Sound travels 0.0343 cm per µs, and we halve it because the sound goes there and back.

What it does when something is close

Avoidance sequence: stop 200 ms, reverse 400 ms, stop 150 ms, turn 500 ms, stop 150 msForwarduntil ≤20 cmStop200 msReverse400 msStop150 msTurn500 msStop150 msagainTurn direction: right, then left, then right … but in a corner (a new obstacle within 2 s) it keeps turning the same way.The whole sequence takes 1.4 s. Then the loop checks the distance again.
If the path is clear, or no echo comes back, the robot keeps driving forward and checks again every 50 ms.

The four movements

The four movements: forward, backward, turn right and turn left forward()Both wheels forwardbackward()Both wheels backwardturnRight()Spins right on the spotturnLeft()Spins left on the spot
Turning runs one wheel forward and the other backward, so the robot spins on the spot.

What you’ll learn

  • Ultrasonic distance measurement using echo timing.
  • Direction and PWM speed control with an L298N H-bridge.
  • Differential steering with two wheels.
  • Writing a decision loop that reacts to its surroundings.
1

Gather the parts

ComponentQtyJob in this project
Arduino UNO + USB cable1The robot’s brain
L298N motor driver1Drives both motors
HC-SR04 ultrasonic sensor1Measures the distance ahead
BO motors (DC gear motors)2Left and right drive
Wheels2Fit on the BO motors
Castor wheel1Balances the chassis
18650 Li-ion cells (3.7 V) + holder27.4 V supply
Male-to-female jumper wires–Connect module pins to the UNO’s female headers
Mini breadboard or jumper splitter1Shares 5V between the Arduino and the sensor
Chassis, screws–The robot’s body
2

Build the robot

  1. Fit the motors and wheelsFix both BO motors to the chassis and push the wheels onto the motor shafts.
  2. Fit the castorBolt the castor wheel at the other end of the chassis for balance.
  3. Mount the boardsFix the Arduino UNO, the L298N and the battery holder with screws or double-sided tape.
  4. Mount the sensorFix the HC-SR04 at the front, facing straight ahead, with nothing blocking its two “eyes”.
Top view: HC-SR04 at the front, motors and wheels on the sides, L298N, Arduino, battery holder and caster Front L298N Arduino UNO 2 × 18650 HC-SR04front, facing straight ahead BO motor + wheelone on each side Arduino UNOscrews or double tape L298N driverbetween the motors Battery holderswitch easy to reach Castor wheelat the back
Mount the sensor level. If it tilts down, it can “see” the floor as an obstacle.
3

Wire it up

Keep the battery switched off while wiring. Pick a part to see only its wires.

Wiring map: HC-SR04 TRIG to D4 and ECHO to D7, L298N ENA to D5, ENB to D6, IN1 to IN4 to D8 to D11, motors on OUT1/OUT2 and OUT3/OUT4, battery to L298N 12V, L298N 5V to the 5V rail feeding the Arduino and the sensor, common ground Mini breadboard rails (or a splitter) +5V railcommon GND HC-SR04 TRIGECHO VCCGND ArduinoUNO D4D7 D5D6 D8D9D10D11 5VGND L298N ENAENB IN1IN2IN3IN4 12VGND5V Left Right OUT1/2OUT3/4 2 × 186507.4 V + 5V out
The L298N’s 5V output feeds the 5V rail, which powers the Arduino and the sensor. All grounds meet on one GND rail.

Pin connection table

FromToNote
HC-SR04 TRIGD4Sends the sound pulse
HC-SR04 ECHOD7Times the echo
L298N ENAD5Left speed (PWM), jumper removed
L298N ENBD6Right speed (PWM), jumper removed
L298N IN1 / IN2D8 / D9Left motor direction
L298N IN3 / IN4D10 / D11Right motor direction
L298N OUT1 / OUT2Left motor
L298N OUT3 / OUT4Right motor
Battery + / −L298N 12V / GND7.4 V input
L298N 5V5V railPowers the Arduino 5V and HC-SR04 VCC
L298N, Arduino, HC-SR04 GNDGND railCommon ground

The L298N jumpers

L298N jumpers: remove the ENA and ENB jumpers, keep the 5V regulator jumper fitted L298N chip IN1 IN2 IN3 IN4 ENAENB KEEP5V jumper REMOVEENA jumper, wire to D5 REMOVEENB jumper, wire to D6 Board layouts vary: read the labels printed next to each jumper.
The ENA and ENB jumpers must come off so the Arduino can control speed. The 5V jumper must stay on, or the L298N’s 5V pin won’t power the Arduino.

Power notes

  • One 5V pin: the Arduino 5V pin needs both the L298N 5V wire and the sensor, so join them on a breadboard rail or splitter.
  • Common ground: join the L298N, Arduino and HC-SR04 grounds.
  • Never reverse the battery polarity. It can damage the L298N and the Arduino.
  • Battery charge: the L298N’s 5V regulator needs about 7 V in. Low cells make the Arduino reset, so recharge them with a proper Li-ion charger and never short them.

Before you switch on

0 of 6 checked

4

Upload the code

  1. Battery offSwitch the battery off while uploading. The USB cable powers the Arduino.
  2. Install the Arduino IDENo extra libraries are needed.
  3. Pick the board and portChoose Tools → Board → Arduino Uno and the correct Tools → Port.
  4. Verify, then UploadPaste the code into a new sketch, click Verify and then Upload. Open the Serial Monitor at 9600 baud to see the distance readings.
obstacle_avoiding_robot.ino
/*
  ULTRASONIC OBSTACLE AVOIDING ROBOT
  Arduino Uno + HC-SR04 + L298N
  HC-SR04: TRIG -> D4, ECHO -> D7
  L298N:   ENA -> D5, ENB -> D6 (remove both jumpers)
           IN1 -> D8, IN2 -> D9, IN3 -> D10, IN4 -> D11
           Left motor -> OUT1/OUT2, Right motor -> OUT3/OUT4
*/
#define TRIG_PIN 4
#define ECHO_PIN 7
#define ENA 5
#define ENB 6
#define IN1 8
#define IN2 9
#define IN3 10
#define IN4 11

// ---------- SETTINGS ----------
const int FORWARD_SPEED = 120;          // 0-255
const int REVERSE_SPEED = 110;
const int TURN_SPEED = 120;
const float OBSTACLE_DISTANCE = 20.0;   // cm
const unsigned long REVERSE_TIME = 400; // ms
const unsigned long TURN_TIME = 500;    // ms
const unsigned long ECHO_TIMEOUT = 25000;
const unsigned long CORNER_TIME = 2000;  // ms

int turnDirection = 1;         // 1 = right, -1 = left
unsigned long lastTurn = 0;    // when the last turn finished

// ---------- MOTOR CONTROL ----------
void leftMotor(int speedValue) {
  speedValue = constrain(speedValue, -255, 255);
  if (speedValue > 0)      { digitalWrite(IN1, LOW);  digitalWrite(IN2, HIGH); }
  else if (speedValue < 0) { digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);  }
  else                     { digitalWrite(IN1, LOW);  digitalWrite(IN2, LOW);  }
  analogWrite(ENA, abs(speedValue));
}

void rightMotor(int speedValue) {
  speedValue = constrain(speedValue, -255, 255);
  if (speedValue > 0)      { digitalWrite(IN3, LOW);  digitalWrite(IN4, HIGH); }
  else if (speedValue < 0) { digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);  }
  else                     { digitalWrite(IN3, LOW);  digitalWrite(IN4, LOW);  }
  analogWrite(ENB, abs(speedValue));
}

void forward()   { leftMotor(FORWARD_SPEED);  rightMotor(FORWARD_SPEED);  }
void backward()  { leftMotor(-REVERSE_SPEED); rightMotor(-REVERSE_SPEED); }
void turnLeft()  { leftMotor(-TURN_SPEED);    rightMotor(TURN_SPEED);     }
void turnRight() { leftMotor(TURN_SPEED);     rightMotor(-TURN_SPEED);    }
void stopRobot() { leftMotor(0);              rightMotor(0);              }

// ---------- ULTRASONIC SENSOR ----------
float getDistanceCM() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(3);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT);
  if (duration == 0) return -1.0;       // no echo
  return duration * 0.0343 / 2.0;
}

// ---------- SETUP ----------
void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(ENA, OUTPUT); pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);
  stopRobot();
  Serial.println("Obstacle Avoidance Robot Ready");
  delay(1000);
}

// ---------- MAIN LOOP ----------
void loop() {
  float distance = getDistanceCM();
  Serial.print("Distance: ");
  if (distance < 0) Serial.println("No echo");
  else { Serial.print(distance); Serial.println(" cm"); }

  if (distance > 0 && distance <= OBSTACLE_DISTANCE) {
    Serial.println("Obstacle detected!");
    // New obstacle soon after the last turn? It's a corner:
    // keep turning the same way. Otherwise, alternate.
    if (lastTurn > 0 && millis() - lastTurn > CORNER_TIME) {
      turnDirection = -turnDirection;
    }
    stopRobot();  delay(200);           // stop
    backward();   delay(REVERSE_TIME);  // reverse for clearance
    stopRobot();  delay(150);

    if (turnDirection > 0) { Serial.println("Turning right"); turnRight(); }
    else                   { Serial.println("Turning left");  turnLeft();  }
    delay(TURN_TIME);
    stopRobot();  delay(150);
    lastTurn = millis();
  }
  else {
    forward();                          // clear path (or no echo)
  }
  delay(50);
}

Why the CORNER_TIME check?If the robot always alternates, a corner traps it: it turns right, meets the next wall, turns left and faces the corner again. Now, when a new obstacle appears within 2 seconds of the last turn, it keeps turning the same way and escapes.

5

Test and tune

  1. Lift the wheelsProp the robot up so the wheels spin in the air, then switch the battery on.
  2. Check the directionBoth wheels should spin forward. If one spins backward, swap that motor’s two wires on its OUT terminals.
  3. Test the sensorBring your hand within 20 cm of the sensor. The wheels should stop, reverse and turn.
  4. Let it roamPlace it on the floor among a few boxes and watch it find its way.

Key settings

Change these in the SETTINGS part of the code. The two sliders in the simulator change the code on this page too.

SettingValueWhat it changes
FORWARD_SPEED / TURN_SPEED120Motor speed, 0–255
REVERSE_SPEED110Reversing speed
OBSTACLE_DISTANCE20 cmHow close an obstacle can get
REVERSE_TIME / TURN_TIME400 ms / 500 msHow far it backs up and turns

Troubleshooting

The motors hum but don’t move

Raise the speed values to around 150–180, or charge the batteries. The L298N loses about 2 V, so the motors get less than 7.4 V.

The Serial Monitor shows “No echo”
  • Check TRIG is on D4, ECHO on D7, and the sensor’s 5V and GND.
  • Soft or angled surfaces (cushions, cloth, sharp angles) can scatter the sound.
One motor doesn’t run

Check the ENA / ENB wires on D5 / D6, that those jumpers are removed, and the motor’s screw terminals.

The Arduino doesn’t turn on with the battery

Check the L298N’s 5V jumper is still fitted and its 5V pin reaches the Arduino 5V through the rail.

It turns too little or too much

Increase or decrease TURN_TIME. Try the Turn time slider in the simulator first.

The Arduino resets when the motors start

The batteries are weak. Recharge them, and check every ground is joined.

It bumps into thin or low objects

The sensor sees a narrow cone straight ahead at its own height. Chair legs, low objects and things off to the side can be missed.