An HC-SR04 ultrasonic sensor measures distance by timing an echo: the Arduino sends a 10 µs pulse to the Trig pin, the module fires a burst of 40 kHz sound, and the Echo pin stays HIGH for as long as the sound takes to reach an object and come back. Multiply that time by the speed of sound, divide by two, and you have the distance. This tutorial covers the wiring to an Arduino Uno, two sketches (plain pulseIn() and the NewPing library), what limits the readings, and how to fix the usual 0 cm problem.
Every spec in this guide comes from the HC-SR04 datasheet or the documentation listed under Sources at the end.
How the HC-SR04 ultrasonic sensor works
The module has two round transducers. One (marked T) sends sound, the other (marked R) listens for the echo. Ultrasonic means the frequency is above what people can hear; the HC-SR04 works at 40 kHz.
One measurement follows the sequence in the datasheet’s timing diagram:
- Your Arduino holds the Trig pin HIGH for at least 10 µs.
- The module sends an 8-cycle burst of 40 kHz ultrasound.
- The Echo pin goes HIGH and stays HIGH until the reflected sound returns.
- The length of that HIGH pulse is the round-trip time of the sound.
If nothing reflects the sound, the Echo pin does not stay HIGH forever. On many modules it gives up after about 38 ms, which your code will read as an out-of-range result.
The distance formula
The datasheet gives the formula as distance = high-level time × velocity of sound / 2. The division by two is there because the pulse covers the trip to the object and back.
Sound travels at about 343 m/s in air at 20 °C (68 °F). Converted to the units the Arduino measures in, that is 0.0343 cm per microsecond, so:
distance_cm = duration_us * 0.0343 / 2
A 1,000 µs echo works out to 1000 × 0.0343 / 2 = 17.2 cm. The datasheet also gives a shortcut, µs / 58 = centimeters (or µs / 148 = inches), which is the same math rearranged: 2 / 0.0343 ≈ 58.3 µs per centimeter.
HC-SR04 specifications
| Parameter | Value (datasheet) |
|---|---|
| Working voltage | 5 V DC |
| Working current | 15 mA |
| Ultrasonic frequency | 40 kHz |
| Range | 2 cm to 400 cm (about 0.8 in to 13 ft) |
| Ranging accuracy | up to 3 mm |
| Measuring angle | 15° |
| Trigger input | 10 µs TTL pulse |
| Suggested measurement cycle | over 60 ms |
| Dimensions | 45 × 20 × 15 mm |
HC-SR04 pinout
The four pins are labeled on the front of the board, left to right:
- VCC: 5 V supply.
- Trig: trigger input. A HIGH pulse of at least 10 µs starts a measurement.
- Echo: echo output. Goes HIGH for the round-trip time of the sound. On a 5 V supply this is a 5 V signal, which matters for 3.3 V boards (see below).
- GND: ground, shared with the Arduino.
Wiring the ultrasonic sensor to an Arduino Uno
The Uno uses 5 V logic, the same as the sensor, so all four wires go straight to the board with no extra parts. Pins 9 and 10 are used here; any two digital pins work if you change the numbers in the code.
| HC-SR04 pin | Arduino Uno pin | Notes |
|---|---|---|
| VCC | 5V | Do not use the 3.3V pin with a standard HC-SR04 |
| Trig | D9 | Set as OUTPUT |
| Echo | D10 | Set as INPUT |
| GND | GND | Common ground |
Mount the sensor so both transducers face the target with nothing in front of them. A breadboard edge or a wire bundle sitting inside the beam will return its own echo.
Basic Arduino code with pulseIn()
This sketch needs no library. It triggers the sensor, measures the echo with pulseIn(), converts it to centimeters, and prints the result to the Serial Monitor.
// HC-SR04 ultrasonic sensor with Arduino Uno - no library
const int trigPin = 9;
const int echoPin = 10;
// 30,000 us is enough time for an echo from roughly 5 m,
// beyond the sensor's 4 m rated range
const unsigned long ECHO_TIMEOUT_US = 30000UL;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, LOW);
}
void loop() {
// Make sure Trig starts LOW, then send a 10 us HIGH pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Length of the HIGH pulse on Echo, in microseconds (0 = timeout)
unsigned long duration = pulseIn(echoPin, HIGH, ECHO_TIMEOUT_US);
if (duration == 0) {
Serial.println("Out of range");
} else {
float distanceCm = duration * 0.0343 / 2.0;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
}
delay(100); // datasheet suggests a measurement cycle over 60 ms
}
How the code works
The trigger pulse. Pulling Trig LOW for 2 µs first gives a clean edge; the 10 µs HIGH that follows is the minimum trigger length from the datasheet.
pulseIn() and its timeout. According to the Arduino reference, pulseIn(pin, HIGH) waits for the pin to go HIGH, starts timing, waits for it to go LOW again, and returns the pulse length in microseconds. It returns 0 if no complete pulse arrives before the timeout. The default timeout is one second, which would freeze your loop for a full second every time nothing is in range. Passing 30,000 µs as the third argument keeps the wait short. That value is not arbitrary: at 0.0343 cm/µs, a 400 cm target produces an echo of about 23,300 µs, so 30,000 µs leaves margin above the rated range.
The math. duration * 0.0343 / 2.0 is the datasheet formula with the speed of sound at 20 °C. Using 2.0 and a float keeps the decimal places; integer math would round every reading down to whole centimeters.
The delay between readings. The datasheet recommends a measurement cycle of more than 60 ms so the next trigger doesn’t collide with a late echo from the previous one. delay(100) covers that. If your project has other work to do between readings, such as driving motors, use a millis() timer instead of delay(); our guide on why delay() blocks your Arduino and how to use millis() shows the pattern.
Arduino code with the NewPing library
NewPing, by Tim Eckel, wraps the trigger, timing and conversion into one call. Install it from the Arduino IDE: open the Library Manager, search for “newping”, and install the library by Tim Eckel.
// HC-SR04 with the NewPing library
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // cm; NewPing's default is 500
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned int cm = sonar.ping_cm(); // whole cm, 0 = no echo within MAX_DISTANCE
Serial.print("Distance: ");
Serial.print(cm);
Serial.println(" cm");
delay(100);
}
Things to know about NewPing:
ping_cm()returns whole centimeters and returns 0 when no echo comes back within the maximum distance. Treat 0 as “nothing detected”, not as “touching the sensor”.ping_in()returns inches instead.ping()returns the raw echo time in microseconds, sosonar.ping() * 0.0343 / 2gives you decimals.ping_median(iterations)takes several readings (5 by default), discards out-of-range ones and returns a single combined echo time in microseconds. Convert it the same way:sonar.ping_median(5) * 0.0343 / 2. This is the simplest way to steady a noisy reading.
Use the plain pulseIn() sketch when you want to see exactly what the sensor does, and NewPing when you’d rather not repeat the timing code in every project.
Reading the Serial Monitor output
Open Tools > Serial Monitor and set the baud rate to 9600 to match Serial.begin(9600). A mismatched baud rate shows garbled characters, not numbers.
With the first sketch you’ll see a new line roughly every 100 ms in the form Distance: 17.15 cm. Move your hand toward and away from the sensor and the number should follow. “Out of range” means pulseIn() hit its timeout: nothing was close enough, or the echo was lost (see the next section). The Serial Plotter (Tools > Serial Plotter) can graph the values if you print only the number on each line.
Accuracy and limits of the HC-SR04
The datasheet’s 3 mm accuracy figure describes good conditions: a flat, hard target facing the sensor head-on. Several things pull real readings away from that.
Target surface and size
Soft materials such as fabric, foam, fur and cushions absorb sound, so the echo is weak or missing. Small or thin objects like a pencil or a chair leg reflect very little. A sensor mounted close to the floor can pick up a reflection from the floor itself instead of the object you care about.
Angle
The datasheet gives a 15° measuring angle. A smooth surface tilted away from the sensor reflects sound the way a mirror reflects light, so the echo goes elsewhere. You may then get no reading, or a long reading from some other object the sound eventually bounced off. Point the sensor square to the surface you’re measuring.
Minimum distance
Below about 2 cm the module can’t separate the returning echo from its own outgoing burst. Readings under 2 cm aren’t meaningful.
Temperature
The 0.0343 cm/µs constant assumes air at 20 °C. The speed of sound in air is approximately 331.3 + 0.606 × T m/s, with T in °C: about 325 m/s at −10 °C and 352 m/s at 35 °C. Keeping 343 m/s in your code causes an error of about 0.18% per °C away from 20 °C. At 35 °C that is roughly 2.7%, or about 5 cm on a 2 m reading. For outdoor or unheated builds, read a temperature sensor and calculate the speed of sound in code:
float tempC = 25.0; // replace with a reading from your temperature sensor
float soundCmPerUs = (331.3 + 0.606 * tempC) / 10000.0; // m/s to cm/us
float distanceCm = duration * soundCmPerUs / 2.0;
Multiple sensors
Two HC-SR04 modules facing the same space can hear each other’s bursts. Trigger them one at a time, and leave the 60 ms measurement cycle the datasheet suggests between pings.
Troubleshooting: 0 cm, out of range, or stuck readings
| Symptom | Likely cause | Fix |
|---|---|---|
| Always 0 cm or “Out of range” | Trig and Echo swapped, or wired to different pins than the code uses | Check the wiring table against the pin numbers in the sketch |
| Always 0 cm with NewPing | Nothing within MAX_DISTANCE, which the library reports as 0 | Test against a wall 30 to 100 cm away; raise MAX_DISTANCE if needed |
Always 0 with pulseIn() | Timeout too short, or no echo pulse at all | Use a timeout of at least 25,000 µs; confirm VCC is on 5V, not 3.3V |
| Reading jumps to the maximum, or a value far larger than expected | Echo lost on a soft or angled surface; the sound bounced off something farther away | Aim square at a hard surface; filter with ping_median() or ignore single outliers |
| Erratic values | Triggering faster than the 60 ms cycle, or a loose jumper | Increase the delay between readings; reseat the wires |
| Garbled text in the Serial Monitor | Baud rate mismatch | Set the monitor to the same rate as Serial.begin() |
A quick hardware check: point the sensor at a wall about 50 cm away and run the first sketch. If you get a stable number near 50 cm, the module and wiring work, and any remaining problem is with the target or the code.
Using the HC-SR04 with 3.3 V boards (ESP32 and others)
The standard HC-SR04 needs a 5 V supply and does not run reliably at 3.3 V. On a 5 V supply its Echo output is also 5 V. ESP32 GPIO pins are 3.3 V pins and are not 5 V tolerant, so connecting Echo directly can damage the pin.
The fix is a two-resistor voltage divider on the Echo line:
- Power the sensor from the board’s 5V or VIN pin (USB 5 V).
- Connect Echo to a 1 kΩ resistor, and the other end of that resistor to the ESP32 input pin.
- Connect a 2 kΩ resistor from that same ESP32 pin to GND.
- The pin then sees 5 V × 2 / (1 + 2) ≈ 3.3 V. A 10 kΩ / 20 kΩ pair gives the same ratio.
The Trig line needs no change: a 3.3 V output from the ESP32 is high enough to trigger the module.
Some modules sold as HC-SR04P, and the RCWL-1601, run on 3.0 to 5.5 V with an Echo level equal to the supply. Powered from 3.3 V they need no divider. Check the markings on your board, because some sellers label the 5 V version as “HC-SR04P”.
On the ESP32 (Arduino core) the pulseIn() sketch above works with only the pin numbers changed; Random Nerd Tutorials uses GPIO 5 for Trig, GPIO 18 for Echo and a baud rate of 115200.
Project ideas using an ultrasonic sensor
Once the sensor reads reliably, these builds on emergingtechs.org use it or the same skills:
- Obstacle avoidance robot. The classic HC-SR04 project: drive forward until the distance drops below a threshold, then turn. See our Arduino obstacle avoidance robot using ultrasonic sensors and the step-by-step guide to building an obstacle avoidance robot with Arduino.
- Parking or proximity indicator. Convert distance into LED brightness, a buzzer rate or a bar graph. The Arduino map() function turns a range like 5 to 100 cm into 0 to 255 for
analogWrite(). - Distance display. Print the reading on a 16×2 screen instead of the Serial Monitor, following our Arduino LCD display tutorial.
- Tank or bin level sensor. Mount the sensor above the contents, pointing down; the fill level is the mounting height minus the reading. Keep the sensor itself dry; waterproof variants exist for wet locations.
For more student-level builds that combine sensors and microcontrollers, browse our list of engineering projects for students.
FAQ
What is the range of the HC-SR04 ultrasonic sensor?
The datasheet rates it from 2 cm to 400 cm (about 13 ft), with ranging accuracy up to 3 mm and a 15° measuring angle. Real-world range is shorter for soft, small or angled targets.
Why is my ultrasonic sensor reading 0?
A 0 almost always means no echo was measured. With pulseIn() that is a timeout; with NewPing it means nothing was detected within MAX_DISTANCE. Check that Trig and Echo match the pins in your code, that VCC is on 5V, and test against a hard wall within a meter.
Can I connect the HC-SR04 to 3.3 V?
Not the standard version, which needs 5 V. On a 3.3 V board, power it from 5 V and put a 1 kΩ / 2 kΩ voltage divider on the Echo pin. Variants such as the HC-SR04P and RCWL-1601 are designed to run on 3.3 V.
Do I need a library for the ultrasonic sensor?
No. pulseIn() is part of the Arduino core and the basic sketch above uses nothing else. NewPing is optional; it shortens the code and adds a median filter.
Sources
Checked 2026-11-25.
- HC-SR04 ultrasonic ranging module datasheet (SparkFun copy): 5 V, 15 mA, 40 kHz, 2 to 400 cm, 3 mm accuracy, 15° angle, 10 µs trigger, 8-cycle burst, distance formula, µs/58 shortcut, 60 ms cycle, dimensions.
- Arduino reference: pulseIn(): behavior, return value in microseconds, 0 on timeout, default one-second timeout.
- UMass Amherst Physical Computing Makerspace: Ultrasonic Distance Sensor: 343 m/s at 20 °C (0.0343 cm/µs), temperature formula and 0.18%/°C error, 38 ms no-echo timeout, surface and angle limits, 2 cm minimum, ESP32 voltage divider, 3.3 V trigger, HC-SR04P and RCWL-1601 variants, waterproof variants.
- Random Nerd Tutorials: ESP32 with HC-SR04: speed of sound at 20 °C, pinout, ESP32 pins and baud rate.
- Last Minute Engineers: HC-SR04 with Arduino: NewPing installation,
ping_cm(),ping_in(),ping_median()(default 5 readings), 500 cm default maximum, floor reflections and small or soft targets.