Overview
The HC-SR04 sends a burst of 40 kHz sound and raises its Echo pin for as long as the sound takes to return. Sound travels about 0.0343 cm per microsecond, and the time covers the trip there and back, so distance = time × 0.0343 ÷ 2.
You will need
- Arduino Uno R3
- HC-SR04 ultrasonic module (5 V version)
- 4 jumper wires
Wiring
| Uno pin | Connects to | Notes |
|---|---|---|
| 5V | VCC | |
| 7 | Trig | 10 µs HIGH pulse starts a measurement |
| 6 | Echo | HIGH for the round-trip time |
| GND | GND |
The sketch
const int TRIG_PIN = 7;
const int ECHO_PIN = 6;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
Serial.begin(9600);
}
void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Wait at most 30 ms (about 5 m round trip) for the echo
unsigned long echoUs = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (echoUs == 0) {
Serial.println("No echo (out of range)");
} else {
float distanceCm = echoUs * 0.0343 / 2.0;
Serial.print("Distance: ");
Serial.print(distanceCm, 1);
Serial.println(" cm");
}
delay(100);
}How the code works
The timeout in pulseIn() matters: without it the call waits up to one second
when nothing reflects. Keep at least 60 ms between pings so echoes from one ping do not arrive during
the next. Soft or angled surfaces may not reflect enough to measure.
Some newer modules (HC-SR04P, RCWL-1601) also run at 3.3 V; the classic module needs 5 V.
What you should observe
- A hand 20 cm away reads about 20 cm; accuracy is typically within a centimetre or so.
- Below about 2 cm or beyond about 4 m you will see erratic values or "No echo".