Component Guide

Sensors Beginner

HC-SR04 Ultrasonic Distance Sensor

Low-cost ultrasonic distance sensor that measures nearby objects with sound pulses for ESP32 robots, parking aids, and level sensing.

BeginnerDifficulty 14 minReading time 20-35 minBench time ESP32Compatible
Share
HC-SR04 Ultrasonic Distance Sensor

Plain-English Overview

The HC-SR04 measures distance using echoes. It sends a short burst of sound that humans cannot hear, then waits for the sound to bounce off an object and return.

Your ESP32 measures how long the echo took. Sound moves through air at a known speed, so the code converts time into distance. If the echo returns quickly, the object is close. If it takes longer, the object is farther away.

Use it for simple distance experiments and robots. Do not use it where soft fabric, angled surfaces, wind, rain, or tiny objects must be measured accurately.

Where You Use It

  • Robot obstacle detection
  • Parking distance indicator
  • Tank level experiment
  • Hands-free trigger
  • Doorway people counter
  • Classroom echo demo
  • Trash-bin fill monitor
  • Distance alarm

Quick Facts

  • Range About 2 cm to 400 cm
  • Signal TRIG output and ECHO input
  • Power 5 V module power
  • ESP32 safety Level shift ECHO to 3.3 V
  • Best surface Flat and hard
  • Timing Microsecond pulse measurement

How It Works

The sensor has two round cans. One is an ultrasonic transmitter and the other is a receiver. When the ESP32 sends a 10 microsecond pulse to TRIG, the module emits a short burst near 40 kHz.

After transmitting, the ECHO pin goes HIGH. It stays HIGH until the reflected sound returns or the module times out. The ESP32 measures that HIGH time in microseconds.

Distance equals speed times time, but the sound travels to the object and back. That is why code divides by two. At room temperature, sound travels about 0.0343 centimeters per microsecond, so distance in cm is roughly duration * 0.0343 / 2.

The ECHO pin on many HC-SR04 modules is 5 V. ESP32 input pins are 3.3 V only, so use a voltage divider or level shifter. This one detail is the difference between a safe beginner build and a damaged board.

Technical Specifications

Arduino library: Built-in Arduino timing with pulseIn

SpecificationValueWhy it matters
Supply voltage 5 V typical Common modules need 5 V for the ultrasonic transmitter.
ESP32 input safety ECHO must be reduced to 3.3 V Protects the ESP32 GPIO from 5 V logic.
Range About 2 cm to 400 cm Objects too close or too far may produce invalid readings.
Best range Roughly 5 cm to 200 cm More reliable for beginner robots and classroom tests.
Accuracy About 3 mm under good conditions Real accuracy depends on angle, surface, and temperature.
Ultrasonic frequency Around 40 kHz Above human hearing, but still affected by surfaces and air.
Trigger pulse 10 microseconds HIGH Starts one distance measurement.
Echo output Pulse width proportional to distance The ESP32 measures this time to calculate distance.
Field of view Roughly 15 degrees Wide enough to detect nearby obstacles but not a camera-like beam.
Update interval Use 50 ms or slower Gives echoes time to fade before the next ping.
Poor targets Cloth, foam, angled surfaces, small objects These absorb or deflect sound away from the receiver.

Pinout

  • VCC Power input 5 V Power the module from 5 V unless you have a special 3.3 V version.
  • TRIG Trigger input ESP32 GPIO5 ESP32 output; 3.3 V HIGH is normally accepted by the module.
  • ECHO Echo output ESP32 GPIO18 through level shifter/divider Do not connect 5 V ECHO directly to ESP32.
  • GND Ground reference ESP32 GND Common ground is required for correct signal timing.

Wiring Diagram

The HC-SR04 uses 5 V power but the ESP32 uses 3.3 V logic. TRIG from ESP32 to sensor is usually safe, but ECHO from sensor to ESP32 must be level shifted.

A simple voltage divider can use 1 k ohm from ECHO to the ESP32 input and 2 k ohm from the ESP32 input to GND. A logic level shifter is also fine.

Wiring Diagram HC-SR04 VCC to 5 V, GND to GND, TRIG to GPIO5, ECHO through voltage divider to GPIO18
  1. 1

    Unplug USB before wiring.

  2. 2

    Connect HC-SR04 VCC to 5 V or VIN on the ESP32 board.

  3. 3

    Connect HC-SR04 GND to ESP32 GND.

  4. 4

    Connect TRIG to ESP32 GPIO5.

  5. 5

    Connect ECHO to a voltage divider or level shifter.

  6. 6

    Connect the shifted ECHO signal to ESP32 GPIO18.

  7. 7

    Point the sensor at a flat object at least 5 cm away.

  8. 8

    Upload the code and open Serial Monitor at 115200 baud.

Code Examples

Use the same wiring with Arduino IDE, PlatformIO, or ESP-IDF. Start with Arduino, then graduate when you need a larger project structure.

hcsr04_esp32_distance_test.ino
#define TRIG_PIN 5
#define ECHO_PIN 18

const unsigned long ECHO_TIMEOUT_US = 30000;
const float SOUND_CM_PER_US = 0.0343;

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);
  Serial.println("HC-SR04 ESP32 distance test");
}

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  unsigned long duration = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (duration == 0) {
    return -1.0;
  }

  return (duration * SOUND_CM_PER_US) / 2.0;
}

void loop() {
  float distanceCm = readDistanceCm();

  if (distanceCm < 2 || distanceCm > 400) {
    Serial.println("No reliable echo. Check target distance, angle, and wiring.");
  } else {
    Serial.print("Distance: ");
    Serial.print(distanceCm, 1);
    Serial.println(" cm");
  }

  delay(100);
}

TRIG is an ESP32 output. ECHO is an ESP32 input after level shifting. The timeout in pulseIn() prevents the sketch from waiting forever when no echo returns.

The code rejects distances outside the practical range so beginners do not trust impossible numbers. For robots, take several readings and use the median or average to reduce single bad echoes.

Expected Output

With a flat object in front of the sensor, Serial Monitor prints values such as Distance: 24.7 cm. Move your hand closer and the number decreases. Move it farther away and the number increases. If the object is too close, too soft, too angled, or missing, the sketch prints a no reliable echo message.

Common Mistakes

  • Connecting ECHO directly to ESP32 without level shifting.
  • Forgetting common ground.
  • Measuring objects closer than 2 cm.
  • Pointing the sensor at cloth or angled surfaces.
  • Using delay too short between pings.
  • Expecting perfect readings outdoors in wind.
  • Powering the module from weak 3.3 V.
  • Swapping TRIG and ECHO.
  • Using pulseIn without timeout.
  • Mounting the sensor where robot vibration changes its angle.

Troubleshooting

ProblemPossible causeSolution
Always reads 0 or timeout No echo, wrong wiring, or target out of range. Check TRIG/ECHO pins, common GND, and place a flat object 20 cm away.
ESP32 input damaged or unstable ECHO connected directly at 5 V. Use a voltage divider or level shifter before connecting ECHO.
Distance is double or half Formula forgot the divide-by-two or used wrong sound constant. Use duration * 0.0343 / 2 for centimeters.
Numbers jump wildly Object angle, soft target, vibration, or electrical noise. Aim at a flat hard surface and average several readings.
Short distances fail Object is inside the blind zone. Keep targets at least 2 to 5 cm away.
Long distances fail Echo too weak or timeout too short. Use larger flat target and timeout around 30000 us.
Works on Arduino Uno but not ESP32 Voltage-level assumptions differ. Level shift ECHO and confirm ESP32 GPIO numbers.
Robot sees obstacles late Sensor angle or update interval is wrong. Mount level and read every 50-100 ms.
False detections from floor Sensor points downward. Tilt sensor slightly up or adjust mounting height.
No readings after adding motor Motor noise or power dip. Use separate motor power and common ground.
Serial gibberish Wrong baud rate. Set Serial Monitor to 115200.
Only works when USB connected 5 V supply missing on external power. Provide stable 5 V to VCC and common GND.
Outdoor readings poor Wind and soft targets scatter sound. Use infrared, LiDAR, or waterproof ultrasonic module for outdoor use.
Multiple sensors interfere Pings overlap. Trigger sensors one at a time with delay between pings.
Tank level reading wrong Foam or angled liquid surface absorbs sound. Use stilling tube or different level sensor.

Related Guides

Related Projects

FAQ

Review, Testing, and References

Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-07-05. Reviewed: wiring, code, beginner safety, and ESP32 compatibility. Educational level: Beginner.

Use this component page as an educational starting point. Check official documentation before using the part in production, high-current, outdoor, battery, or safety-critical hardware.

Downloads

HC-SR04 datasheet for timing, range, voltage, and mechanical notes.

Download Datasheet (PDF)