One of the most common questions a robot needs to answer is: "How far away is the nearest obstacle?" The HC-SR04 ultrasonic sensor is the cheapest and most popular way to answer that question in Arduino projects.
How does the HC-SR04 sensor work?
This sensor sends out an ultrasonic wave (inaudible to humans), measures how long it takes for the wave to bounce back off an obstacle, and calculates distance from the speed of sound — the exact same principle radar and sonar use.
Step 1: Connecting the sensor
The HC-SR04 has four pins: VCC (to the Arduino's 5V), GND (to ground), Trig (the pin that sends the wave, to a digital pin like pin 9), and Echo (the pin that receives the reflection, to another digital pin like pin 10).
Step 2: Sending the Trig signal
To start a measurement, you set the Trig pin HIGH for 10 microseconds — this triggers the sensor to send out an ultrasonic pulse.
Step 3: Reading the Echo pin
After sending the pulse, use pulseIn() to read how long the Echo pin stays HIGH (the wave's round-trip time) — this number is in microseconds.
Step 4: Converting time to distance
Using basic physics (distance = speed × time, accounting for the wave traveling a round trip), you convert the measured time to centimeters — distance (cm) is roughly equal to time (microseconds) divided by 58.
Step 5: Displaying the result
Use Serial.println() to view the calculated distance in the Arduino IDE's Serial Monitor — a great way to test and debug the sensor before using it in a complete project.
Step 6: Practical use
Now that you have the distance, you can add decision logic — for example, "if distance is less than 10 cm, stop the motors" — exactly the core mechanism behind obstacle avoidance in autonomous robots.
Summary
Combining a distance sensor with a motor (like the servo from the previous tutorial) is exactly the pair of components you need to build your first real autonomous robot.
Blog
The HC-SR04 Ultrasonic Sensor: Measuring Distance with Arduino
Related Articles
Prefer hands-on, in-person learning?
You can learn this same material in person, with real hands-on labs, at Amniat Technical & Vocational Institute in Shiraz.
Visit Amniat Academy in Shiraz