HC-SR04 Ultrasonic Distance Sensor
The HC-SR04 measures distance by sending an ultrasonic pulse and timing how long it takes for the echo to return.
Key idea:
The HC-SR04 has a range of 2cm–400cm with ~3mm accuracy. It operates at 5V and uses a simple pulse timing protocol.
Wiring
HC-SR04 VCC ────── 5V
HC-SR04 Trig ────── Arduino Pin 9
HC-SR04 Echo ────── Arduino Pin 10 (via voltage divider!)
HC-SR04 GND ────── GND
Using the NewPing Library
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
}
void loop() {
delay(50);
unsigned int distance = sonar.ping_cm();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}Manual Timing (without library)
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(115200);
}
void loop() {
// Send 10µs trigger pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo pulse duration
long duration = pulseIn(echoPin, HIGH);
// Calculate distance: speed of sound = 343 m/s = 0.0343 cm/µs
// Distance = (duration × 0.0343) / 2 (divide by 2 for round trip)
float distance = duration * 0.0343 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(100);
}Handling Out-of-Range
The HC-SR04 has a minimum range of 2cm. Below that, readings are unreliable:
float distance = sonar.ping_cm();
if (distance == 0 || distance > 400) {
Serial.println("Out of range");
} else {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}Key Takeaways
- HC-SR04 range: 2cm–400cm, ~3mm accuracy
- Trigger with 10µs HIGH pulse on Trig pin
- Measure echo pulse width on Echo pin
- Distance = (duration × 0.0343) / 2
- Use NewPing library for easier handling
- Voltage divider needed on Echo pin for 3.3V boards (ESP32)
Resources
- NewPing Library: https://github.com/jim-upton/NewPing
- Video: HC-SR04 Arduino Tutorial - https://www.youtube.com/watch?v=5IJD1tXeo3U
- HC-SR04 Datasheet: https://www.micropik.com/PDF/HCSR04.pdf