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.
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
The four movements
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.
Gather the parts
| Component | Qty | Job in this project |
|---|---|---|
| Arduino UNO + USB cable | 1 | The robot’s brain |
| L298N motor driver | 1 | Drives both motors |
| HC-SR04 ultrasonic sensor | 1 | Measures the distance ahead |
| BO motors (DC gear motors) | 2 | Left and right drive |
| Wheels | 2 | Fit on the BO motors |
| Castor wheel | 1 | Balances the chassis |
| 18650 Li-ion cells (3.7 V) + holder | 2 | 7.4 V supply |
| Male-to-female jumper wires | – | Connect module pins to the UNO’s female headers |
| Mini breadboard or jumper splitter | 1 | Shares 5V between the Arduino and the sensor |
| Chassis, screws | – | The robot’s body |
Build the robot
- Fit the motors and wheelsFix both BO motors to the chassis and push the wheels onto the motor shafts.
- Fit the castorBolt the castor wheel at the other end of the chassis for balance.
- Mount the boardsFix the Arduino UNO, the L298N and the battery holder with screws or double-sided tape.
- Mount the sensorFix the HC-SR04 at the front, facing straight ahead, with nothing blocking its two “eyes”.
Wire it up
Keep the battery switched off while wiring. Pick a part to see only its wires.
Pin connection table
| From | To | Note |
|---|---|---|
| HC-SR04 TRIG | D4 | Sends the sound pulse |
| HC-SR04 ECHO | D7 | Times the echo |
| L298N ENA | D5 | Left speed (PWM), jumper removed |
| L298N ENB | D6 | Right speed (PWM), jumper removed |
| L298N IN1 / IN2 | D8 / D9 | Left motor direction |
| L298N IN3 / IN4 | D10 / D11 | Right motor direction |
| L298N OUT1 / OUT2 | Left motor | |
| L298N OUT3 / OUT4 | Right motor | |
| Battery + / − | L298N 12V / GND | 7.4 V input |
| L298N 5V | 5V rail | Powers the Arduino 5V and HC-SR04 VCC |
| L298N, Arduino, HC-SR04 GND | GND rail | Common ground |
The L298N jumpers
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
Upload the code
- Battery offSwitch the battery off while uploading. The USB cable powers the Arduino.
- Install the Arduino IDENo extra libraries are needed.
- Pick the board and portChoose Tools → Board → Arduino Uno and the correct Tools → Port.
- 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.
/*
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.
Test and tune
- Lift the wheelsProp the robot up so the wheels spin in the air, then switch the battery on.
- Check the directionBoth wheels should spin forward. If one spins backward, swap that motor’s two wires on its OUT terminals.
- Test the sensorBring your hand within 20 cm of the sensor. The wheels should stop, reverse and turn.
- 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.
| Setting | Value | What it changes |
|---|---|---|
FORWARD_SPEED / TURN_SPEED | 120 | Motor speed, 0–255 |
REVERSE_SPEED | 110 | Reversing speed |
OBSTACLE_DISTANCE | 20 cm | How close an obstacle can get |
REVERSE_TIME / TURN_TIME | 400 ms / 500 ms | How 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.