HC-SR04 Ultrasonic Distance Sensor with Arduino & ESP32: Complete Beginner Guide

HC-SR04 ultrasonic distance sensor with Arduino Uno and ESP32 measuring the distance to an object

The HC-SR04 Ultrasonic Distance Sensor is a popular electronic module used to measure the distance between a sensor and a nearby object without physical contact. It is widely used with Arduino, ESP32 and other microcontroller boards in robotics, automation, security systems, water-level monitoring and smart electronics projects.

The module sends a burst of ultrasonic sound toward an object and measures how long the reflected sound takes to return. A microcontroller then uses this travel time to calculate the distance.

This beginner-friendly guide explains the HC-SR04 pinout, specifications, working principle, Arduino and ESP32 wiring, programming, troubleshooting and practical applications.

What You Will Learn

By the end of this guide, you will understand:

  • What the HC-SR04 ultrasonic sensor is
  • How ultrasonic distance measurement works
  • The function of the VCC, TRIG, ECHO and GND pins
  • How to connect the HC-SR04 to an Arduino Uno
  • How to connect it safely to an ESP32
  • How to calculate distance using echo-pulse duration
  • How to display readings in the Arduino Serial Monitor
  • How to troubleshoot unstable or incorrect measurements
  • Where the HC-SR04 is used in real-world projects

What Is an HC-SR04 Ultrasonic Sensor?

The HC-SR04 is a non-contact distance-measurement module. It uses ultrasonic sound waves that are above the normal range of human hearing.

The module has two circular ultrasonic transducers:

  • One transducer sends ultrasonic waves.
  • The other transducer receives the reflected echo.

Because the sensor does not need to touch the object, it is suitable for detecting obstacles, measuring liquid levels, assisting robots with navigation and monitoring the position of nearby objects.

The HC-SR04 is commonly used by:

  • Arduino beginners
  • Engineering students
  • Robotics enthusiasts
  • Embedded-system developers
  • STEM laboratories
  • Universities and technical institutes
  • DIY electronics makers

Main Features of the HC-SR04

The HC-SR04 offers a useful combination of affordability, simplicity and measuring performance.

Its main features include:

  • Non-contact distance measurement
  • Typical measuring range from approximately 2 cm to 400 cm
  • Four-pin interface
  • 5V operating supply
  • Ultrasonic operating frequency around 40 kHz
  • Fast response
  • Low power consumption
  • Easy integration with Arduino
  • Compatible with ESP32 when the ECHO voltage is reduced
  • Suitable for robotics and automation projects

The actual performance can vary depending on the object’s shape, surface, angle, size and surrounding environmental conditions.

HC-SR04 Technical Specifications

Specification Typical Value
Module type Ultrasonic distance sensor
Operating voltage 5V DC
Operating current Approximately 15 mA
Measuring range Approximately 2–400 cm
Typical accuracy Approximately ±3 mm under suitable conditions
Ultrasonic frequency Around 40 kHz
Trigger input Minimum 10 μs HIGH pulse
Output signal ECHO pulse proportional to travel time
Measuring angle Approximately 15°
Interface pins VCC, TRIG, ECHO and GND
Measurement method Ultrasonic time of flight

These figures are typical values. Real-world results can change depending on the target material, sensor alignment, temperature, electrical noise and power-supply stability.

HC-SR04 Pinout

The HC-SR04 has four pins arranged in the following order on most modules:


VCC — TRIG — ECHO — GND

VCC Pin

The VCC pin supplies power to the sensor.

It is normally connected to:

  • Arduino Uno 5V
  • ESP32 development-board 5V or VIN supply, depending on the board design
  • A regulated external 5V power supply

The sensor should not be powered from an unstable or incorrectly regulated source.

TRIG Pin

The TRIG pin starts a distance measurement.

The microcontroller sends a short HIGH pulse of at least approximately 10 microseconds to this pin. The HC-SR04 then emits a short burst of ultrasonic waves.

The TRIG pin is an input to the sensor.

ECHO Pin

The ECHO pin sends a HIGH pulse back to the microcontroller.

The duration of this pulse represents the total time taken by the ultrasonic wave to:

  1. Travel from the sensor to the object
  2. Reflect from the object
  3. Return to the sensor

The microcontroller measures this pulse duration and calculates the distance.

The HC-SR04 ECHO output can reach approximately 5V. That is acceptable for an Arduino Uno, but it should not be connected directly to a 3.3V-only ESP32 GPIO pin. A voltage divider or suitable level-shifting circuit should be used.

GND Pin

The GND pin is the electrical ground connection.

It must be connected to the ground of the Arduino, ESP32 or external power supply. All devices in the circuit must share a common ground.

How Does the HC-SR04 Work?

The HC-SR04 works using the time-of-flight principle.

The complete process happens in six stages.

1. The Microcontroller Sends a Trigger Pulse

The Arduino or ESP32 sends a HIGH pulse of approximately 10 microseconds to the TRIG pin.

This tells the HC-SR04 to begin a new measurement.

2. The Sensor Produces an Ultrasonic Burst

The transmitting transducer emits a short burst of ultrasonic sound at approximately 40 kHz.

These sound waves travel through the air.

3. The Sound Travels Toward an Object

The waves continue moving until they encounter a surface such as:

  • A wall
  • A box
  • A vehicle
  • A person
  • Water inside a tank
  • An obstacle in front of a robot

4. The Sound Reflects from the Object

When the ultrasonic wave hits the object, part of the sound reflects toward the sensor.

Hard and flat surfaces generally provide stronger reflections than soft, angled or sound-absorbing surfaces.

5. The Receiver Detects the Echo

The receiving transducer detects the returning ultrasonic wave.

The module keeps the ECHO pin HIGH for a duration corresponding to the total travel time.

6. The Microcontroller Calculates Distance

The Arduino or ESP32 measures how long the ECHO pin remains HIGH.

It then uses the speed of sound to convert the travel time into distance.

HC-SR04 Distance Formula

The ultrasonic wave travels to the object and then returns to the sensor. Therefore, the measured travel path is twice the actual distance.

The basic formula is:


Distance = (Echo Duration × Speed of Sound) ÷ 2

For common Arduino calculations using microseconds and centimetres, this is often simplified to:


Distance in cm = Echo Duration in microseconds × 0.0343 ÷ 2

Another commonly used version is:


Distance in cm = Echo Duration ÷ 58

The division by two is necessary because the measured time includes both the outward and return journeys.

Example Calculation

Suppose the ECHO pulse remains HIGH for approximately 1,458 microseconds:


Distance = 1458 × 0.0343 ÷ 2
Distance ≈ 25 cm

The object is therefore approximately 25 centimetres away from the sensor.

Factors That Affect Ultrasonic Measurements

The HC-SR04 can provide useful results, but its readings depend on the target and environment.

Object Angle

An object positioned at a steep angle may reflect the sound away from the receiver instead of back toward it.

Target Surface

Hard, flat surfaces usually produce strong echoes. Soft materials such as fabric, foam or carpet may absorb ultrasonic sound.

Object Size

Very small or narrow objects may not reflect enough sound for reliable detection.

Temperature

The speed of sound changes slightly with air temperature, which can affect precision in demanding applications.

Electrical Noise

Long jumper wires, poor grounding or an unstable power supply may cause fluctuating readings.

Minimum Distance

Objects placed too close to the sensor can fall inside its blind zone and may not be measured correctly.

Components Required

For the Arduino Uno setup, you will need:

  • HC-SR04 Ultrasonic Distance Sensor
  • Arduino Uno
  • Male-to-female jumper wires
  • USB programming cable
  • Breadboard, optional
  • Computer with Arduino IDE installed

For the ESP32 setup, you will also need:

  • ESP32 development board
  • 2 kΩ resistor
  • 3.3 kΩ resistor

The two resistors are used to build a voltage divider for the ESP32 ECHO connection.

HC-SR04 Wiring with Arduino Uno

The HC-SR04 works directly with the Arduino Uno because both devices use 5V logic for this connection.

Use the following connections:

HC-SR04 Pin Arduino Uno Connection
VCC 5V
TRIG Digital Pin 9
ECHO Digital Pin 10
GND GND

Step-by-Step Wiring

  1. Connect the HC-SR04 VCC pin to the Arduino 5V pin.
  2. Connect the sensor GND pin to Arduino GND.
  3. Connect the TRIG pin to Arduino digital pin 9.
  4. Connect the ECHO pin to Arduino digital pin 10.
  5. Connect the Arduino Uno to your computer using a USB cable.

Check the pin labels carefully before powering the circuit. Reversing VCC and GND may damage the sensor.

Arduino Code for HC-SR04

Open the Arduino IDE and create a new sketch.

Copy and upload the following code:


const int trigPin = 9;
const int echoPin = 10;

long duration;
float distanceCm;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.begin(9600);
  Serial.println("HC-SR04 Distance Sensor");
  Serial.println("-----------------------");
}

void loop() {
  // Ensure the trigger pin starts LOW
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Send a 10 microsecond trigger pulse
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the ECHO pulse duration
  duration = pulseIn(echoPin, HIGH, 30000);

  // Check whether a valid echo was received
  if (duration == 0) {
    Serial.println("No object detected or object out of range");
  } else {
    // Convert duration into distance
    distanceCm = duration * 0.0343 / 2.0;

    Serial.print("Distance: ");
    Serial.print(distanceCm, 2);
    Serial.println(" cm");
  }

  delay(500);
}

How the Arduino Code Works

Defining the Pins


const int trigPin = 9;
const int echoPin = 10;

These lines assign Arduino pin 9 to the sensor’s TRIG pin and pin 10 to the ECHO pin.

Creating Measurement Variables


long duration;
float distanceCm;

The duration variable stores the ECHO pulse length in microseconds.

The distanceCm variable stores the calculated distance in centimetres.

Configuring the Pins


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

The TRIG pin is configured as an output because the Arduino sends a pulse to the sensor.

The ECHO pin is configured as an input because the Arduino receives the timing signal from the sensor.

Starting Serial Communication


Serial.begin(9600);

This starts communication between the Arduino and the Serial Monitor at 9600 baud.

Make sure the Serial Monitor is also set to 9600 baud.

Sending the Trigger Pulse


digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);

digitalWrite(trigPin, LOW);

The Arduino first keeps the TRIG pin LOW briefly to ensure a clean signal.

It then sends a HIGH pulse for 10 microseconds, which starts the ultrasonic measurement.

Measuring the ECHO Duration


duration = pulseIn(echoPin, HIGH, 30000);

The pulseIn() function measures how long the ECHO pin remains HIGH.

The third value, 30000, is a timeout in microseconds. It prevents the program from waiting indefinitely when no echo is received.

Calculating Distance


distanceCm = duration * 0.0343 / 2.0;

The value 0.0343 represents the approximate speed of sound in centimetres per microsecond.

The result is divided by two because the sound travels to the object and then returns to the sensor.

Viewing Distance in the Serial Monitor

After uploading the code:

  1. Open the Arduino IDE.
  2. Click Tools.
  3. Select Serial Monitor.
  4. Set the baud rate to 9600.
  5. Place an object in front of the sensor.

You should see output similar to:


HC-SR04 Distance Sensor
-----------------------
Distance: 10.04 cm
Distance: 24.98 cm
Distance: 50.12 cm

Move the object closer or farther away and observe how the readings change.

Practical Distance-Measurement Test

For a simple accuracy test:

  1. Place the HC-SR04 on a stable surface.
  2. Position a flat box directly in front of the sensor.
  3. Use a ruler to measure the actual distance.
  4. Compare the ruler value with the Serial Monitor reading.
  5. Repeat the test at different distances.

Suggested test points include:

  • 5 cm
  • 10 cm
  • 20 cm
  • 30 cm
  • 50 cm
  • 100 cm

A small difference between the actual and measured values is normal.

For better results:

  • Keep the object directly facing the sensor.
  • Use a large, hard, flat surface.
  • Keep the sensor stable.
  • Avoid testing near soft fabric or angled objects.
  • Use short jumper wires.

Real Hardware Setup

A real circuit may include:

  • Arduino Uno
  • HC-SR04
  • Breadboard
  • Jumper wires
  • LCD display
  • Object used as the measurement target

A display is optional. The beginner circuit can show distance only in the Serial Monitor.

Later, the same sensor can be connected to:

  • A 16x2 LCD
  • OLED display
  • Buzzer
  • Servo motor
  • Relay module
  • Robot motor driver

HC-SR04 Wiring with ESP32

The HC-SR04 can also work with an ESP32, but one important voltage difference must be considered.

The ESP32 GPIO pins operate at approximately 3.3V logic, while the standard HC-SR04 ECHO pin can output approximately 5V.

Connecting the ECHO pin directly to an ESP32 GPIO may damage the ESP32 over time.

Use the following connections:

HC-SR04 Pin ESP32 Connection
VCC 5V or VIN
TRIG GPIO 23
ECHO GPIO 22 through voltage divider
GND GND

ESP32 ECHO Voltage Divider

A voltage divider safely reduces the HC-SR04’s 5V ECHO signal to approximately 3.3V.

Use:

  • R1 = 2 kΩ
  • R2 = 3.3 kΩ

Connect the circuit as follows:


HC-SR04 ECHO
      |
     R1
    2 kΩ
      |
      +-------- ESP32 GPIO 22
      |
     R2
   3.3 kΩ
      |
     GND

The output voltage is approximately:


Vout = Vin × R2 ÷ (R1 + R2)

With a 5V input:


Vout = 5 × 3.3 ÷ (2 + 3.3)
Vout ≈ 3.11V

This is safe for the ESP32 GPIO input.

Do not connect the ESP32 GPIO directly to the standard HC-SR04 ECHO output unless your specific sensor version already provides a 3.3V-safe output.

ESP32 Code for HC-SR04

Use the following code in the Arduino IDE:


const int trigPin = 23;
const int echoPin = 22;

long duration;
float distanceCm;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.begin(115200);
  Serial.println("HC-SR04 with ESP32");
  Serial.println("------------------");
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH, 30000);

  if (duration == 0) {
    Serial.println("No valid echo received");
  } else {
    distanceCm = duration * 0.0343 / 2.0;

    Serial.print("Distance: ");
    Serial.print(distanceCm, 2);
    Serial.println(" cm");
  }

  delay(500);
}

Uploading the Code to ESP32

Before uploading:

  1. Install ESP32 board support in the Arduino IDE.
  2. Connect the ESP32 with a data-capable USB cable.
  3. Select the correct ESP32 board from Tools → Board.
  4. Select the correct COM port.
  5. Upload the sketch.
  6. Open the Serial Monitor.
  7. Set the baud rate to 115200.

Some ESP32 boards may require you to hold the BOOT button briefly while uploading.

Arduino Uno vs ESP32 for HC-SR04

Feature Arduino Uno ESP32
Logic voltage 5V 3.3V
Direct ECHO connection Yes No, use voltage divider
Wi-Fi No Built in
Bluetooth No Built in
Beginner friendliness Excellent Good
Best use Basic distance projects IoT and wireless projects

Choose the Arduino Uno for simple beginner experiments.

Choose the ESP32 when the project requires:

  • Wi-Fi
  • Bluetooth
  • Mobile monitoring
  • Cloud data logging
  • Web dashboards
  • IoT automation

Common Wiring Mistakes

Reversing VCC and GND

Always check the pin labels before powering the circuit.

Swapping TRIG and ECHO

The circuit will not work correctly if these pins are reversed.

Missing Common Ground

The sensor and microcontroller must share the same ground.

Direct ESP32 ECHO Connection

Use a voltage divider to protect the ESP32 input.

Incorrect GPIO Numbers

Make sure the code matches the physical wiring.

Loose Jumper Wires

Intermittent connections can cause unstable or zero readings.

Common HC-SR04 Problems and Solutions

The HC-SR04 is simple to use, but incorrect wiring, weak reflections or unstable power can produce unreliable results.

Sensor Always Shows 0 cm

Possible causes:

  • ECHO pin is not connected correctly.
  • TRIG and ECHO wires are reversed.
  • The GPIO numbers in the code do not match the wiring.
  • The target is outside the sensor’s measuring range.
  • The sensor is not receiving 5V power.
  • Jumper wires are loose or damaged.

Check the complete circuit and confirm that all devices share a common ground.

Sensor Shows Maximum or Very Large Distance

This usually means that no valid echo is returning to the receiver.

Possible reasons include:

  • The target is too far away.
  • The object is too small.
  • The object is positioned at an angle.
  • The surface absorbs ultrasonic sound.
  • The sensor is not facing the object directly.

Use a large, hard and flat target during testing.

Readings Change Continuously

Small changes are normal, but large fluctuations may indicate:

  • Unstable power
  • Long jumper wires
  • Loose breadboard connections
  • Electrical interference
  • A moving target
  • A soft or irregular surface
  • Multiple ultrasonic sensors interfering with each other

Taking several measurements and calculating an average can make the output more stable.

ESP32 Gives Incorrect Readings

Confirm that:

  • The HC-SR04 is powered from 5V.
  • The ECHO signal passes through a voltage divider.
  • ESP32 GPIO numbers match the code.
  • The ESP32 and HC-SR04 grounds are connected.
  • The correct board and COM port are selected in Arduino IDE.

Never assume that a standard HC-SR04 ECHO output is safe for direct connection to a 3.3V ESP32 input.

Serial Monitor Displays Nothing

Check the following:

  • Correct COM port is selected.
  • The code uploaded successfully.
  • Serial Monitor baud rate matches the code.
  • Arduino Uno code uses 9600 baud.
  • ESP32 code uses 115200 baud.
  • The USB cable supports data transfer.

Some low-cost USB cables provide power only and cannot upload code.

Distance Is Approximately Double or Half the Correct Value

This usually comes from an incorrect formula.

Use:

Distance in cm = Echo Duration × 0.0343 ÷ 2

The division by two is required because the sound travels to the target and then back to the sensor.

How to Improve HC-SR04 Measurement Accuracy

The HC-SR04 is suitable for educational and general-purpose projects, but proper setup is important.

Keep the Sensor Stable

Mount the sensor securely so it does not move during measurement.

A moving sensor changes the angle and distance of the ultrasonic path.

Use a Flat Target

A large, hard and flat object gives a stronger echo than a narrow, curved or soft surface.

Position the Target Straight

The surface should face the sensor directly.

Angled surfaces may reflect sound away from the receiver.

Use Short Jumper Wires

Short wires reduce noise and loose-connection problems.

Take Multiple Samples

Instead of using one reading, take several measurements and calculate an average.

Example:


float totalDistance = 0;

for (int i = 0; i < 5; i++) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH, 30000);

  if (duration > 0) {
    totalDistance += duration * 0.0343 / 2.0;
  }

  delay(50);
}

float averageDistance = totalDistance / 5.0;

Averaging helps reduce occasional spikes.

Add a Timeout

Use a timeout with pulseIn():


duration = pulseIn(echoPin, HIGH, 30000);

This prevents the program from waiting too long when no echo is detected.

Avoid Measuring Too Frequently

Allow a short delay between readings.

A delay of approximately 50–100 milliseconds helps prevent one ultrasonic burst from interfering with the next.

Consider Temperature Compensation

The speed of sound changes slightly with temperature.

For ordinary beginner projects, the standard formula is usually sufficient. More precise applications may use a temperature sensor to adjust the speed-of-sound value.

Real-World Applications of the HC-SR04

The HC-SR04 is used in many educational, robotics and automation projects.

Obstacle-Avoiding Robots

A robot uses the HC-SR04 to detect objects in front of it.

The controller can then stop, reverse or change direction.

This project often combines:

  • Arduino Uno
  • HC-SR04
  • L298N motor driver
  • DC geared motors
  • Robot chassis
  • SG90 servo motor

Automatic Dustbin

The sensor detects when a hand approaches the dustbin.

An Arduino then controls an SG90 servo motor to open the lid automatically.

Water-Level Monitoring

The HC-SR04 can be installed above a water tank to measure the distance between the sensor and the water surface.

The controller can estimate whether the tank is:

  • Empty
  • Partially filled
  • Nearly full
  • Completely full

The sensor should be protected from moisture and condensation.

Parking Assistance

The sensor measures the distance between a vehicle and a wall or obstacle.

A buzzer or display can warn the driver as the distance decreases.

People and Object Detection

The sensor can detect when a person or object enters a defined area.

It can be used in:

  • Entry counters
  • Security systems
  • Automatic doors
  • Interactive displays
  • Smart lighting

Robot Navigation

Mobile robots use ultrasonic sensors to understand nearby obstacles and select a safer path.

More advanced robots may use multiple sensors for front, left and right detection.

Smart Home Automation

HC-SR04-based projects can control:

  • Lights
  • Curtains
  • Doors
  • Alarms
  • Displays
  • Touch-free switches

Distance-Meter Projects

A simple handheld distance meter can combine:

  • HC-SR04
  • Arduino or ESP32
  • OLED or LCD
  • Battery supply
  • Enclosure

HC-SR04 vs HC-SR04P

The HC-SR04 and HC-SR04P are similar ultrasonic distance sensors, but the HC-SR04P is commonly marketed as a wider-voltage or more 3.3V-friendly version.

Feature HC-SR04 HC-SR04P
Typical supply 5V Often advertised for wider voltage support
Arduino Uno use Direct connection Direct connection on compatible versions
ESP32 use ECHO voltage reduction recommended May offer better 3.3V compatibility
Measuring method Ultrasonic time of flight Ultrasonic time of flight
Typical application Arduino and 5V projects Arduino, ESP32 and low-voltage projects
Availability Very common Depends on supplier

Specifications can vary between manufacturers and cloned modules. Always check the documentation or test the actual module before connecting its ECHO output directly to a 3.3V microcontroller.

For the standard HC-SR04, using a voltage divider with ESP32 remains the safer approach.

HC-SR04 vs IR Obstacle Sensor

These two sensors are often used in beginner robotics, but they perform different tasks.

Feature HC-SR04 Ultrasonic Sensor IR Obstacle Sensor
Main purpose Measures approximate distance Detects object presence
Detection method Ultrasonic sound Infrared light
Output Distance based on echo time Usually digital detection output
Typical range Longer Usually shorter
Surface sensitivity Affected by angle and sound absorption Affected by colour and ambient light
Best for Distance measurement and navigation Basic obstacle or line detection
Outdoor use Can be affected by environment Bright sunlight can reduce performance

Choose the HC-SR04 when the project needs an approximate distance value.

Choose an IR sensor when only simple object detection is required.

Advantages of the HC-SR04

  • Affordable and widely available
  • Easy to connect with Arduino
  • Non-contact measurement
  • Suitable for beginners
  • Useful measuring range
  • Simple four-pin interface
  • No special Arduino library required
  • Works in many robotics projects
  • Easy to combine with displays, buzzers and motors
  • Large amount of learning material available

Limitations of the HC-SR04

  • Standard ECHO output is not directly safe for many 3.3V GPIO pins
  • Soft materials may absorb ultrasonic waves
  • Angled surfaces may produce weak echoes
  • Very small objects may be difficult to detect
  • Measurements may fluctuate
  • Outdoor wind and environmental conditions can affect results
  • It is not waterproof
  • It has a short minimum detection distance
  • Multiple nearby ultrasonic sensors may interfere with each other
  • It is not suitable for high-precision industrial measurement

For wet or outdoor environments, consider a waterproof ultrasonic sensor designed for those conditions.

Recommended Products for This Project

Add direct product links to the items available on Chip.pk.

Main Product

HC-SR04 Ultrasonic Distance Sensor Module

Use it for Arduino, robotics, distance measurement and automation projects.

Development Boards

  • Arduino Uno R3
  • ESP32 development board
  • Arduino Nano
  • Raspberry Pi Pico, with suitable voltage considerations

Connection Accessories

  • Male-to-female jumper wires
  • Male-to-male jumper wires
  • Breadboard
  • USB programming cable
  • Resistor pack
  • 2 kΩ and 3.3 kΩ resistors for the ESP32 divider

Frequently Asked Questions

What is the HC-SR04 used for?

The HC-SR04 is used to measure the approximate distance between the sensor and an object using ultrasonic sound waves.

What is the measuring range of the HC-SR04?

It is commonly specified for approximately 2 cm to 400 cm, although practical performance depends on the target and environment.

Does the HC-SR04 work with Arduino Uno?

Yes. It connects directly to Arduino Uno using 5V, GND and two digital pins.

Does the HC-SR04 work with ESP32?

Yes, but the standard module’s ECHO output should be reduced to a safe voltage using a voltage divider or level shifter.

Why is a voltage divider needed with ESP32?

The ESP32 uses 3.3V GPIO logic, while the HC-SR04 ECHO signal can be approximately 5V.

Can the HC-SR04 measure water level?

Yes. It can measure the distance to the water surface from above, but the module itself is not waterproof.

Can it detect transparent objects?

Detection depends on whether the object reflects ultrasonic sound. Transparency to visible light is not the main factor.

Can it detect people?

Yes, provided the person is within range and positioned where enough ultrasonic energy reflects back to the receiver.

Why does the sensor show unstable readings?

Possible causes include weak reflections, loose wires, electrical noise, moving targets and angled surfaces.

What frequency does the HC-SR04 use?

It commonly operates using ultrasonic bursts around 40 kHz.

Does the HC-SR04 need a library?

No. It can be controlled using standard Arduino functions such as digitalWrite(), delayMicroseconds() and pulseIn().

Can multiple HC-SR04 sensors be used together?

Yes, but they should be triggered one at a time to reduce ultrasonic interference.

Can it measure through glass or walls?

No. It normally measures the first surface that reflects the ultrasonic waves.

Is the HC-SR04 waterproof?

No. Standard HC-SR04 modules are not designed for direct exposure to water or rain.

Can the sensor detect very small objects?

Small or narrow objects may not reflect enough sound for reliable measurement.

What is the best target for testing?

A large, hard and flat box or wall positioned directly in front of the sensor.

Why is the distance divided by two?

The measured time includes the sound travelling to the object and returning to the sensor.

Can the HC-SR04 control a motor directly?

No. The sensor provides a measurement signal. A microcontroller and motor driver are needed to control motors.

Is HC-SR04 good for an obstacle-avoiding robot?

Yes. It is one of the most popular sensors for beginner obstacle-avoiding robot projects.

Which is better: HC-SR04 or an IR sensor?

The HC-SR04 is better for approximate distance measurement, while an IR obstacle sensor is useful for simple short-range object detection.

🌐 Continue Learning Across Our Platforms

Choose your preferred platform to explore this guide and discover more electronics tutorials from Chip.pk.

🌐 Original Article (Chip.pk Knowledge Hub)

Read the complete guide on the official Chip.pk Knowledge Hub, featuring detailed explanations, wiring diagrams, Arduino & ESP32 examples, troubleshooting tips, and product recommendations.

📘 GitHub Repository

Browse the complete documentation, source code, project files, and technical resources on GitHub.

🛠 Hackster.io Project

Follow the practical project tutorial with hardware connections, implementation steps, and example code.

💻 DEV Community

Explore the developer-focused version with formatted code examples, wiring diagrams, and implementation details.

🛒 Recommended Products

Build your HC-SR04 distance measurement project using genuine electronic components available from Chip.pk.

📡 HC-SR04 Ultrasonic Distance Sensor

The main component used in this tutorial for accurate non-contact distance measurement.

🤖 Arduino Uno R3

Perfect for beginners learning Arduino programming, robotics, and sensor interfacing.

📶 ESP32 Development Board

Ideal for IoT, Wi-Fi, Bluetooth, and smart automation projects using the HC-SR04.

🍞 Breadboard

Build your prototype quickly without soldering.

🔌 Jumper Wires

High-quality jumper wires for reliable breadboard and Arduino connections.

⚡ Resistor Kit

Useful for creating the voltage divider required when connecting the HC-SR04 ECHO pin to an ESP32.

⚙️ SG90 Micro Servo Motor

Perfect for automatic dustbin, smart gate, and obstacle-avoiding robot projects.

🚗 L298N Motor Driver Module

Control DC motors and build robot cars using the HC-SR04 sensor.

🚘 Robot Car Chassis Kit

Build an obstacle-avoiding robot using the HC-SR04, Arduino, and motor driver.

📟 16×2 LCD with I2C Module

Display distance measurements in real time without using the Serial Monitor.

Complete Your Project with Chip.pk

Whether you're building a beginner Arduino project, a smart automation system, or a robotics prototype, Chip.pk offers genuine electronic components, expert technical guidance, and fast nationwide delivery across Pakistan.

🛍️ Browse All Products:

 

Build your next project

Explore genuine electronics and embedded systems products

Shop Arduino, ESP32, Raspberry Pi, STM32, robotics, sensors, power modules, LED lighting and electronic components from Chip.pk.

Explore Products