Arduino HC-SR04 Ultrasonic Sensor Tutorial. Measure Distance with Code & Wiring Diagram
Arduino HC-SR04 Ultrasonic Sensor Tutorial: Measure Distance with Code & Wiring Diagram
Meta description: Learn how to wire and program an HC-SR04 ultrasonic sensor with Arduino to measure distance in centimeters and inches — full code and troubleshooting included.
Introduction
The HC-SR04 ultrasonic sensor is one of the most widely used components in beginner Arduino projects. It measures distance by sending out a sound wave and timing how long it takes to bounce back — the same basic principle used by bats and sonar.
In this tutorial, you'll learn how to wire the HC-SR04 to an Arduino, program it to measure distance, and display accurate readings in both centimeters and inches using the Serial Monitor.
What This Project Does
You'll build a simple distance-measuring circuit where the Arduino triggers the HC-SR04 to send an ultrasonic pulse, measures the time it takes for the echo to return, and calculates the distance to the nearest object.
The calculated distance is displayed live in both centimeters and inches through the Arduino Serial Monitor.
Required Components
- Arduino Uno (or compatible board)
- HC-SR04 ultrasonic sensor
- Breadboard
- Jumper wires
- USB cable
Features
- Real-time distance measurement in centimeters and inches
- Simple 4-pin wiring with no extra components required
- Uses built-in Arduino functions with no additional libraries
- Provides a foundation for robotics, obstacle-avoidance, and parking-sensor style projects
How It Works
The HC-SR04 has two important signal pins: TRIG (trigger) and ECHO. The Arduino sends a short electrical pulse to the TRIG pin, causing the sensor to emit an ultrasonic sound wave.
When the sound wave hits an object and returns to the sensor, the HC-SR04 sets the ECHO pin HIGH for a duration proportional to the time the sound wave took to travel to the object and back.
The Arduino measures this duration and uses the speed of sound to calculate the distance to the object.
Wiring / Circuit Information
Connect the HC-SR04 ultrasonic sensor to the Arduino Uno as follows:
| HC-SR04 Pin | Arduino Pin |
|---|---|
| VCC | 5V |
| TRIG | Pin 9 |
| ECHO | Pin 10 |
| GND | GND |
The HC-SR04 typically operates at 5V logic and works well with an Arduino Uno's 5V-tolerant digital pins.
If you use the HC-SR04 with an ESP32 instead, do not connect the ECHO pin directly to an ESP32 GPIO. The ESP32 GPIO pins are not 5V tolerant, so a voltage divider should be used on the ECHO line to reduce the voltage to a safe level.
Step-by-Step Instructions
- Wire the circuit according to the wiring table above.
- Open the Arduino IDE and connect your Arduino board to your computer using the USB cable.
- Select your board and port under the Tools menu in the Arduino IDE.
- Upload the code below. No additional libraries are required because the sketch uses built-in Arduino functions.
- Open the Serial Monitor and set the baud rate to 9600 to view the live distance measurements.
Complete Code
#define TRIG_PIN 9
#define ECHO_PIN 10
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Send a 10-microsecond pulse to trigger the sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in centimeters
// Speed of sound = 0.0343 cm/microsecond
float distanceCm = (duration * 0.0343) / 2;
// Convert centimeters to inches
float distanceIn = distanceCm / 2.54;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.print(" cm | ");
Serial.print(distanceIn);
Serial.println(" in");
delay(500);
}
Explanation of Important Code Sections
-
digitalWrite(TRIG_PIN, HIGH)with a 10-microsecond delay — sends the trigger pulse required to start an HC-SR04 distance measurement. -
pulseIn(ECHO_PIN, HIGH)— measures how long the ECHO pin stays HIGH. The returned value represents the round-trip travel time of the ultrasonic sound wave in microseconds. -
distanceCm = (duration * 0.0343) / 2— uses the approximate speed of sound of 0.0343 cm per microsecond. The result is divided by 2 because the measured time includes the journey to the object and back. -
distanceIn = distanceCm / 2.54— converts the calculated distance from centimeters into inches. -
delay(500)— waits half a second between measurements, limiting the output to approximately two readings per second.
Testing
Open the Serial Monitor and set the baud rate to 9600. Place your hand or another object in front of the HC-SR04 sensor.
Move the object closer and farther away and watch the distance values change in the Serial Monitor. The measurements should be displayed in both centimeters and inches.
At very close distances, roughly below 2cm, or at distances beyond roughly 400cm, readings can become unreliable. These limitations are related to the operating range of the HC-SR04 rather than a problem with the code.
Troubleshooting
Readings show 0 or stay constant:
- Double-check that TRIG and ECHO aren't swapped. This is one of the most common wiring mistakes.
- Confirm that the HC-SR04 is receiving 5V through its VCC pin.
- Make sure GND is connected correctly between the sensor and Arduino.
Erratic or jumping readings:
- Soft or angled surfaces can scatter the ultrasonic wave. Test the sensor against a flat, hard surface first.
- Make sure there aren't multiple ultrasonic sensors operating very close together, as they can interfere with each other.
- Keep the sensor positioned directly toward the object for more consistent measurements.
No output at all in the Serial Monitor:
-
Confirm the Serial Monitor baud rate is set to
9600, matchingSerial.begin(9600)in the code. - Make sure the correct Arduino board and COM port are selected in the Arduino IDE.
Common Problems and Solutions
| Problem | Likely Cause | Solution |
|---|---|---|
| Reading stuck at 0 | TRIG/ECHO wired backwards | Swap the two signal connections and test again. |
| Inconsistent readings on soft surfaces | Sound wave scattering | Test against a hard, flat surface. This is a normal limitation of ultrasonic distance sensing. |
| No reading beyond ~4m | Sensor's maximum range | This is expected behavior. The HC-SR04 is generally rated for a maximum range of roughly 400cm. |
Improvements / Upgrades
Once your basic HC-SR04 distance sensor is working, you can use it as the foundation for more advanced Arduino projects.
- Add a buzzer or LED that activates when an object gets within a defined distance.
- Mount the HC-SR04 on a servo motor and sweep it from side to side to create a simple radar-style scanner.
- Combine the sensor with motor control to build an obstacle-avoiding robot.
- Average multiple distance readings to reduce measurement noise and create smoother results.
Frequently Asked Questions
Under good conditions, the HC-SR04 can typically measure distance to within a few millimeters. However, accuracy can be affected by soft, angled, or irregular surfaces that scatter the ultrasonic sound wave.
Yes, but you need to be careful with voltage levels. The HC-SR04 typically operates with a 5V supply and its ECHO output can reach 5V, while ESP32 GPIO pins are not 5V tolerant.
Use a simple voltage divider on the ECHO line to reduce the voltage to a safe level before connecting it to an ESP32 GPIO.
The HC-SR04 has a minimum detection range of roughly 2cm. At very short distances, the sensor needs time to transmit and receive the ultrasonic pulse, which limits how close an object can be reliably detected.
Conclusion
You now have a working distance-measuring circuit using an HC-SR04 ultrasonic sensor and Arduino. The project measures the distance to an object and displays the result in both centimeters and inches through the Serial Monitor.
The HC-SR04 is a useful building block for robotics, automation, proximity detection, and safety projects. Once you understand the basic distance measurement, you can combine the sensor with LEDs, buzzers, servo motors, or DC motors to create more advanced projects.
From here, a natural next step is building an obstacle-avoiding robot or an automated parking sensor using the same distance-measurement technique.
Comments
Post a Comment