Skip to Content

Using ESP32 with HC-SR04 Ultrasonic Distance Sensor

Using ESP32 with HC-SR04 Ultrasonic Distance Sensor

In this article, I will teach you how to connect and use a distance sensor HC-SR04 sensor to ESP32.

Why do you need one?

Have you seen how an advertisement board will light up soon after you approach it or a simple, intelligent garbage bin that opens its lid as you go close to it? 

Or even the robots in the mall which avoid crashes intelligently almost all of them use an ultrasonic sensor.

An ultrasonic sensor uses sound to detect objects and obstructions, and they are simple to use in many DIY and hobby projects.

By the end of this article, you will understand how the sensors work and be equipped with the skills and knowledge to experiment with them in your projects.

Whether you’re a beginner or an experienced maker, this article will provide a solid foundation to explore more applications of ultrasonic sensors, including the HC-SR04.

Let’s get started!

Components Needed To Build ESP32 And HC-SR04 Sensor Project

Hardware Components


Guide is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to products on

Basics of The HC-SR04 Sensors

The working principle of ultrasonic sensors is similar to the echolocation used in bats.

  1. The sensors emit sound waves. They are always beyond 20 kHz (so you won’t hear them). 
  2. The sensor then waits for the sound to come back due to reflection after hitting objects.
  3. The time it takes for the sound signal to travel to the object and back is measured. Since you know the speed of sound, you can calculate the distance traveled by the sound emitted by the sensor.

Do you know the speed of sound in the air?

Speed of sound in dry air at 20 °C = 343 m / s

This is a piece of crucial information for your code. 

Let’s look at the sensor module HC-SR04. I have labeled its key components in this diagram:

Pinout of HC-SR04
Pinout of HC-SR04

The sensor has four pins. The description of the four pins of the HC-SR04 sensor is given in the table below:

VCCPower supply pin. Typically 5 V
TRIGTrigger pin – Used to activate the measurements. You send a pulse onto this pin of at least 10 µs width
ECHOThe pulse width on this pin is proportional to the range
GNDGround connection 

Here’s a summary of how the ESP32 and HC-SR04 sensor work together (and reflected visually in the image below):

  1. You send a trigger signal from ESP32 to the HC-SR04 Sensor
  2. The HC-SR04 sensor module sends a burst of 8 pulses of 40 kHz
  3. The Echo pulse will provide a range of measurements
ESP32 and HC-SR04 sensor

Typical specifications of an HC-SR04 Sensor:

ParameterValue / Range
Frequency of pulses40 kHz
Range of measurement2 cm to 400 cm
Ranging accuracyUp to 3 mm
Working voltageDC 5 V
Working current 15 mA
Measuring angle15 degrees
Trigger input signal10 µs pulse

Applications of HC-SR04 Sensors

The ultrasonic sensors find their use in several areas; here are a few. You can find far more applications than I have listed here. What is your use case?

  1. Parking assistance systems: HC-SR04 sensors are used in parking assistance systems. It helps to measure the distance between the car and the wall/obstacle. It provides feedback to the driver through visual or audio feedback.
  1. Robotics: HC-SR04 sensors can be used in robotics to detect obstacles, avoid collisions, or measure distances and help robots navigate their environment. This is a must-sensor for autonomous robots. 
  1. Home automation: HC-SR04 sensors can be used in home automation systems to detect the presence of people or objects and trigger actions such as turning on lights or opening doors. 

It helps to save power when there are no people. It also gives an intelligent feel to the users. Turn on the light only when needed. You can also use the sensor to detect the water level in overhead tanks and run or stop motors accordingly.

  1. Security systems: HC-SR04 sensors can be used in security systems to detect movement or measure distances and trigger alarms or cameras. 

For example, if people are too close to the museum display, you can raise a small warning to deter people upfront. 

  1. Industrial automation: HC-SR04 sensors can be used in industrial automation applications to measure distances, monitor objects, or detect obstacles. 

It also helps people work efficiently, especially when driving or carrying heavy items. 

Factors affecting HC-SR04 accuracy

The following factors can all affect the measurement range:

  • Temperature
  • Humidity
  • The nature of the object
  • The assumption of the speed of sound

The sensor can be calibrated for a given system to ensure the measurement errors are within the expected limits. 

In the next section, let’s connect an HC-SR04 sensor to ESP32.

Instructions To Connect The HC-SR04 Module with ESP32

I will show you how to build a project using ESP32 and the sensor HC-SR04.

Let’s get started with the hardware connections.

Step 1: Basic hardware connection diagram

Connecting HC-SR04 to ESP32
Connecting HC-SR04 to ESP32

Start with the ground connections. If you have to use other pins, edit the code accordingly. Power the entire system only after completing all the connections.

HC-SR04 PinsESP32 Pins

Here is the connection summary between the ESP32 sensor and the HC-SR04 sensor. 

  • Connect the VCC pin of the ultrasonic sensor to the 5 V pin of the ESP32.
  • Connect the ESP32 GPIO5 to the TRIG pin of the UNO.
  • Connect the ESP32 GPIO18 pin to the ECHO pin of the sensor.
  • Connect the GND pin of the ESP32 to the sensor GND pin.

Step 2: Program the ESP32 with the code below

Follow the next step to understand the code implementation. You can use the code below to test the ESP32 module and the connected HC-SR04 sensor.

Please follow our guide to install the ESP32 core on the Arduino IDE.

#define echoPin 18 // attach pin ESP32 GPIO18 to pin Echo of HC-SR04
#define trigPin 5  // attach pin ESP32 GPIO5 to pin Trig of HC-SR04                     

long duration; // Variable to store time taken to the pulse
// to reach the receiver

int distance; // Variable to store distance calculated using
// formula

void setup()
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT

  // Serial Communication is starting with 9600 of
  // baudrate speed

  // The text to be printed in the serial monitor
  Serial.println("Distance measurement using ESP32");

void loop()
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // wait for 2 ms to avoid
  // collision in the serial monitor

  digitalWrite(trigPin, HIGH); // turn on the Trigger to generate pulse
  delayMicroseconds(10); // keep the trigger "ON" for 10 ms to generate
  // pulse for 10 ms.

  digitalWrite(trigPin, LOW); // Turn off the pulse trigger to stop
  // pulse generation

  // If pulse reached the receiver echoPin
  // become high Then pulseIn() returns the
  // time taken by the pulse to reach the
  // receiver

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.0344 / 2; // Expression to calculate
  // distance using time

  Serial.print("Distance: ");
  Serial.print(distance); // Print the output in serial monitor
  Serial.println(" cm");

Step 3: Code Walkthrough

Code Explanation:

Let’s walk through the code. This example measures the distance based on the signal feedback from the echo pin of the HCSR04 sensor.

#define echoPin 18 // attach pin GPIO18 ESP32 to pin Echo of HC-SR04
#define trigPin 5  // attach pin GPIO5 ESP32 to pin Trig of HC-SR04

These two lines define the pin numbers that are used to connect the HC-SR04 sensor to the Arduino board.

The echoPin is used to receive the echo signal from the sensor, and trigPin is used to trigger the sensor to send an ultrasonic pulse.

long duration;
int distance;

These two lines declare two variables, duration, and distance. duration is used to store the time it takes for the ultrasonic pulse to bounce back to the sensor, while distance is used to store the calculated distance in centimeters.

the setup() function, which is called once when the program starts. In this function, the trigPin is set as an output pin, and the echoPin is set as an input pin. 

Serial.begin(9600) initializes the serial communication at a baud rate of 9600, and the following Serial.println() statement is used to print a message to the serial monitor. 

The delay(500) function waits for half a second before proceeding to the loop() function.

The loop() function is called repeatedly throughout the program. 

This code starts by sending a low signal to the trigPin for 2 microseconds. Then it sends a high signal to the trigPin for 10 microseconds to generate a pulse for 10 milliseconds.

After the pulse is generated, the trigPin is turned off.

The pulseIn() function is then used to calculate the duration of the pulse. This function waits for the pulse to reach the echoPin and then measures the time it takes for the pulse to return. 

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.0344 / 2; // Expression to calculate
  // distance using time

The duration is then converted to a distance value using the expression which is based on the speed of sound (approximately 344 meters per second).

  Serial.print("Distance: ");
  Serial.print(distance); // Print the output in serial monitor
  Serial.println(" cm");

Finally, the distance value is printed to the serial monitor. The program then waits for 100 milliseconds before starting the loop over again.

I hope this explanation helps! Let me know if you have any other questions.

FAQs About The ESP32 And HC-SR04 Ultrasonic Sensor

I have included a list of the most frequently asked questions about projects built using the ESP32 and the distance sensor HC-SR04 sensors.

What is the HC-SR04 sensor?

The HC-SR04 is an ultrasonic sensor that uses sound waves to detect distance. It is commonly used in robotics, automation, and IoT projects.

It is a low-cost ultrasonic sensor to measure distance, detect an obstruction, etc. 

How does the HC-SR04 sensor work?

The sensor emits an ultrasonic pulse and then measures the time it takes for the pulse to bounce back after hitting an object.

This time is then used to calculate the distance to the object.

The signal moves approximately at the speed of sound. 

Hence, Distance = (Time taken to reach back X SpeedOfSound) / 2. 

Please refer to the Basics section of this article above for a detailed explanation.

What is the range of the HC-SR04 sensor?

The range of the sensor is typically between 2cm and 4m. A wide variety of ultrasonic sensors work at different frequencies and different ranges.

Please refer to the datasheet of the part you use for the most accurate information.

What is the accuracy of the HC-SR04 sensor?

The sensor’s accuracy depends on temperature, humidity, and the object being detected. However, in general, it has an accuracy of around 1 cm.

What is the operating voltage of the HC-SR04 sensor?

The operating voltage of the sensor is typically between 5V and 6V DC. Please refer to the datasheet for the correct information. 

What is the output of the HC-SR04 sensor?

The sensor outputs a digital signal (HIGH or LOW) corresponding to the object’s distance. 

How do I interface the HC-SR04 sensor with a microcontroller?

The sensor has four pins: VCC (power supply), GND (ground), TRIG (trigger), and ECHO (echo).

To interface it with a microcontroller, connect VCC to a 5V supply, GND to ground, TRIG to a digital output pin, and ECHO to a digital input pin.

Can I use multiple HC-SR04 sensors in the same project?

You can use multiple sensors by assigning each sensor a unique set of trigger and echo pins.

Consider a motor-mounted ultrasonic sensor through which you can get spatial information with just one sensor by rotating it as needed. 


In this article, I have taught you everything you need to know to build your distance measurement project successfully. 

You can use the HC-SR04 sensor in water level monitoring, movement detection, movement direction detection, and 3D mapping when you combine multiple sensors and motors. 

The connection guide and the example code helped you verify the connections and bring up your first ESP32 HC-SR04 project correctly. 

Was the article easy to follow? If you have suggestions to improve the article, you are always welcome to share feedback. What projects are you working on?

If you have further questions about the low-cost ultrasonic sensors, please post them in the comments section below.

Keep learning!