Explain Like I'm 12
HC-SR04 is like a bat that sends out a tiny sound you can't hear. It listens for the echo and tells your ESP32 how far away something is — like measuring how close your hand is to a wall.
Technical Specifications
Arduino library: Built-in Arduino timing (or NewPing library)
- Range: 2 cm to 400 cm
- Operating voltage: 5 V
- Trigger and Echo pins
- Accuracy: about 3 mm
Pinout
- VCC → 5 V
- GND → GND
- TRIG → GPIO5
- ECHO → GPIO18 (via level shifter if needed)
Wiring
Connect each pin as shown in the pinout section above.
Wiring Diagram
Wiring diagram for HC-SR04 Ultrasonic Distance Sensor
Code Example
Copy into Arduino IDE. Install the library listed above first.
example.ino
#define TRIG 5
#define ECHO 18
void setup() { Serial.begin(115200); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); }
void loop() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long duration = pulseIn(ECHO, HIGH);
float cm = duration * 0.034 / 2;
Serial.printf("Distance: %.1f cm\n", cm);
delay(500);
}
Expected Output
Serial Monitor prints distance in centimeters.
Related Guides
Related Projects
FAQ
The object may be too close (under 2 cm) or the sensor is angled wrong.
Downloads
Official manufacturer PDF for teachers and advanced builders.
Download Datasheet (PDF)