
The HC-SR04 Ultrasonic Sensor is widely used for distance measurement in robotics, automation, and obstacle detection projects. It works by sending out ultrasonic waves and measuring the time it takes for the waves to bounce back after hitting an object.
The ESP32 makes an excellent choice for working with the HC-SR04 because it offers fast processing, multiple GPIO pins, and precise timing functions that help in measuring distance accurately.
In this tutorial, we will:
📏 Formula for distance:

| HC-SR04 Pin | ESP32 DOIT Kit Pin |
|---|---|
| VCC | 5V |
| GND | GND |
| TRIG | GPIO 15 |
| ECHO | GPIO 2 |

#define TRIG_PIN 15
#define ECHO_PIN 2
long duration;
float distance;
void setup() {
Serial.begin(115200); // Start serial communication
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Send a 10µs pulse to trigger
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of echo pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
distance = (duration * 0.0343) / 2;
// Print distance on Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000); // Wait for 1 second
}
Pin Definitions
#define TRIG_PIN 15
#define ECHO_PIN 2
Assigns ESP32 pins 15 and 2 for TRIG and ECHO.
Setup Function
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
TRIG is set as output (to send signal), ECHO as input (to receive).
Sending Trigger Pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
Sends a short 10µs pulse to start measurement.
Measuring Echo
duration = pulseIn(ECHO_PIN, HIGH);
Measures time (in microseconds) that ECHO pin stays HIGH.
Calculating Distance
distance = (duration * 0.0343) / 2;
Converts time into distance in centimeters.
Output Result
Serial.println("Distance: ...");
Displays measured distance in the Serial Monitor.
The HC-SR04 typically works with 5V, but it can be interfaced with ESP32 using a voltage divider on the Echo pin.
We connected Trigger → GPIO15 and Echo → GPIO2.
It can measure distances from 2 cm to 400 cm with an accuracy of about ±3 mm.
Unstable readings may occur due to electrical noise, reflective surfaces, or poor wiring. Use averaging in code to smooth values.
Yes, but performance may reduce in direct sunlight or windy conditions. For reliable outdoor use, a waterproof ultrasonic sensor (like JSN-SR04T) is recommended.






