Working Principle
The HC-SR04 measures distance using time-of-flight: it emits an ultrasonic burst at 40 kHz, waits for the echo reflected by an object, and outputs a pulse whose width encodes the round-trip time. Distance is calculated as:
distance_cm = (pulse_us / 2.0) / 29.1
Analogy: It works exactly like shouting into a canyon and timing the echo — just at a frequency far above human hearing.
Electrical Characteristics
| Parameter | Value |
|---|---|
| Supply Voltage | 5 V |
| Current | 15 mA |
| Range | 2 cm – 400 cm |
| Accuracy | ± 3 mm |
| Beam Angle | ~15° |
| Trigger Pulse | 10 µs HIGH |
Interfacing
Two GPIO pins are needed: TRIG (output, sends 10 µs pulse) and ECHO (input, measures return pulse width). If connecting to a 3.3 V MCU, use a voltage divider on the ECHO pin.
Calibration
The speed of sound varies with temperature. For precise measurements, apply temperature compensation:
speed_of_sound = 331.3 + (0.606 * temperature_c) m/s
Code Example
/*
* HC-SR04 Ultrasonic Distance Sensor — Arduino
* Wiring: TRIG → Pin 9, ECHO → Pin 10, VCC → 5V, GND → GND
*/
#define TRIG_PIN 9
#define ECHO_PIN 10
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
float measureDistance() {
/* Send 10µs trigger pulse */
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
/* Measure echo pulse duration */
long duration = pulseIn(ECHO_PIN, HIGH, 30000); /* 30ms timeout */
if (duration == 0) return -1.0; /* No echo = out of range */
/* Convert to cm (speed of sound ≈ 343 m/s at 20°C) */
return (duration / 2.0) / 29.1;
}
void loop() {
float dist = measureDistance();
if (dist < 0) {
Serial.println("Out of range");
} else {
Serial.print("Distance: ");
Serial.print(dist, 1);
Serial.println(" cm");
}
delay(100); /* Min 60ms between measurements */
}
Real-World Applications
Parking Assist Systems
Cars mount 4–8 ultrasonic sensors in bumpers to detect obstacles during parking. Multiple sensors with overlapping beams triangulate object positions, producing the familiar beeping cadence that accelerates as distance shrinks.
Limitations
- Soft surfaces: Fabric and foam absorb sound, producing weak or no echoes.
- Narrow angles: Objects outside the 15° cone are invisible.
- Crosstalk: Multiple HC-SR04 modules can interfere; stagger trigger timing.
- Minimum range: 2 cm dead zone means you cannot measure very close objects.