/ HC-SR04 Distance Sensor Guide
← All Guides Shop ↗
🌐 Translate:
⏱ 20 min 🔌 4 wires ✅ Beginner

HC-SR04 Ultrasonic
Distance Sensor Guide

Measure distance from 2cm to 400cm using sound waves — no contact needed. Used in obstacle detection, parking sensors, liquid level monitoring, and robotics.

ℹ️
Note: This guide covers the HC-SR04 ultrasonic distance sensor. If your module is labelled "HC-SC04", that's likely a printing variation — the module is the same and these instructions apply identically.
📺

Video walkthrough

Prefer to watch? These cover the same steps.

HC-SR04 Ultrasonic Sensor with Arduino
DroneBot Workshop · YouTube
▶ YouTube
Measure Distance with Arduino — Full Tutorial
Paul McWhorter · YouTube
▶ YouTube

Community videos. Tishvi is not affiliated with creators.

1

How the HC-SR04 Works

Understanding the physics makes the code make sense.

The HC-SR04 works like a bat's echolocation — or like a parking sensor. It sends out an ultrasonic pulse (40kHz, inaudible) and waits for the echo to bounce back off an object. By timing how long this takes, it calculates distance.

TRIG 10µs trigger ECHO Echo pulse width → distance HIGH while waiting for echo Distance (cm) = duration / 58
📡
Range
2cm – 400cm
±3mm accuracy
Voltage
5V DC
Draws only 15mA
📐
Beam Angle
15° cone
Aim directly at target
🔌
Pins
VCC, Trig, Echo, GND
4 pins total
2

What You Need

No soldering needed — just jumper wires.

Tishvi Arduino UNO R3

Any variant (DIP or SMD). Must have Arduino IDE installed. See the UNO R3 Setup Guide first if needed.

HC-SR04 (or HC-SC04) Module

The white plastic module with two silver cylinders (the transducers — one sends, one receives). Has 4 header pins labelled VCC, Trig, Echo, GND.

4× Male-to-Male Jumper Wires

Or Female-to-Male if your sensor has female headers. Standard colours: red (VCC), black (GND), plus two others for Trig and Echo.

Optional: LED + 220Ω Resistor

For the proximity alert sketch in Step 6 — lights up when an object is within range. The built-in LED on pin 13 works fine if you don't have a separate one.

3

Wiring to Arduino UNO R3

4 wires. Pin 9 = Trig, Pin 10 = Echo. Both are digital I/O pins.

ARDUINO UNO R3 5V GND D9 D10 TX RX VCC GND TRG ECH VCC (Red) GND (Black) Trig (Blue) Echo (Purple) HC-SR04
HC-SR04 PinConnect to ArduinoWire ColourNotes
VCC5V■ RedMust be 5V — not 3.3V
GNDGND■ BlackAny GND pin works
TrigPin 9■ BlueSends the ultrasonic pulse (output from Arduino)
EchoPin 10■ PurpleReceives the echo timing (input to Arduino)
💡
You can use any two digital pins — not just 9 and 10. Just update the trigPin and echoPin constants in the code to match your wiring.
⚠️
5V only. The HC-SR04 Echo pin outputs 5V — which the Arduino UNO handles fine. However, 3.3V boards (like Arduino Zero) need a voltage divider on the Echo line. UNO R3 users: wire directly, no divider needed.
4

Read Distance in Centimetres

Core sketch — the foundation for all HC-SR04 projects.

hcsr04_distance.ino
// HC-SR04 Ultrasonic Distance Sensor
// Tishvi Docs · Wiring: VCC→5V | GND→GND | Trig→9 | Echo→10

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

long  duration;    // echo pulse width in microseconds
float distance;    // calculated distance in centimetres

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // 1. Send a 10µs trigger pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);   // 10µs pulse
  digitalWrite(trigPin, LOW);

  // 2. Measure how long the Echo pin stays HIGH
  duration = pulseIn(echoPin, HIGH);

  // 3. Convert to centimetres
  // Speed of sound = 343 m/s = 0.0343 cm/µs
  // Distance = (duration / 2) * 0.0343  →  simplifies to duration / 58.2
  distance = duration / 58.2;

  // 4. Print to Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance, 1);   // 1 decimal place
  Serial.println(" cm");

  delay(200);  // read 5× per second
}
ℹ️
The maths: Sound travels at ~343 m/s (0.0343 cm/µs). The pulse travels to the object and back, so we halve the duration. distance = (duration / 2) × 0.0343 simplifies to duration / 58.2. For inches: use duration / 148.
5

View Output in Serial Monitor

Open the Serial Monitor to see live distance readings.

1

Upload the sketch from Step 4

Click Upload → and wait for "Done uploading."

2

Open Serial Monitor

Click the magnifying glass icon in the top-right of Arduino IDE, or press Ctrl+Shift+M (Win/Linux) / Cmd+Shift+M (Mac).

3

Set baud rate to 9600

In the bottom-right dropdown of Serial Monitor, select 9600 baud. This must match Serial.begin(9600) in the sketch.

4

Watch the readings

You'll see "Distance: 24.3 cm" updating 5 times per second. Move your hand towards/away from the sensor to see it change.

Readings updating and changing as you move your hand = sensor is working correctly. Typical indoor readings fluctuate by ±0.5cm.
💡
Out-of-range readings: If you see 0 cm or very large numbers (>400), the sensor either has nothing in front of it, or the object is too close (<2cm). The HC-SR04 has a minimum range of 2cm.
6

Proximity Alert — LED Warning

Light up an LED when something gets within 20cm. A basic obstacle detector.

hcsr04_proximity_alert.ino
// HC-SR04 Proximity Alert
// LED on pin 13 (built-in) lights when object < 20cm

const int trigPin     = 9;
const int echoPin     = 10;
const int ledPin      = 13;    // built-in LED
const int alertRange  = 20;   // alert if closer than 20cm

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin,  OUTPUT);
  Serial.begin(9600);
}

void loop() {
  float distance = measureDistance();

  Serial.print("Distance: ");
  Serial.print(distance, 1);
  Serial.print(" cm  →  ");

  if (distance < alertRange && distance > 2) {
    digitalWrite(ledPin, HIGH);  // LED ON
    Serial.println("⚠ TOO CLOSE!");
  } else {
    digitalWrite(ledPin, LOW);   // LED off
    Serial.println("OK");
  }

  delay(100);  // 10× per second
}

float measureDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long dur = pulseIn(echoPin, HIGH);
  return dur / 58.2;
}
💡
To change the alert range, edit the alertRange = 20 constant. Set it to 50 for a 50cm alert zone. To use an external LED, connect it to any free pin (e.g. pin 12) through a 220Ω resistor to GND, then change ledPin to 12.
7

Troubleshooting

Common problems and fixes.

?

Always reads 0 cm

Check Trig and Echo aren't swapped. Trig goes from Arduino → sensor (OUTPUT), Echo goes from sensor → Arduino (INPUT). Also confirm VCC is 5V not 3.3V.

?

Readings are erratic or jumping wildly

The sensor is picking up multiple echo bounces. Move it away from walls or corners. Soft objects (fabric, cushions) absorb ultrasound and give poor readings. Flat hard surfaces give best results.

?

Reads very large values (>400 cm)

Nothing within range, or the echo pulse timed out. Add a timeout to pulseIn: pulseIn(echoPin, HIGH, 25000) limits it to a 25ms timeout (max ~430cm).

?

Serial Monitor shows garbage characters

Baud rate mismatch. Make sure Serial Monitor dropdown matches Serial.begin() in your sketch. Both should be 9600.

?

Works, but readings seem off by a few cm

Temperature affects the speed of sound. At 20°C the formula works well. For precision, use: speedOfSound = 331.3 + (0.606 * tempCelsius) with a temperature sensor. For most projects the fixed formula is accurate enough.

Download Sample Sketch

Get a ready-to-upload .ino file for the HC-SR04 distance sensor.

Download the complete sample sketch below — it includes wiring comments, distance measurement in centimetres, a timeout guard, and a proximity alert. Ready to upload without any changes.

📄
hcsr04_distance_sample.ino
Distance in cm · Timeout guard · Proximity alert · No libraries needed
⬇ Download .ino
💡
How to open: In Arduino IDE go to File → Open and select the downloaded .ino file. No external libraries are needed — the sketch uses only Arduino's built-in pulseIn() function.