What is the HC-SR04?
The HC-SR04 ultrasonic sensor measures distance by sending a short burst of 40 kHz sound and timing the echo reflected from an object. The common module is specified for a nominal 2 cm to 400 cm range and uses four connections: VCC, TRIG, ECHO and GND.
To measure distance, a microcontroller holds TRIG HIGH for at least 10 µs, then measures how long ECHO remains HIGH. That pulse is the sound's round-trip travel time, so the one-way distance is calculated as speed of sound × time ÷ 2. Near 20 °C, a useful shortcut is distance in cm ≈ Echo time in µs ÷ 58.
One electrical detail matters: the classic HC-SR04 is powered from 5 V and its ECHO output is typically 5 V. An Arduino Uno can read it directly; an ESP32, ESP8266 or Raspberry Pi needs a suitable voltage divider or level shifter on ECHO. Use the Arduino Uno wiring and code guide or the ESP32 guide with a protected ECHO input to build it safely.
Specifications
- Operating voltage
- 5 V DC (3.3 V variants exist, see below)
- Working current
- 15 mA
- Ultrasonic frequency
- 40 kHz
- Range
- 2 cm to 400 cm
- Ranging accuracy
- up to 3 mm (best case)
- Measuring angle
- 15°
- Trigger input
- 10 µs TTL pulse
- Echo output
- TTL pulse, width proportional to distance
- Echo logic level
- 5 V (on the classic module)
- Minimum cycle
- above 60 ms between measurements
- Distance formula
- echo µs ÷ 58 = cm
- Board size
- 45 × 20 × 15 mm
- Header
- 4 pins, 2.54 mm pitch
Figures follow the HC-SR04 datasheet (ElecFreaks, as reproduced by SparkFun). Real-world accuracy depends on the target, angle and temperature, and cheap clones vary. The datasheet's 3 mm accuracy is a best case on a flat hard target.
Pinout
| Pin | Name | Description |
|---|---|---|
| 1 | VCC | 5 V supply. Needs a real 5 V rail, not a 3.3 V pin, to reach rated range. |
| 2 | Trig | Trigger input. Hold HIGH for at least 10 µs to start one measurement. A 3.3 V logic HIGH is accepted. |
| 3 | Echo | Output. Goes HIGH when the burst is sent and LOW when the echo returns. HIGH time = round trip. Swings to 5 V. |
| 4 | GND | Ground. Must be shared with your microcontroller. |
Pin order is printed on the board: VCC, Trig, Echo, GND.
Wiring & code
Setting up HC-SR04 with Arduino Uno
Library
None — uses built-in pulseIn() by Arduino core
None required. The basic sketch uses only functions built into Arduino. Optional: NewPing by Tim Eckel (install from Library Manager) for median filtering.
This HC-SR04 with Arduino Uno tutorial takes you from the four-wire circuit to a working distance meter in the Serial Monitor. The classic HC-SR04 uses a 5 V supply and a 5 V ECHO output, which is compatible with the Uno's 5 V input. You do not need a resistor divider for this Uno connection.
You will connect TRIG to D9 and ECHO to D10, upload a no-library sketch with an explicit pulse timeout, then extend the build into a parking-distance alert and a touch-free dustbin lid. Start with the HC-SR04 sensor overview if you want the operating principle and measurement limits first.
At a glance
- Time
- About 15 minutes
- Skill level
- Complete beginner
- Extra parts
- None for the basic build
- You will learn
- Wiring, uploading code, reading the Serial Monitor, how time becomes distance
What you need
Everything in the first table is required. The second table is only for the two projects at the end.
Required parts
Arduino Uno (or compatible)
- Qty
- 1
- Notes
- Any Uno, clone or Nano-class board works. This guide uses Uno pin names.
USB cable
- Qty
- 1
- Notes
- The one that fits your board (usually USB-B for a genuine Uno).
HC-SR04 ultrasonic sensor
- Qty
- 1
- Notes
- Four pins: VCC, Trig, Echo, GND.
Breadboard
- Qty
- 1
- Notes
- Half-size is plenty.
Jumper wires, male to male
- Qty
- 4
- Notes
- Different colours help: red, black, plus two others.
A computer with the Arduino IDE
- Qty
- 1
- Notes
- Free from arduino.cc. We install it in Step 2.
If your jumper wires are male to female, you can skip the breadboard and plug the female ends straight onto the sensor pins.
Optional parts for the projects
| Part | Qty | Used in |
|---|---|---|
| Active buzzer | 1 | Project 1: parking sensor |
| LED (any colour) | 1 | Project 1 |
| 220 Ω resistor | 1 | Project 1 (protects the LED) |
| SG90 micro servo | 1 | Project 2: dustbin lid |
Step 1. Wire it up
Unplug the USB cable first. Connecting wires to a powered board is how short circuits happen, so make wiring a habit you do with the power off.
You are making four connections. Two carry power, one tells the sensor to measure, and one brings the answer back:
- 5V to VCC gives the sensor power.
- GND to GND completes the circuit. Both devices must share a ground or nothing works.
- D9 to Trig. The Uno shouts "measure now" on this wire.
- D10 to Echo. The sensor answers on this wire, and the Uno times the answer.
Here is the same circuit wired in the SolderHub Simulator. Open it from the simulator card further down to run it:
Wiring: HC-SR04 to Arduino Uno
| Component pin | Arduino Uno pin | Note |
|---|---|---|
| VCC | 5V | Red wire. Power for the sensor. |
| Trig | D9 | Blue wire. Uno to sensor: start a measurement. |
| Echo | D10 | Green wire. Sensor to Uno: the timing pulse. The Uno is a 5 V board, so this is safe to connect directly. |
| GND | GND | Black wire. Common ground. |
- 1Push the HC-SR04 into the breadboard so its four pins land in four different rows (the metal cans face away from the board).
- 2Red wire: from the Uno's 5V pin to the row of the sensor pin labelled VCC.
- 3Black wire: from a Uno GND pin to the row of the sensor pin labelled GND.
- 4Blue wire: from Uno pin 9 to the row of the sensor pin labelled Trig.
- 5Green wire: from Uno pin 10 to the row of the sensor pin labelled Echo.
Check before plugging in. Trace each wire with your finger: red goes to VCC, black to GND. Swapping those two can damage the sensor. Trig and Echo are harmless if swapped, but nothing will read.
Step 2. Set up the Arduino IDE
If you already upload sketches to your Uno, skip to Step 3.
- Download and install the Arduino IDE from arduino.cc.
- Plug the Uno into your computer with the USB cable. The small green power light on the board should come on.
- Open the IDE. Click Tools > Board and choose Arduino Uno.
- Click Tools > Port and choose the port that appeared when you plugged in the board. On Windows it looks like
COM3, on Mac/dev/cu.usbmodem..., on Linux/dev/ttyACM0.
Step 3. Upload your first sketch
A sketch is an Arduino program. Copy this one into a new IDE window, replacing everything in it. It uses no library, only functions every Arduino already has.
// HC-SR04 distance meter - Arduino Uno
const int TRIG_PIN = 9; // Uno pin D9 -> sensor Trig
const int ECHO_PIN = 10; // Uno pin D10 <- sensor Echo
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW); // start with Trig LOW
}
void loop() {
// 1. Send a 10 microsecond pulse on Trig
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// 2. Measure how long Echo stays HIGH (in microseconds).
// 30000 us = give up after 30 ms if no echo comes back.
unsigned long echoTime = pulseIn(ECHO_PIN, HIGH, 30000UL);
// 3. Turn time into distance
if (echoTime == 0) {
Serial.println("No echo - nothing in range?");
} else {
float distanceCm = echoTime / 58.0;
Serial.print("Distance: ");
Serial.print(distanceCm, 1);
Serial.println(" cm");
}
delay(500); // read twice per second
}- 1Click the Upload button (the right arrow at the top left). Wait for "Done uploading".
- 2Click Tools > Serial Monitor.
- 3At the bottom right of the Serial Monitor, set the speed to 9600 baud. If this does not match the code, you will see random symbols.
- 4Hold your hand about 20 cm in front of the sensor, then slowly move it closer and farther.
You should see numbers like these, changing as your hand moves:
Distance: 21.3 cm
Distance: 20.8 cm
Distance: 14.2 cm
Distance: 9.7 cm
Distance: 5.1 cm
No echo - nothing in range?Seeing numbers? Congratulations, it works. If not, jump to Troubleshooting.
How the sketch works, line by line
You do not need to memorise this, but understanding it turns copy-pasting into building.
The sketch explained
- const int TRIG_PIN = 9;
- Gives the pin number a name so the code is readable. The sensor's Trig wire is on pin 9.
- pinMode(TRIG_PIN, OUTPUT);
- Trig is a pin the Uno writes to, so it is an OUTPUT.
- pinMode(ECHO_PIN, INPUT);
- Echo is a pin the Uno listens to, so it is an INPUT.
- digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
- Raises Trig for 10 microseconds. That is the "measure now" signal.
- pulseIn(ECHO_PIN, HIGH, 30000UL);
- Waits for Echo to go HIGH, times how long it stays HIGH, and returns that time in microseconds. If nothing returns within 30,000 µs it gives up and returns 0.
- echoTime / 58.0
- Converts time into centimetres. Sound covers about 1 cm in 29 µs, and the pulse measures out and back, so 58 µs per centimetre of distance.
- if (echoTime == 0)
- Zero means no echo came back: nothing in front, too far, or the surface is soft or angled.
- delay(500);
- Waits half a second. The sensor needs more than 60 ms between measurements, so never go faster than that.
Why 58? Speed of sound is about 0.0343 cm per microsecond. Distance = 0.0343 × time ÷ 2, which is time ÷ 58.
Try this circuit in the SolderHub Simulator
Run this exact circuit in your browserReady-wired, code loadedConfirm simulator behavior against the real wiring and the sensor datasheet before connecting hardware.
Experiments: learn what the sensor can and cannot do
Spend five minutes breaking it on purpose. You will avoid hours of confusion later.
Try this
Point it at a wall from 30 cm
- What you should see
- A steady number near 30
- Why
- Flat, hard and square-on: the ideal target.
Tilt a book at 45° in front of it
- What you should see
- Jumpy numbers or No echo
- Why
- The sound bounces off at an angle and never returns.
Hold a pillow or jacket in front
- What you should see
- Weak or missing readings
- Why
- Soft things absorb ultrasound.
Move your hand closer than 2 cm
- What you should see
- Nonsense or No echo
- Why
- Too close: the echo returns before the sensor is ready to listen.
Point it at the ceiling
- What you should see
- No echo, or a distant number
- Why
- Nothing within range reflects the sound back.
Make it accurate: calibrate with a tape measure
Cheap sensors are rarely wrong by much, but a two-minute check makes you certain.
- Place the sensor 50 cm from a flat wall, measured with a tape from the front of the sensor's cans.
- Read the number on the Serial Monitor. Say it shows 51.2 cm.
- The difference (-1.2 cm) is your offset. Change the line to
float distanceCm = echoTime / 58.0 - 1.2;.
Warm rooms read slightly short and cold rooms slightly long because sound speed changes with temperature. For most projects ignore this. The overview explains how to correct for it.
Easier and steadier: the NewPing library
The plain sketch is perfect for learning. For projects, many people use NewPing by Tim Eckel. It hides the timing code, handles timeouts, and can take several readings and keep the middle one, which removes random spikes.
- 1In the Arduino IDE, click the Library Manager icon on the left (the stack of books).
- 2Type NewPing in the search box.
- 3Find NewPing by Tim Eckel and click Install.
- 4Upload the sketch below. Your wiring does not change.
#include <NewPing.h>
#define TRIG_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // cm, the sensor's limit
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600);
}
void loop() {
// Take 5 readings and keep the middle one: ignores one-off spikes
unsigned int echoTime = sonar.ping_median(5);
unsigned int cm = sonar.convert_cm(echoTime);
if (cm == 0) {
Serial.println("No echo - nothing in range?");
} else {
Serial.print("Distance: ");
Serial.print(cm);
Serial.println(" cm");
}
delay(300);
}sonar.ping_median(5) takes five measurements and returns the middle one, so a single bad reading cannot fool you. sonar.convert_cm() turns microseconds into centimetres and returns 0 when there was no echo.
Project 1. Parking sensor
Beeps faster as an object gets closer, like a car's reversing sensor. Add a buzzer and an LED to the circuit you already built.
Extra wiring for Project 1
- Active buzzer + leg
- Uno D8
- Active buzzer - leg
- GND
- LED long leg (+) through 220 Ω resistor
- Uno D7
- LED short leg (-)
- GND
The sensor stays on 5V, D9, D10 and GND exactly as before. An active buzzer has a + mark and makes sound when given power.
// Parking sensor: the closer the object, the faster the beeping.
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int BUZZER_PIN = 8; // active buzzer, + leg to D8
const int LED_PIN = 7; // LED + 220 ohm resistor to D7
float readCm() {
digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long t = pulseIn(ECHO_PIN, HIGH, 30000UL);
return t == 0 ? -1.0 : t / 58.0;
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
float cm = readCm();
if (cm < 0 || cm > 100) { // nothing close: stay quiet
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
delay(100);
return;
}
// 100 cm -> 600 ms gap between beeps, 5 cm -> 50 ms (almost continuous)
int gap = map((long)cm, 5, 100, 50, 600);
gap = constrain(gap, 50, 600);
digitalWrite(BUZZER_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
delay(40);
digitalWrite(BUZZER_PIN, LOW);
digitalWrite(LED_PIN, LOW);
delay(gap);
}Nothing happens beyond 100 cm. Closer than that the buzzer beeps, and the gap between beeps shrinks from about 0.6 seconds at 100 cm down to 0.05 seconds at 5 cm, which sounds almost continuous. The map() line is where distance becomes beep speed. Change 100 and 600 to tune it for your room.
Project 2. Touch-free dustbin lid
Wave a hand or drop rubbish within 20 cm and a servo opens the lid for three seconds, then closes it.
Extra wiring for Project 2
- Brown or black (ground)
- GND
- Red (power)
- 5V
- Orange or yellow (signal)
- Uno D6
Small SG90 servos can run from the Uno's 5V for a demo. If the servo jitters or the Uno resets, power the servo from a separate 5 V supply and join its ground to the Uno's GND.
// Touch-free dustbin lid: opens when something is within 20 cm.
#include <Servo.h>
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int SERVO_PIN = 6;
const float OPEN_BELOW_CM = 20.0;
const unsigned long STAY_OPEN_MS = 3000;
Servo lid;
unsigned long closeAt = 0;
float readCm() {
digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long t = pulseIn(ECHO_PIN, HIGH, 30000UL);
return t == 0 ? -1.0 : t / 58.0;
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
lid.attach(SERVO_PIN);
lid.write(0); // lid closed
}
void loop() {
float cm = readCm();
if (cm > 0 && cm < OPEN_BELOW_CM) { // hand or object detected
lid.write(90); // open
closeAt = millis() + STAY_OPEN_MS; // restart the 3 second timer
}
if (closeAt != 0 && millis() > closeAt) {
lid.write(0); // close
closeAt = 0;
}
delay(60); // keep 60 ms between readings
}The sketch never freezes while the lid is open: it records when to close (closeAt) and keeps measuring, instead of using a long delay(). Using millis() this way is how real projects stay responsive. The delay(60) at the end respects the sensor's minimum 60 ms between measurements.
Troubleshooting
Fix it fast
Always "No echo"
- Most likely cause
- Trig and Echo wires on the wrong pins, or VCC not on 5V
- Fix
- Compare wires to the wiring table. Make sure the red wire is on 5V, not 3.3V.
Random symbols in Serial Monitor
- Most likely cause
- Baud rate mismatch
- Fix
- Set the Serial Monitor to 9600 baud.
Port is greyed out or missing
- Most likely cause
- Cable is charge-only or driver missing
- Fix
- Try another USB cable. Clone boards may need a CH340 driver.
Number stuck on a small value
- Most likely cause
- Something is in front of the sensor
- Fix
- Check wires, the breadboard edge or a table lip in front of the cans.
Numbers jump around
- Most likely cause
- Soft or angled target, or electrical noise
- Fix
- Aim at a flat surface, use the NewPing median sketch, add a 100 µF capacitor across VCC and GND.
Values are 3 to 5 cm off
- Most likely cause
- Cheap module tolerance or temperature
- Fix
- Calibrate with a tape measure.
Upload fails: avrdude error
- Most likely cause
- Wrong Board or Port selected
- Fix
- Re-check Tools > Board and Tools > Port.
Where to go next
You have a working distance sensor. Good next steps:
- Read the HC-SR04 overview to understand range, angle and temperature in depth.
- Build the same circuit on an ESP32 and put the reading on a web page.
- Compare with a laser sensor, the VL53L0X, when you need millimetre accuracy.
References
- HC-SR04 datasheet (PDF) — module timing and recommended measurement interval.
- Arduino pulseIn() reference — pulse timing and timeout behavior.









