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:
- β ESP32 Development Board
- β HC-SR04 Ultrasonic Sensor
- β Micro USB Cable
- β M2M Jumper Wires
- β Breadboard
π§ 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:
- 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.
- Wave Propagation: The ultrasonic waves travel through the air until they hit an object.
- Echo Reception: Once the waves hit an object, they bounce back and are received by the sensorβs Echo pin.
- Time Measurement: The time between sending and receiving the pulse is measured in microseconds.
- 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 Pin | ESP32 GPIO |
---|---|
VCC | 5V(VIN) |
GND | GND |
Trig | GPIO 5 |
Echo | GPIO 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.
π 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 Chatbot, Internet of things, Docker, Python Programming, Machine Learning, Natural Language Processing, MQTT, Tech News, ESP-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! β€οΈπ₯ππ οΈπ‘π‘