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.
Video walkthrough
Prefer to watch? These cover the same steps.
Community videos. Tishvi is not affiliated with creators.
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.
±3mm accuracy
Draws only 15mA
Aim directly at target
4 pins total
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.
Wiring to Arduino UNO R3
4 wires. Pin 9 = Trig, Pin 10 = Echo. Both are digital I/O pins.
| HC-SR04 Pin | Connect to Arduino | Wire Colour | Notes |
|---|---|---|---|
| VCC | 5V | ■ Red | Must be 5V — not 3.3V |
| GND | GND | ■ Black | Any GND pin works |
| Trig | Pin 9 | ■ Blue | Sends the ultrasonic pulse (output from Arduino) |
| Echo | Pin 10 | ■ Purple | Receives the echo timing (input to Arduino) |
trigPin and echoPin constants in the code to match your wiring.Read Distance in Centimetres
Core sketch — the foundation for all HC-SR04 projects.
// 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 }
distance = (duration / 2) × 0.0343 simplifies to duration / 58.2. For inches: use duration / 148.View Output in Serial Monitor
Open the Serial Monitor to see live distance readings.
Upload the sketch from Step 4
Click Upload → and wait for "Done uploading."
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).
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.
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.
Proximity Alert — LED Warning
Light up an LED when something gets within 20cm. A basic obstacle detector.
// 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; }
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.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.
.ino file. No external libraries are needed — the sketch uses only Arduino's built-in pulseIn() function.Next Steps
What to build with your distance sensor next.
SG90 Servo + HC-SR04
Wire both together — servo turns when an object is detected. Classic obstacle-avoidance starter project.
Display Distance on OLED
Show live HC-SR04 readings on a 0.96" OLED screen — ditch the Serial Monitor and build a real distance meter.
Display Distance on LCD
Use a 16×2 LCD with I2C to display distance values — a great combination for a parking sensor or range finder.