How to Interface HC-SR04 Sensor with ESP32 Using ESP-IDF (With Live Demo & Code)

Interfacing HC-SR04 Ultrasonic Sensor with ESP32 using ESP-IDF
1
0
4 min read

Looking to measure distance using ESP32? The HC-SR04 Ultrasonic Sensor is a fantastic module for beginners and professionals alike. In this tutorial, we’ll guide you step-by-step on how to interface this sensor with an ESP32 development board using ESP-IDF. You’ll learn how the sensor works, how to connect it, and how to write the firmware to get distance measurements.


📦 Components Required

To get started, you’ll need the following components:


🧠 Understanding HC-SR04 Sensor

The HC-SR04 ultrasonic sensor is a popular device. It is cost-effective. It is used for measuring distance by utilizing the principles of sound wave reflection. It operates using the time-of-flight method. This method calculates the time it takes for sound waves to travel to an object and bounce back.

  • VCC – Power supply (5V)
  • Trig – Trigger pulse input
  • Echo – Echo pulse output
  • GND – Ground

🚀 Working Principle:

  1. Trigger Initiation: When the Trigger pin receives a 10µs HIGH signal, it emits a short burst of ultrasonic sound. This consists of 8 pulses at 40 kHz.
  2. Wave Propagation: The ultrasonic waves travel through the air until they hit an object.
  3. Echo Reception: Once the waves hit an object, they bounce back and are received by the sensor’s Echo pin.
  4. Time Measurement: The time between sending and receiving the pulse is measured in microseconds.
  5. Distance Calculation:
    The distance to the object is calculated using the formula:
    Distance (cm)=(Time (µs)×0.0343)/2
    0.0343 cm/µs is the speed of sound in air.
    ○ The time is divided by 2 because it covers both the forward and return trip.

📏 Example:

If the Echo pin remains HIGH for 500 µs, the distance is:
500×0.03432/2=8.575 cm

This real-time, accurate, and non-contact distance measurement makes the HC-SR04 ideal for robotics, object avoidance, water level monitoring, and more.

It measures distances from 2 cm to 400 cm with a precision of about 3 mm.


🔌 Circuit Connections

HC-SR04 PinESP32 GPIO
VCC5V(VIN)
GNDGND
TrigGPIO 5
EchoGPIO 18

Tip: Use a voltage divider if you’re cautious about 5V on ESP32’s GPIOs. In many cases, the echo pin works reliably when connected directly to a 3.3V-compatible GPIO, but safety first!


🧰 ESP-IDF Project Structure

We’ll use the ESP-IDF framework to code the firmware. Make sure ESP-IDF is installed and set up.

idf.py create-project ultrasonic_sensor
cd ultrasonic_sensor

💻 Writing the Code

Here is the full C code to read distance using HC-SR04:

#include <stdio.h>
#include <stdbool.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <ultrasonic.h>
#include <esp_err.h>

#define MAX_DISTANCE_CM 500 // 5m max

#define TRIGGER_GPIO 5
#define ECHO_GPIO 18


void ultrasonic_test(void *pvParameters)
{
ultrasonic_sensor_t sensor = {
.trigger_pin = TRIGGER_GPIO,
.echo_pin = ECHO_GPIO
};

ultrasonic_init(&sensor);

while (true)
{
float distance;
esp_err_t res = ultrasonic_measure(&sensor, MAX_DISTANCE_CM, &distance);
if (res != ESP_OK)
{
printf("Error %d: ", res);
switch (res)
{
case ESP_ERR_ULTRASONIC_PING:
printf("Cannot ping (device is in invalid state)\n");
break;
case ESP_ERR_ULTRASONIC_PING_TIMEOUT:
printf("Ping timeout (no device found)\n");
break;
case ESP_ERR_ULTRASONIC_ECHO_TIMEOUT:
printf("Echo timeout (i.e. distance too big)\n");
break;
default:
printf("%s\n", esp_err_to_name(res));
}
}
else
printf("Distance: %0.04f cm\n", distance*100);

vTaskDelay(pdMS_TO_TICKS(500));
}
}

void app_main()
{
xTaskCreate(ultrasonic_test, "ultrasonic_test", configMINIMAL_STACK_SIZE * 3, NULL, 5, NULL);
}

Download the full code here.

🔧 Building and Flashing the Code

To build and flash the code:

idf.py build
idf.py -p /dev/ttyUSB0 flash
idf.py monitor

Make sure to replace /dev/ttyUSB0 with your actual serial port. The port will be different(like COM3, COM4, etc) if you are working on windows OS


🎯 Expected Output

After uploading the firmware and opening the serial monitor, you should see distance readings printed every second like this:

Distance: 17.32 cm
Distance: 18.04 cm
Distance: 17.58 cm

This confirms that your sensor is working correctly!


Also, watch this video to get the clear understand on how to do it practically with zero error ratio.

https://youtu.be/FS8bsHBiL6Y

🎓 Conclusion

Congratulations! You’ve successfully interfaced the HC-SR04 ultrasonic sensor with the ESP32 using ESP-IDF. This foundational setup opens up many project possibilities—from robot navigation to smart parking sensors.

👉 Need Components?

You can grab all the components used in this project from the links below:


💬 Got Questions?

Leave a comment below if you’re stuck or have suggestions! You can also check out our YouTube tutorial on this same project.

Let’s innovate together — one sensor at a time!

Also, check out our other playlist Rasa ChatbotInternet of thingsDockerPython ProgrammingMachine LearningNatural Language ProcessingMQTTTech NewsESP-IDF etc.
Become a member of our social family on youtube here.
Stay tuned and Happy Learning. ✌🏻😃
Happy coding, and your NLP endeavors be both enlightening and rewarding! ❤️🔥🚀🛠️🏡💡

Leave a Reply