How to Use the HC‑SR04 Ultrasonic Sensor with Arduino
Why the HC‑SR04 is a Go‑To Choice for Distance Sensing
The HC‑SR04 is a compact, inexpensive transducer that measures distance by emitting a short burst of ultrasound and listening for the echo. Because the sensor works on a simple principle—time‑of‑flight—it can be read with just a few lines of code on any Arduino board. Its 2 cm to 400 cm range and 3 mm resolution make it ideal for robotics, parking‑assist prototypes, and even simple art installations that react to proximity.
What You’ll Need
- HC‑SR04 module
- Arduino Uno, Nano, or any compatible board
- Jumper wires (male‑to‑male)
- Optional: 10 kΩ resistor for a voltage divider (if using a 5 V‑only board)
- Breadboard (helps keep connections tidy)
Hooking the Sensor Up
Connecting the HC‑SR04 is straightforward, but a few details can save you headaches later:
- VCC → 5 V on the Arduino
- GND → Ground
- Trig → Any digital pin (commonly D9)
- Echo → Any digital pin (commonly D10). If your board tolerates only 3.3 V on inputs, place a simple voltage divider (two 10 kΩ resistors) between Echo and the Arduino pin.
Because the sensor draws only a few milliamps, you can power several of them from the same 5 V rail without overloading the board.
Understanding the Ping‑Pong Cycle
When you set the Trig pin high for at least 10 µs, the module emits eight 40 kHz sound bursts. Those waves travel through the air, bounce off the nearest object, and return to the receiver. The Echo pin then goes high for a duration proportional to the round‑trip time. By measuring that pulse width, you can compute distance:
Distance (cm) = (Echo time µs) ÷ 58
The divisor 58 comes from the speed of sound (≈ 340 m/s) and the round‑trip factor.
First Sketch: Getting a Reading
Below is a minimal program that prints the measured distance to the Serial Monitor. It demonstrates the essential steps without any frills.
#include <Arduino.h>const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Trigger the pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo
long duration = pulseIn(echoPin, HIGH);
// Convert to centimeters
long distance = duration / 58;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(200);
}
Upload the sketch, open the Serial Monitor, and you should see a steady stream of numbers. Move your hand in front of the sensor—watch the values change in real time.
Fine‑Tuning for Accuracy
Raw readings are often within a few centimeters of the true distance, but you can tighten that range:
- Temperature compensation: Sound travels faster in warm air. Adding
float temperature = 20.0;and adjusting the divisor to58.2 - 0.2 * temperatureyields better results. - Median filtering: Take five successive readings, discard the highest and lowest, then average the rest. This smooths out occasional spikes caused by noisy reflections.
- Physical mounting: Keep the sensor away from metal surfaces that could reflect the burst back too quickly, and avoid direct sunlight which may heat the air unevenly.
Common Pitfalls and How to Avoid Them
Echo Pin Reads 0 µs
If pulseIn() returns 0, the module didn’t detect an echo. Check that the object is within the 2‑400 cm range and that nothing blocks the line of sight. Also verify that the Echo pin isn’t inadvertently pulled low by a stray connection.
Interference Between Multiple Sensors
When you place two HC‑SR04 units close together, their ultrasonic bursts can interfere. The simple solution is to stagger their trigger times by at least 60 ms, giving each sensor a clear window to listen for its own echo.
Power Issues on Small Boards
Boards such as the Arduino Nano 33 IoT operate at 3.3 V. Feeding the HC‑SR04 directly from the 5 V line can overload the regulator. Use an external 5 V source or a step‑up converter, and always share a common ground.
Putting It to Work: Mini Projects
Once you have reliable distance data, the sky is the limit. Here are three starter ideas that illustrate different ways to use the sensor.
- Obstacle‑Avoiding Robot: Pair the HC‑SR04 with two motor drivers. When the distance drops below 15 cm, reverse and turn.
- Parking Assistant: Mount the sensor on a hobby‑grade car chassis, map the distance to a series of LEDs that light up progressively as you approach a wall.
- Interactive Art: Feed the distance value into a NeoPixel strip, changing colors or patterns based on how close a viewer stands.
All three projects share the same core code; only the output actions differ. That modularity makes the HC‑SR04 a perfect learning platform for expanding into more sophisticated sensor arrays.
FAQ
What is the maximum reliable range of the HC‑SR04?
In ideal conditions the sensor can detect objects up to 400 cm away, but practical accuracy drops sharply beyond 300 cm, especially in noisy or humid environments.
Can I use the HC‑SR04 with a 3.3 V Arduino?
Yes, but you must protect the Echo pin with a voltage divider or level‑shifter because the sensor outputs a 5 V signal, which exceeds the safe input voltage of most 3.3 V boards.
Do I need a separate power supply for multiple sensors?
For a handful of sensors, the Arduino’s 5 V rail is sufficient. If you plan to run ten or more simultaneously, consider an external 5 V regulator to avoid voltage sag.
How often can I poll the sensor?
The HC‑SR04 requires at least a 60 ms pause between triggers. Polling faster than that can cause missed echoes and erratic readings.