HC-SR04 Ultrasonic Sensor with ESP32 — Manuscript, Part 1
SEO title
HC-SR04 Ultrasonic Sensor with ESP32 – Complete Distance Measurement Guide
Meta description
Learn how to use the HC-SR04 ultrasonic sensor with ESP32. Includes safe wiring, voltage dividers, distance calculations, obstacle detection, tank monitoring, troubleshooting, and real-world examples.
1. Introduction
The HC-SR04 is an inexpensive ultrasonic distance sensor commonly used in ESP32 projects. It can estimate the distance to a solid surface without physical contact, making it useful for obstacle detection, basic tank-level monitoring, parking indicators, and robot prototypes.
It is easy to make the sensor produce a number. It is harder to make that number dependable. The sensor has a blind zone at short range, its sound pulse can be distorted by surface angle and material, and its Echo output can reach 5 V while ESP32 GPIO is designed for 3.3 V logic. A correct voltage divider is therefore not optional decoration; it protects the ESP32 input.
This guide starts with the electrical and physical model, then moves toward filtering, practical examples, and reliable system design. Read the ESP32 Pinout Guide before wiring. The DHT11/DHT22 and BME280 guides are useful prerequisites for environmental projects, especially where temperature affects the speed of sound.
2. What Is the HC-SR04 Ultrasonic Sensor?
The HC-SR04 contains an ultrasonic transmitter, an ultrasonic receiver, and a small control circuit. When the Trigger input receives a short pulse, the module emits an ultrasonic burst, typically around 40 kHz. It then raises the Echo output while waiting for the reflected sound to return.
The ESP32 measures the Echo pulse duration. A longer pulse generally means the reflected sound took longer to travel to the target and back, which implies a greater distance.
The HC-SR04 works best with a broad, hard target positioned roughly perpendicular to the sensor face. A soft curtain, angled wall, narrow pole, absorbent material, irregular water surface, or moving target can reflect less sound toward the receiver and produce unstable or missing readings.
3. How Ultrasonic Distance Measurement Works
The measurement sequence has four steps:
The ESP32 sends a brief Trigger pulse.
The sensor emits an ultrasonic burst.
The sound reflects from a target.
The sensor holds Echo high for the round-trip travel time.
Because the sound travels to the object and back, distance is half the total path:
distance = (travel time × speed of sound) ÷ 2
At room temperature, the speed of sound is approximately 343 metres per second, or about 0.0343 centimetres per microsecond. A convenient approximation is:
distance in cm = echo duration in microseconds × 0.0343 ÷ 2
Temperature changes the speed of sound. For basic indoor work, the approximation is usually enough. For better accuracy, use temperature data from an existing DHT or BME280 sensor to adjust the sound-speed calculation.
4. HC-SR04 Specifications
Property Typical HC-SR04 value
Supply voltage 5 V
Trigger input Short logic pulse
Echo output 5 V pulse
Operating frequency About 40 kHz
Minimum practical distance About 2 cm
Maximum advertised distance About 400 cm
Reliable project range Often lower than advertised maximum
Beam pattern Broad cone, not a narrow laser
Specifications vary between module versions. Treat the advertised four-metre range as a best-case condition, not a guarantee. Test the final enclosure, target surface, and environment.
5. Advantages and Limitations
The HC-SR04 is inexpensive, non-contact, and easy to understand. It does not require I2C or SPI and can be driven with two ESP32 GPIO connections. It is useful for demonstrations and indoor prototypes.
Its limitations matter:
It is not waterproof.
It can be affected by target angle and material.
Echo is 5 V and requires level shifting.
Several nearby ultrasonic sensors can interfere with one another.
It cannot accurately measure inside its near-field blind zone.
Temperature, wind, humidity, and acoustic noise affect results.
For wet, dusty, outdoor, or industrial environments, consider a sealed ultrasonic sensor, a time-of-flight optical sensor, or another technology matched to the environment.
6. Required Components
ESP32 development board
HC-SR04 ultrasonic sensor
Breadboard and jumper wires
Two resistors for an Echo voltage divider
USB cable and Arduino IDE
Optional display, buzzer, servo, relay, or Wi-Fi dashboard
A practical divider uses 1 kΩ from Echo to the ESP32 input and 2 kΩ from the ESP32 input to ground. This reduces a 5 V Echo pulse to approximately 3.3 V.
7. HC-SR04 Pinout Explained
HC-SR04 pin Function
VCC 5 V module supply
Trig Trigger pulse input
Echo Echo pulse output at approximately 5 V
GND Shared ground
The ESP32 and sensor must share ground. Without a common reference, the ESP32 cannot reliably interpret Trigger or Echo signals.
8. Safe Wiring to ESP32
Connection ESP32 pin Notes
HC-SR04 VCC 5 V/VIN Power the module as specified
HC-SR04 GND GND Shared ground
HC-SR04 Trig GPIO5 ESP32 3.3 V output is generally sufficient
HC-SR04 Echo GPIO18 through divider Never connect Echo directly
Do not connect Echo directly to GPIO18 or any other ESP32 input. The sensor’s output can be approximately 5 V, above the ESP32’s safe logic level.
9. Why Voltage Dividers Are Important
The Echo signal is produced by a 5 V module. ESP32 GPIO inputs are 3.3 V logic. Direct connection can overstress the input protection structures and cause immediate failure, intermittent behavior, or long-term damage.
A resistor divider lowers the Echo voltage:
Divider arrangement Approximate output from 5 V
1 kΩ top, 2 kΩ bottom 3.33 V
4.7 kΩ top, 10 kΩ bottom 3.40 V
10 kΩ top, 20 kΩ bottom 3.33 V
Connect the top resistor between Echo and the ESP32 GPIO node. Connect the bottom resistor between that GPIO node and GND. Long-term protection also means short wiring, a stable ground, and avoiding accidental direct 5 V connections during breadboard changes.
10. Connecting Trigger and Echo Pins
Trigger is an ESP32 output. Echo is an ESP32 input after the divider.
ESP32 GPIO5 → HC-SR04 Trig
HC-SR04 Echo → top resistor → ESP32 GPIO18
ESP32 GPIO18 → bottom resistor → GND
ESP32 GND → HC-SR04 GND
ESP32 5 V → HC-SR04 VCC
Keep Trigger and Echo wires away from motor power cables where possible. Robots and pumps can introduce electrical noise that makes timing-based readings inconsistent.
11. Measuring Distance
const int trigPin = 5;
const int echoPin = 18;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
float readDistanceCm() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
unsigned long duration = pulseIn(echoPin, HIGH, 30000);
if (duration == 0) return -1;
return duration * 0.0343f / 2.0f;
}
void loop() {
float distance = readDistanceCm();
if (distance < 0) {
Serial.println("No echo received");
} else {
Serial.printf("Distance: %.1f cmn", distance);
}
delay(250);
}
Explanation: the ESP32 sends a ten-microsecond Trigger pulse, waits for Echo, and converts its duration to centimetres. The timeout prevents a missing echo from blocking the program indefinitely.
Expected Serial Monitor output:
Distance: 42.6 cm
Troubleshooting: if the result is always No echo received, check power, common ground, divider wiring, Trigger/Echo pin assignments, and whether an object is within a practical range.
12. Understanding Pulse Width
Pulse width is the duration for which Echo remains high. It represents sound travel time, not a direct distance unit. A reflected sound path of 100 cm means the pulse represents approximately 200 cm of sound travel because the wave goes outward and returns.
Using a timeout is important. Without one, a missing echo can pause a program long enough to disrupt displays, Wi-Fi tasks, robot control, or safety logic.
13. Distance Calculation Formula
The basic formula is:
distance_cm = duration_us × 0.0343 ÷ 2
For a temperature-aware estimate:
speed of sound (m/s) ≈ 331.3 + 0.606 × temperature_C
distance_cm = duration_us × speed_m_per_s ÷ 20000
The temperature-aware form is useful when combining HC-SR04 with the existing DHT11/DHT22 or BME280 guides.
11:56 PM
ok next
11:57 PM
HC-SR04 Ultrasonic Sensor with ESP32 — Manuscript, Part 2
14. Filtering Noisy Readings
Ultrasonic readings can jump when the target is angled, moving, soft, narrow, or outside the strongest part of the beam. A simple average reduces random variation:
float averageDistanceCm() {
const int samples = 5;
float total = 0;
int valid = 0;
for (int i = 0; i < samples; i++) {
float d = readDistanceCm();
if (d >= 0) {
total += d;
valid++;
}
delay(60);
}
return valid ? total / valid : -1;
}
Explanation: the function collects five readings, ignores failed measurements, and returns the average of valid values.
Expected output: values should fluctuate less than a single reading.
Troubleshooting: averaging cannot fix a fundamentally bad reflection. If readings remain unstable, improve target alignment, reduce range, shorten wiring, or choose a more appropriate sensor.
15. Measuring Short Distances
HC-SR04 has a near-field blind zone, commonly around two centimetres. Very close targets can produce unreliable reflections because the transmitted burst has not finished before the return arrives.
Do not use the sensor as a precision contact switch. For very short distances, use a different technology such as a time-of-flight optical sensor, mechanical limit switch, or capacitive/proximity sensor selected for the material and environment.
16. Measuring Long Distances
Long-range measurements are affected by target size, target material, angle, background noise, temperature, and air movement. A flat wall perpendicular to the sensor is easy to measure. A narrow chair leg or angled container wall is not.
Treat the maximum advertised range as an upper bound under favorable conditions. Design alarms and tank thresholds inside the range you have tested in the final enclosure.
17. Obstacle Detection Systems
Obstacle detection is more reliable when it uses zones rather than one precise distance:
float d = averageDistanceCm();
if (d < 0) {
Serial.println("Obstacle sensor unavailable");
} else if (d < 20) {
Serial.println("STOP: obstacle very close");
} else if (d < 50) {
Serial.println("CAUTION: obstacle ahead");
} else {
Serial.println("Path clear");
}
Explanation: zone logic is less sensitive to small measurement noise than reacting to every decimal value.
Expected output: a clear state based on distance.
Troubleshooting: use hysteresis in moving systems. For example, enter a warning at 50 cm but do not leave it until distance exceeds 55 cm.
18. Tank Level Monitoring
For a tank, mount the sensor above the liquid surface and measure the distance downward. Convert empty-space distance into fill level:
liquid level = tank internal height – measured empty-space distance
The sensor must remain dry and protected from condensation. HC-SR04 is not waterproof and should not be mounted where splashes, vapor, or condensation can reach its electronics. Test with the real tank shape; sloped walls and turbulence can scatter the ultrasonic reflection.
19. Parking Sensor Systems
A parking indicator can use progressive states:
More than 150 cm: clear
80–150 cm: approaching
30–80 cm: caution
Less than 30 cm: stop
Use a buzzer or display only after validating the sensor and voltage divider. Do not use a hobby HC-SR04 as the sole safety system for a real vehicle.
20. Robot Navigation Applications
The existing WiFi Robot project is a suitable relationship. HC-SR04 can provide a forward obstacle estimate, while a motor-control layer decides whether to slow, stop, reverse, or turn.
A single forward sensor cannot understand the full environment. It can miss narrow obstacles, reflect from angled surfaces poorly, and cannot see around corners. Better robots combine multiple sensors, motion limits, conservative behavior, and fault handling.
21. Performance Optimization
Use timeouts with pulseIn, avoid excessive sampling, and separate measurement from control logic. In a robot, measure at a fixed rate and keep motor safety independent of display refresh. In a tank monitor, several readings per minute may be enough.
For multiple ultrasonic sensors, trigger only one at a time. Wait for its echo or timeout before starting the next sensor. Simultaneous bursts can be mistaken for each other’s reflections.
22. Common Problems and Fixes
Problem Likely cause Fix
No echo Wiring, range, no shared ground Verify power, divider, target, pins
Constant zero Invalid pulse handling Use timeout and check duration
Unstable values Angled/soft target, noise Average readings; improve placement
ESP32 resets Echo wired directly at 5 V Add proper voltage divider
Wrong tank level Bad reference height Measure internal tank height carefully
False robot stop Echo from nearby sensor Trigger sensors sequentially
23. Troubleshooting Guide
Start with a stationary, flat target about 30–50 cm away.
Verify VCC and GND.
Verify Trigger GPIO.
Verify Echo divider orientation.
Confirm Echo reaches the ESP32 only through the divider.
Use the basic Serial sketch.
Test one sensor at a time.
Confirm target angle and practical range.
Add averaging only after a single reading works.
24. Best Practices
Always divide the 5 V Echo signal before ESP32 GPIO.
Use a timeout for every measurement.
Mount the sensor perpendicular to the expected target.
Use zones and hysteresis for alarms.
Sample only as often as the application needs.
Test with final power, enclosure, and target surfaces.
Keep ultrasonic sensors dry unless using a waterproof model.
Treat failed readings as faults, not zero distance.
25. Real-World Applications
Related existing projects:
Project HC-SR04 role
Distance Monitoring Project Core distance measurement input
WiFi Robot Obstacle-detection input
Smart Parking System Use only if an existing published project is available; otherwise do not link it
Future topics, without placeholder links:
ESP32 Servo Control
MPU6050 with ESP32
26. Conclusion
HC-SR04 is a useful ESP32 learning sensor when its electrical and physical limits are respected. The key safety rule is simple: Echo is approximately 5 V, while ESP32 GPIO is 3.3 V, so use a correctly wired voltage divider. The key measurement rule is equally important: ultrasonic distance is an estimate shaped by target geometry, environment, timing, and filtering.
FAQ
How accurate is HC-SR04?
It is suitable for hobby distance estimation, but accuracy varies with target surface, angle, temperature, and range.
What is the maximum range?
About 400 cm is commonly advertised, but reliable range is often lower in real installations.
What is the minimum range?
About 2 cm is typical; readings inside the blind zone are unreliable.
Can it measure water levels?
Yes, by measuring empty space above a calm liquid, but the standard module must remain dry.
Why are readings unstable?
Common causes are angled targets, weak reflections, noise, long wires, nearby sensors, and poor power.
Can multiple sensors be used?
Yes, but trigger them sequentially to avoid ultrasonic cross-talk.
Is a voltage divider required?
Yes. The Echo signal can be 5 V, which is unsafe for ESP32 GPIO.
Indoor vs outdoor use?
It is best indoors. The standard module is not waterproof and weather affects sound travel.
How often should measurements be taken?
Use the slowest rate that meets the application need; avoid unnecessary rapid triggering.
What are alternatives to HC-SR04?
Waterproof ultrasonic modules, time-of-flight optical sensors, LiDAR, IR sensors, and capacitive sensors may fit different environments better.
Internal linking plan
Prerequisites:
ESP32 Pinout Guide
DHT11/DHT22 with ESP32
BME280 with ESP32
Related existing projects:
ESP32 Distance Monitoring System
ESP32 WiFi Robot Controller
Related future guides:
ESP32 Servo Control
MPU6050 with ESP32
Originality review
This manuscript is newly written for ESP32Engine. It does not use existing project prose, unpublished batch content, or placeholder links.