HC-SR04 Ultrasonic Distance Sensor

View on Amazon
Overview
About HC-SR04 Ultrasonic Distance Sensor
The HC-SR04 is a budget-friendly ultrasonic sensor designed for precise distance measurement. Using ultrasonic sound waves, it accurately detects objects between 2 cm and 400 cm, making it ideal for obstacle detection, robotics, and automation projects.
⚡ Key Features
- Wide Measurement Range – Detects distances from 2 cm to 400 cm.
- Ultrasonic Sound Waves – Provides reliable and accurate distance calculations.
- Trigger & Echo Mechanism – Simple operation with digital pulse signals.
- Compatible with ESP32 & Arduino – Easy integration into microcontroller-based projects.
With its low cost, ease of use, and reliable performance, the HC-SR04 is a top choice for DIY electronics and robotic applications. 🚀
Get Your HC-SR04
Prices are subject to change. We earn from qualifying purchases as an Amazon Associate.
HC-SR04 Specifications
Complete technical specification details for HC-SR04 Ultrasonic Distance Sensor
📊 Technical Parameters
HC-SR04 Pinout
The HC-SR04 features a simple 4-pin design for power and trigger/echo ultrasonic measurement.
Visual Pinout Diagram

Pin Types
Quick Tips
Requires 5V power - most ESP32 boards provide this,⚠️ ECHO pin outputs 5V - use voltage divider for 3.3V ESP32
Measures 2cm to 400cm with ±3mm accuracy,🔊 Uses ultrasonic sound waves (40kHz)
Measurement takes about 10-25ms
Pin Descriptions
| Pin Name | Type | Description | Notes |
|---|---|---|---|
1 VCC | Power | Power supply input (5V required) | Requires stable 5V power supply |
2 GND | Power | Ground connection | Connect to ESP32 ground |
3 TRIG | Control | Trigger input pin | Send 10µs pulse to initiate measurement |
4 ECHO | Communication | Echo output pin | Returns pulse width proportional to distance |
Wiring HC-SR04 to ESP32
Connect the HC-SR04 with voltage divider for ECHO pin to protect 3.3V ESP32 GPIO.
Visual Wiring Diagram

Connection Status
Protocol
Pin Connections
| HC-SR04 Pin | Connection | ESP32 Pin | Description |
|---|---|---|---|
1 VCC Required | 5V | 5V power supply required | |
2 GND Required | GND | Ground connection | |
3 TRIG Required | GPIO5 | Trigger input (can handle 3.3V logic) | |
4 ECHO Required | GPIO18 | Echo output (use voltage divider) | |
5 ECHO (Divider) Required | 1kΩ + 2kΩ | Voltage divider to convert 5V to 3.3V |
ECHO pin outputs 5V - can damage 3.3V ESP32 GPIO
Use voltage divider: 1kΩ (ECHO to GPIO) + 2kΩ (GPIO to GND)
TRIG pin accepts 3.3V logic directly
Send 10µs HIGH pulse on TRIG to start measurement
ECHO pulse width in µs ÷ 58 = distance in cm
HC-SR04 Troubleshooting
Common issues and solutions to help you get your sensor working
Common Issues
Issue: The HC-SR04 ultrasonic sensor consistently returns zero or no distance measurements.
Possible causes include incorrect wiring, insufficient power supply, or faulty sensor hardware.
Solution: Verify that the VCC pin is connected to a stable 5V power source and the GND pin to ground. Ensure that the TRIG and ECHO pins are connected to the appropriate digital I/O pins on the microcontroller. Check for secure and correct connections, and consider testing the sensor with a different microcontroller or setup to rule out hardware defects.
Issue: The sensor provides inconsistent or incorrect distance readings.
Possible causes include environmental factors such as soft or angled target surfaces, electrical noise, or interference from nearby ultrasonic sensors.
Solution: Ensure that the target surface is hard and perpendicular to the sensor for optimal reflection. Implement averaging of multiple readings in your code to mitigate occasional erroneous data. Maintain a clear line of sight between the sensor and the target, and avoid operating multiple ultrasonic sensors in close proximity to prevent cross-talk interference.
Issue: The microcontroller fails to detect the HC-SR04 sensor, or the sensor does not respond to trigger signals.
Possible causes include incorrect pin assignments in the code, lack of proper initialization, or defective sensor module.
Solution: Double-check the pin assignments in your code to ensure they match the physical connections. Confirm that the sensor is properly initialized in the setup section of your code. If the issue persists, test the sensor with a known working setup or replace it to rule out hardware failure.
Issue: External factors cause the sensor to produce unreliable readings.
Possible causes include high ambient noise levels, temperature variations, or obstacles in the sensor's field of view.
Solution: Operate the sensor in a controlled environment to minimize acoustic and electrical noise. Be aware that temperature changes can affect the speed of sound; consider implementing temperature compensation if precise measurements are required. Ensure that there are no unintended obstacles within the sensor's detection range that could cause false readings.
Debugging Tips
Use the Serial Monitor to check for error messages and verify the sensor's output. Add debug prints in your code to track the sensor's state.
Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor's requirements.
Additional Resources
HC-SR04 Programming Examples
Ready-to-use code examples for different platforms and frameworks
#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);
}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.#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));
}
}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.sensor:
- platform: ultrasonic
trigger_pin: 5
echo_pin: 18
name: "HC-SR04 Distance"
update_interval: 500ms
accuracy_decimals: 1
timeout: 2.0multrasonic 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.platformio.ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200main.cpp
#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);
}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.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)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.Wrapping Up HC-SR04
The ESP32 HC-SR04 Ultrasonic Distance Sensor is a powerful distance sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it's a versatile choice for your IoT projects.
Best Practices
For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.
Safety First
Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.
Ready to Start Building?
Now that you have all the information you need, it's time to integrate the HC-SR04 into your ESP32 project and bring your ideas to life!








