Skip to main content
ESPBoards

ESP32 HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 is a versatile ultrasonic distance sensor capable of measuring distances up to 4 meters with high precision. It is widely used in robotics and automation applications due to its low cost and simple operation. The sensor's compact design and efficient performance make it an excellent choice for both hobbyist and professional projects.

Jump to Code Examples

Arduino Core Image
ESP-IDF Image
ESPHome Image
PlatformIO Image
MicroPython Image

Quick Links

HC-SR04 Ultrasonic Distance Sensor Datasheet ButtonHC-SR04 Ultrasonic Distance Sensor Specs ButtonHC-SR04 Ultrasonic Distance Sensor Specs ButtonHC-SR04 Ultrasonic Distance Sensor Specs Button

HC-SR04 Price

Normally, the HC-SR04 Ultrasonic Distance Sensor costs around 1.5$ per Psc.
The prices are subject to change. Check current price:

Amazon com

Amazon de logo

Aliexpress logo

About HC-SR04 Ultrasonic Distance Sensor

The HC-SR04 is a low-cost ultrasonic distance sensor widely used for measuring distances ranging from 2 cm to 400 cm. It uses ultrasonic sound waves to calculate the distance to objects, making it ideal for obstacle detection, robotics, and automation projects. The sensor operates using a simple Trigger and Echo mechanism, with a short pulse sent by the Trigger pin and a corresponding pulse width on the Echo pin indicating the measured distance.

HC-SR04 Sensor Technical Specifications

Below you can see the HC-SR04 Ultrasonic Distance Sensor Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.

  • Protocol: Trigger/Echo
  • Measurement Range: 2 cm to 400 cm
  • Resolution: 0.3 cm
  • Accuracy: ±3 mm
  • Operating Voltage: 5V DC
  • Trigger Pulse Duration: 10 µs
  • Interface: Trigger/Echo

HC-SR04 Sensor Pinout

Below you can see the pinout for the HC-SR04 Ultrasonic Distance Sensor. The VCC pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND pin is the ground connection and must be connected to the ground of your ESP32!

The HC-SR04 pinout is simple and consists of the following pins:

  • VCC: Connect to a 5V power supply.
  • GND: Ground connection.
  • Trigger (TRIG): Input pin to initiate distance measurement by sending a short 10 µs pulse.
  • Echo: Output pin that provides a pulse width corresponding to the measured distance.

HC-SR04 Wiring with ESP32

Below you can see the wiring for the HC-SR04 Ultrasonic Distance Sensor with the ESP32. Connect the VCC pin of the sensor to the 3.3V pin on the ESP32 or external power supply for power and the GND pin of the sensor to the GND pin of the ESP32. Depending on the communication protocol of the sensor (e.g., I2C, SPI, UART, or analog), connect the appropriate data and clock or signal pins to compatible GPIO pins on the ESP32, as shown below in the wiring diagram.

To use the HC-SR04 with a microcontroller like an ESP32 or Arduino, connect VCC to a 5V power source, GND to ground, and the Trigger and Echo pins to two GPIO pins on the microcontroller. Ensure proper resistors or level shifters are used if interfacing with 3.3V logic devices.

Code Examples

Below you can find code examples of HC-SR04 Ultrasonic Distance Sensor with ESP32 in several frameworks:

Arduino Core Image

ESP32 HC-SR04 Arduino IDE Code Example

Example in Arduino IDE

Fill in your main Arduino IDE sketch file with the following code to use the HC-SR04 Ultrasonic Distance Sensor:

#define TRIG_PIN 5
#define ECHO_PIN 18

void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.println("HC-SR04 Distance Sensor Example");
}

void loop() {
long duration;
float distance;

// Trigger the sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Read the Echo pin
duration = pulseIn(ECHO_PIN, HIGH);

// Calculate distance in cm
distance = duration * 0.034 / 2;

Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

delay(500);
}

This Arduino sketch demonstrates how to use the HC-SR04 sensor for distance measurement. The TRIG_PIN and ECHO_PIN are defined to connect the sensor to GPIO pins 5 and 18, respectively. The setup() function initializes these pins and configures the Serial Monitor. In the loop(), a 10 µs pulse is sent to the Trigger pin to start measurement, and the duration of the Echo pin's HIGH state is measured using the pulseIn() function. The distance is calculated using the formula duration * 0.034 / 2, which converts the time into distance in centimeters.

Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.

ESP-IDF Image

ESP32 HC-SR04 ESP-IDF Code Example
Example in Espressif IoT Framework (ESP-IDF)

If you're using ESP-IDF to work with the HC-SR04 Ultrasonic Distance Sensor, here's how you can set it up and read data from the sensor. Fill in this code in the main ESP-IDF file:

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_timer.h"

#define TRIG_PIN GPIO_NUM_5
#define ECHO_PIN GPIO_NUM_18

void app_main() {
gpio_set_direction(TRIG_PIN, GPIO_MODE_OUTPUT);
gpio_set_direction(ECHO_PIN, GPIO_MODE_INPUT);

while (1) {
// Send trigger pulse
gpio_set_level(TRIG_PIN, 0);
ets_delay_us(2);
gpio_set_level(TRIG_PIN, 1);
ets_delay_us(10);
gpio_set_level(TRIG_PIN, 0);

// Measure echo pulse width
uint64_t start_time = esp_timer_get_time();
while (!gpio_get_level(ECHO_PIN)); // Wait for HIGH
uint64_t echo_start = esp_timer_get_time();
while (gpio_get_level(ECHO_PIN)); // Wait for LOW
uint64_t echo_end = esp_timer_get_time();

uint64_t duration = echo_end - echo_start;
float distance = (duration * 0.034) / 2;

printf("Distance: %.2f cm\n", distance);

vTaskDelay(pdMS_TO_TICKS(500));
}
}

This ESP-IDF code configures GPIO pins for the Trigger and Echo of the HC-SR04 sensor. The gpio_set_level() function sends a 10 µs pulse to the Trigger pin. The time taken for the Echo pin to go HIGH and then LOW is measured using esp_timer_get_time(), which provides timestamps in microseconds. The distance is calculated based on the formula (duration * 0.034) / 2. The program continuously measures and prints the distance in centimeters every 500 ms.

Update the I2C pins (I2C_MASTER_SDA_IO and I2C_MASTER_SCL_IO) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.

ESPHome Image

ESP32 HC-SR04 ESPHome Code Example

Example in ESPHome (Home Assistant)

Fill in this configuration in your ESPHome YAML configuration file (example.yml) to integrate the HC-SR04 Ultrasonic Distance Sensor

sensor:
- platform: ultrasonic
trigger_pin: 5
echo_pin: 18
name: "HC-SR04 Distance"
update_interval: 500ms
accuracy_decimals: 1
timeout: 2.0m

The ESPHome configuration uses the ultrasonic platform to interface with the HC-SR04 sensor. The trigger_pin and echo_pin specify the GPIO pins connected to the sensor. The name assigns a user-friendly identifier ('HC-SR04 Distance') for use in platforms like Home Assistant. The update_interval of 500 ms specifies how often distance measurements are taken, while accuracy_decimals ensures measurements are displayed to one decimal place. The timeout prevents errors in case of no response within the specified time.

Upload this code to your ESP32 using the ESPHome dashboard or the esphome run command.

PlatformIO Image

ESP32 HC-SR04 PlatformIO Code Example

Example in PlatformIO Framework

For PlatformIO, make sure to configure the platformio.ini file with the appropriate environment and libraries, and then proceed with the code.

Configure platformio.ini

First, your platformio.ini should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200

ESP32 HC-SR04 PlatformIO Example Code

Write this code in your PlatformIO project under the src/main.cpp file to use the HC-SR04 Ultrasonic Distance Sensor:

#define TRIG_PIN 5
#define ECHO_PIN 18

void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}

void loop() {
long duration;
float distance;

// Trigger the sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Read the Echo pin
duration = pulseIn(ECHO_PIN, HIGH);

// Calculate distance
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

delay(500);
}

The PlatformIO code is identical to the Arduino example, making it compatible with ESP32 boards configured via the PlatformIO environment. It uses TRIG_PIN and ECHO_PIN for sensor operation. A short 10 µs pulse triggers the measurement, and the pulse duration is read on the Echo pin using the pulseIn() function. The calculated distance is printed to the Serial Monitor every 500 ms.

Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload command.

MicroPython Image

ESP32 HC-SR04 MicroPython Code Example

Example in Micro Python Framework

Fill in this script in your MicroPython main.py file (main.py) to integrate the HC-SR04 Ultrasonic Distance Sensor with your ESP32.

from machine import Pin, time_pulse_us
from time import sleep

# Define pins for Trigger and Echo
TRIG_PIN = 5
ECHO_PIN = 18

# Initialize Trigger and Echo pins
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)

def measure_distance():
# Send a 10 µs pulse to the Trigger pin
trig.low()
sleep(0.000002) # 2 µs
trig.high()
sleep(0.00001) # 10 µs
trig.low()

# Measure the duration of the Echo pulse
duration = time_pulse_us(echo, 1, 30000) # Timeout after 30 ms (no response)

# Calculate distance in cm (speed of sound = 343 m/s)
distance = (duration * 0.0343) / 2
return distance

print("HC-SR04 Distance Sensor Example")

while True:
distance = measure_distance()
if distance > 0:
print("Distance: {:.2f} cm".format(distance))
else:
print("Out of range or no object detected.")
sleep(0.5)

This MicroPython script interfaces with the HC-SR04 sensor using Trigger and Echo pins. The Trigger pin sends a 10 µs pulse to initiate the measurement, while the Echo pin receives a pulse whose width corresponds to the distance measured. The time_pulse_us() function measures the duration of the Echo pulse in microseconds, with a timeout of 30 ms to prevent infinite waiting. The distance is calculated using the formula (duration * 0.0343) / 2, where 0.0343 cm/µs is the speed of sound. The script continuously measures and prints the distance to the console every 500 ms. If no response is detected, it prints an 'Out of range' message.

Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy.

Conclusion

We went through technical specifications of HC-SR04 Ultrasonic Distance Sensor, its pinout, connection with ESP32 and HC-SR04 Ultrasonic Distance Sensor code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.