Ultrasonic Distance Measurement (RADAR/Sonar Principle)
Measure physical distance by emitting 40kHz ultrasonic sound bursts and timing the returning echo reflection.
Car parking reverse sensors, autonomous drone altitude holding, industrial fluid tank level gauging, and robotics collision avoidance.
The transmitter emits an ultrasonic wave packet. When it reflects off an obstacle, the receiver captures the echo. Using the speed of sound in air (v ≈ 343 m/s or 0.0343 cm/µs), distance = (Time × Speed) / 2.
Pin Connection & Wiring Table
| Component Pin / Terminal | Microcontroller Pin (ESP32 / Arduino) | Wiring Note |
|---|---|---|
| VCC | 5V / VIN | HC-SR04 requires 5V supply |
| TRIG | GPIO 5 / Pin 11 | Trigger pulse output from MCU |
| ECHO | GPIO 18 / Pin 12 | Echo pulse input (via voltage divider if using 3.3V ESP32) |
| GND | GND | Common ground |
Step-by-Step Plug & Play Assembly
Mount the HC-SR04 upright on the plug-and-play base with transducers facing forward.
Connect VCC to 5V and GND to GND.
Connect TRIG to GPIO 5.
Connect ECHO to GPIO 18 (with a 1k/2k resistor divider for 3.3V protection).
Complete Tested Source Code
// NovaCircuit Project 4: Ultrasonic Distance Gauge
const int TRIG_PIN = 5;
const int ECHO_PIN = 18;
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.println("HC-SR04 Ultrasonic Ranging Ready");
}
void loop() {
// Clear trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Send a 10 microsecond HIGH pulse
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read duration of ECHO return pulse in microseconds
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // 30ms timeout
// Distance calculation: Distance = (Duration * Speed of Sound 0.0343 cm/us) / 2
float distanceCm = (duration * 0.0343) / 2;
if (duration == 0 || distanceCm > 400) {
Serial.println("Out of Range / No Obstacle Detected");
} else {
Serial.print("Target Distance: ");
Serial.print(distanceCm, 1);
Serial.println(" cm");
}
delay(300);
}pulseIn(ECHO_PIN, HIGH) measures how long the ECHO pin stays HIGH. The echo pulse duration is directly proportional to the round-trip distance traveled by sound waves.
Expected Physical Output
- •Zero distance reported: Check if TRIG and ECHO pins are wired backwards.
- •Inaccurate measurements: Sound reflections bounce off soft fabrics; use a hard flat surface (like a book or wall) for testing.
- •Sensor sound is 40kHz (inaudible to human ears); safe and harmless.
Related Book Chapter & Hardware Kit
Covered in depth within Chapter 6: Sensors and Their Applications. Build this easily with the Sensor Explorer Kit.