The HC-SR04 is an ultrasonic distance sensor that measures range by sending a sound pulse and timing the echo return. It typically uses a 5V supply and a simple digital trigger/echo interface, making it easy to read from Arduino- and ESP32-based projects.
| Pin | Signal | Description |
|---|---|---|
Vcc |
power | bottom-edge power pin hole, leftmost of the 4-pin header |
Trig |
digital | bottom-edge trigger pin hole, second from left |
Echo |
digital | bottom-edge echo pin hole, third from left |
Gnd |
ground | bottom-edge ground pin hole, rightmost of the 4-pin header |
| From | To | Wire |
|---|---|---|
board:5V |
x1:Vcc |
red |
board:GND |
x1:Gnd |
black |
board:D9 |
x1:Trig |
green |
board:D10 |
x1:Echo |
blue |
This example was written and compile-checked for the arduino-uno. Codey Online adapts it to any other supported board for you.
// HC-SR04 ultrasonic distance sensor example
// Wiring:
// HC-SR04 Vcc -> 5V
// HC-SR04 Gnd -> GND
// HC-SR04 Trig -> D9
// HC-SR04 Echo -> D10
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, LOW);
Serial.println("HC-SR04 ready");
}
void loop() {
// Send a 10 microsecond pulse to start a measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse length (timeout after 30 ms)
unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);
if (duration == 0) {
Serial.println("Out of range or no echo");
} else {
// Convert time to distance in centimeters
// Speed of sound approx. 343 m/s => 29.1 us per cm round trip
float distanceCm = duration / 58.0;
Serial.print("Distance: ");
Serial.print(distanceCm, 1);
Serial.println(" cm");
}
delay(500);
}
Describe what you want to build. Codey Online writes the code, draws the wiring diagram, compiles it and flashes your board straight from the browser.
Start for free