Have you ever watched a small robot roll across a room, stop in front of a wall and turn away? It is one of the most popular beginner projects in robotics, and it is called an obstacle-avoiding robot. The idea is simple. A sensor measures the distance in front of the robot, a controller board reads the measurement, and the motors move or stop depending on the result. In this guide we will see how the HC-SR04 distance sensor works, how to wire it to an Arduino Uno, and how to write code that measures distance and then build the robot's logic on top of it.
If you are completely new, start with What Is a Robot? A Beginner's Guide, and take a look at Arduino Projects for Beginners to try simpler projects, such as LEDs and buttons, before you reach this one.
How does the HC-SR04 measure distance?
The sensor works on the same idea as a bat's sonar. It has two parts that look like eyes. One sends out a short burst of sound at a frequency higher than the human ear can hear (ultrasound). The other listens for the echo when the burst bounces off an object in front of it. The sensor measures the time between sending and receiving, and from that time we calculate the distance.
The formula is easy. Sound travels through air at room temperature at about 343 meters per second, which is about 0.0343 centimeters per microsecond. The pulse travels there and back, so we divide the time by two:
distance in cm ≈ time in microseconds × 0.0343 ÷ 2
The datasheets published for the sensor give a shortcut: the distance in centimeters is roughly the echo pulse width in microseconds divided by 58. Both methods give almost the same answer.
Specifications that matter to you
According to the commonly circulated datasheet (such as the SparkFun copy linked in the sources below):
- It measures from 2 cm to 400 cm without touching the object.
- Accuracy can reach 3 mm under ideal conditions.
- It runs on 5 volts.
- The measuring angle is small, about 15 degrees. In other words, it "looks" through a narrow cone in front of it.
- A measurement starts when you give the Trig pin a short 10-microsecond pulse. The sensor then sends a pulse on the Echo pin whose width is proportional to the distance.
Adafruit's product page adds that the sensor gives its best results at roughly 10 to 250 cm. So do not expect very precise readings at 3 cm or at 4 meters.
What affects the reading?
The sensor depends on sound bouncing back, and that has practical consequences:
- Hard, flat surfaces such as walls and doors reflect sound well.
- Soft surfaces such as fabric and foam absorb some of the sound and can give unstable readings.
- An object at a steep angle can bounce the echo away from the sensor, so the object seems to be "not there".
- Very thin objects, such as a thin chair leg, may not be seen if they fall outside the narrow cone.
These are not flaws in your project. They are the nature of the technology. The usual fix in a robot is to take several readings and use the average, rather than trusting a single one.
Parts you need
- An Arduino Uno board (or a similar board).
- An HC-SR04 sensor.
- A small robot chassis with two wheels, two motors and a free-rolling caster (sold as a ready-made kit at a low price).
- A motor driver such as the L298N or similar.
- A power source for the motors (batteries), separate from the USB port.
- Jumper wires and a breadboard.
- Optional: a small servo motor to rotate the sensor, which we mention in the upgrades.
An important note: an Arduino board cannot drive motors directly. Its input and output pins can supply only a small current, and a motor draws much more. So we use a motor driver that receives control signals from the Arduino and takes its power from the batteries.
Wiring step by step
Start with the sensor alone. Do not connect the motors until you are sure the reading works:
- Connect the sensor's VCC pin to the 5V pin on the board.
- Connect the GND pin to GND.
- Connect the Trig pin to digital pin 9.
- Connect the Echo pin to digital pin 10.
Write down where each wire goes. Most beginner problems come from a wire in the wrong place, not from a bug in the code.
First code: just read the distance
Open the Arduino IDE and paste this simple code, which we wrote for this explanation:
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
long readDistanceCm() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // 10-microsecond pulse
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000); // 30 ms timeout
if (duration == 0) return -1; // no echo
return duration * 0.0343 / 2;
}
void loop() {
long d = readDistanceCm();
Serial.println(d);
delay(100);
}
What the important lines do: the function sends a 10-microsecond pulse on Trig, then uses the pulseIn command to measure the width of the Echo pulse. We set a 30-millisecond timeout so the program does not wait forever if no echo comes back. If the value is zero, we treat it as "no object in range".
After uploading, open the Serial Monitor and move your hand toward the sensor and away from it. The numbers should change with the distance. Compare the reading with a ruler to see how accurate your sensor is.
The robot's logic: when to stop and when to turn
Once the reading works, add the motors through the motor driver. The general idea of the program is:
- If the distance is greater than a safety limit (for example 25 cm): go forward.
- If the distance is less than or equal to the limit: stop, back up a little, turn in one direction for a short time, then measure again.
Pick the safety limit by testing. A fast robot needs more braking distance than a slow one. Start at low speed so you can see how it behaves.
A tip to avoid jitter: do not let the robot decide from a single reading. Take three readings in a row, and if at least two of them are below the limit, treat it as an obstacle. This reduces wrong decisions caused by one odd reading.
Common mistakes and fixes
The reading is always zero or -1: Check the Trig and Echo wiring, and make sure the sensor is on 5 volts, not 3.3 volts.
The readings jump around: Wait 50 to 100 milliseconds between measurements, avoid pointing the sensor at a soft or slanted surface, and average several readings.
The robot restarts when the motors start: The cause is usually a voltage drop when the motors draw current. Use a separate supply for the motors, and connect the grounds (GND) of the motor supply and the board.
The robot hits thin objects: The sensor has a narrow cone. Try mounting the sensor firmly in the middle, or move on later to a better approach such as rotating the sensor with a servo.
Taking the project further
After the basic project works, try these ideas in order:
- Rotate the sensor: Mount the sensor on a servo, measure the distance left, right and ahead, and choose the direction with the most free space.
- Add sound and light: Turn on a buzzer or LED when something gets close, so it is easier to see what the robot "sees".
- Show the distance: Add a small display to show the live reading.
- Change the board: As your projects grow you will want to compare boards. Read Arduino vs ESP32 vs Raspberry Pi to know when a move is worth it.
Safety tips
- Disconnect the batteries before changing any wire.
- Do not leave the robot running unattended on a high table, because it may fall.
- Keep small children away from small parts and batteries.
- Do not put your fingers near the wheels while it runs.
Where to go after this project
This project teaches three skills used in every robot: reading a sensor, making a decision from the reading, and moving a motor based on the decision. If you want to put your steps in order, the 90-day robotics learning plan places this kind of project at the right time inside a clear path.
Sources
- Ultrasonic Ranging Module HC-SR04, widely circulated datasheet: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
- Adafruit, HC-SR04 product page and datasheet: https://media.digikey.com/pdf/Data%20Sheets/Adafruit%20PDFs/3942_Web.pdf
- HC-SR04 user's manual (version 1.0): https://grobotronics.com/images/companies/1/HC-SR04Users_Manual.pdf
The explanation and the code in this article were written originally for this site, and the technical numbers come from the sources above. Your real-world results may differ a little depending on the sensor, the temperature and the surface.