The HC-SR04 ultrasonic sensor measures distance using sound. It is a favourite for obstacle-avoiding robots, water level monitors and parking sensors, and it takes only a few minutes to connect to an Arduino.
What you need
How the HC-SR04 works
The Arduino sends a short pulse to the Trig pin, and the sensor emits a burst of ultrasound. The Echo pin then stays high for as long as the sound takes to reach an object and return. Because that time covers the trip both ways, the code divides it by two.
The sensor typically measures from about 2 cm to 400 cm.
HC-SR04 Arduino wiring
| HC-SR04 pin |
Arduino Uno pin |
| VCC |
5V |
| Trig |
D9 |
| Echo |
D10 |
| GND |
GND |
Arduino code
Upload this sketch, then open the Serial Monitor at 9600 baud.
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Send a 10 microsecond trigger pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Wait up to 30 ms for the echo
long duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) {
Serial.println("Out of range");
} else {
float distanceCm = duration * 0.0343 / 2;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
}
delay(200);
}
The distance formula
Distance in cm = echo time in microseconds × 0.0343 ÷ 2. The value 0.0343 is the speed of sound in cm per microsecond at about 20°C. Sound travels faster in hot air, reaching about 0.0355 at 40°C, so a project that needs better accuracy in summer should adjust this number.
Troubleshooting
-
Always out of range: check that Trig and Echo are not swapped, and that VCC has 5 V.
-
Unstable readings: soft surfaces such as cloth absorb sound, and angled surfaces reflect it away. Aim at a flat, hard surface.
-
Wrong values near the sensor: objects closer than about 2 cm cannot be measured reliably.
Using the HC-SR04 with ESP32
The HC-SR04 runs on 5 V, so its Echo output is also 5 V. An ESP32 uses 3.3 V logic, so reduce the Echo signal with a voltage divider, such as 1 kΩ in series and 2 kΩ to ground, or use a level shifter.
Other distance sensors
Frequently asked questions
Do I need a library for the HC-SR04?
No. The code above uses only built-in Arduino functions. Libraries such as NewPing are optional.
Can the HC-SR04 measure water level?
Yes, if you mount it above the water and keep it dry. For a tank with moisture or condensation, use a waterproof sensor instead.
Where can I buy an HC-SR04 in Pakistan?
Order the HC-SR04 from Mcustore with delivery across Pakistan and cash on delivery.