The HC-SR04 is the most popular Arduino ultrasonic sensor and a staple component in any maker’s toolkit. Whether you want to measure distance, build an obstacle-avoiding robot, create a parking sensor, or design a contactless switch, the HC-SR04 gives you accurate distance measurements from 2cm to 400cm for under Rs 50. In this complete tutorial, we cover everything from how the sensor works to real project code and accuracy tips.
Table of Contents
How Ultrasonic Sensors Work
Ultrasonic sensors measure distance using sound waves at a frequency above the range of human hearing (typically 40kHz). The HC-SR04 operates on a simple “ping and listen” principle:
- The Trigger pin is pulsed high for 10 microseconds, causing the sensor to emit 8 ultrasonic pulses at 40kHz
- These sound waves travel outward, hit an object, and reflect back
- The Echo pin goes high as soon as the pulses are sent and stays high until the echo is received
- The time the Echo pin stays high is proportional to the distance to the object
- Distance = (Time × Speed of Sound) / 2 (divided by 2 because the sound travels to the object AND back)
Speed of sound in air is approximately 343 m/s (34,300 cm/s) at 20°C. In microseconds per centimetre, that is approximately 29.1 µs/cm. So the formula becomes:
Distance (cm) = pulse_duration_µs / 58
HC-SR04 Specifications & Pinout
HC-SR04 Specifications:
- Operating Voltage: 5V DC
- Operating Current: 15mA
- Operating Frequency: 40kHz
- Minimum Range: 2 cm
- Maximum Range: 400 cm (4 metres)
- Accuracy: ±3mm
- Measuring Angle: 15 degrees
- Trigger Input Pulse Width: 10 µs
- Dimensions: 45mm × 20mm × 15mm
Pinout (left to right on the board):
- VCC: 5V power supply
- Trig: Trigger input (connect to Arduino digital output pin)
- Echo: Echo output (connect to Arduino digital input pin)
- GND: Ground
Wiring Diagram
Connecting HC-SR04 to Arduino Uno is straightforward — just 4 wires:
- HC-SR04 VCC → Arduino 5V
- HC-SR04 GND → Arduino GND
- HC-SR04 Trig → Arduino Digital Pin 9
- HC-SR04 Echo → Arduino Digital Pin 10
Important note for 3.3V boards (ESP32, Raspberry Pi): The HC-SR04 Echo pin outputs 5V, which can damage 3.3V microcontrollers. Use a voltage divider (1kΩ and 2kΩ resistors) on the Echo pin, or use the HC-SR04P variant which operates at 3.3V.
Code Using pulseIn()
The simplest way to read the HC-SR04 is using Arduino’s built-in pulseIn() function, which measures how long a pin stays at a given state. No library needed.
// HC-SR04 with pulseIn() - No library required
const int trigPin = 9;
const int echoPin = 10;
long duration; // Duration of echo pulse in microseconds
float distanceCm; // Distance in centimetres
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
Serial.println("HC-SR04 Distance Sensor Ready");
}
void loop() {
// 1. Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// 2. Send 10 microsecond trigger pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// 3. Read the echo pin duration (timeout: 30000 µs = ~5 metres)
duration = pulseIn(echoPin, HIGH, 30000);
// 4. Calculate distance
// Speed of sound = 34300 cm/s = 0.0343 cm/µs
// Distance = (duration * 0.0343) / 2
distanceCm = (duration * 0.0343) / 2.0;
// 5. Handle out-of-range readings
if (duration == 0) {
Serial.println("Out of range!");
} else {
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
}
delay(200); // Wait 200ms between readings
}
Using the NewPing Library
The NewPing library by Tim Eckel provides a cleaner API, supports up to 15 sensors simultaneously, eliminates the need for manual trigger pulses, and handles timeouts gracefully. Install it via Sketch → Include Library → Manage Libraries → search “NewPing”.
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400 // Maximum distance in cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(115200);
}
void loop() {
delay(50); // Wait 50ms between pings (avoid echo interference)
unsigned int uS = sonar.ping(); // Get ping in microseconds
float cm = uS / US_ROUNDTRIP_CM; // Convert to cm
Serial.print("Ping: ");
Serial.print(uS); // Microseconds
Serial.print(" us, ");
Serial.print(cm); // Centimetres
Serial.println(" cm");
}
// NewPing also provides:
// sonar.ping_cm() - directly returns distance in cm
// sonar.ping_in() - returns distance in inches
// sonar.ping_median(5) - takes 5 samples and returns median (more stable)
Obstacle Detection Project
Here is a practical obstacle detection circuit that triggers a buzzer and LED when something comes within 20cm. This is the core logic for an obstacle-avoiding robot.
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 200
#define LED_PIN 12
#define BUZZER_PIN 11
#define DANGER_DIST 20 // Alert if object within 20 cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
delay(100);
float distance = sonar.ping_cm();
if (distance == 0) {
// No echo = out of range or no object
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
Serial.println("No object detected");
} else if (distance < DANGER_DIST) {
// Object too close - ALERT!
digitalWrite(LED_PIN, HIGH);
tone(BUZZER_PIN, 1000); // 1kHz beep
Serial.print("OBSTACLE at: ");
Serial.print(distance);
Serial.println(" cm - STOP!");
} else {
// Object detected but safe distance
digitalWrite(LED_PIN, LOW);
noTone(BUZZER_PIN);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}
}
Parking Sensor Project
Build a mini parking assistant that changes LED colour and beep rate based on how close the car is to a wall. Uses three LEDs: green (safe), yellow (caution), red (stop).
#include <NewPing.h>
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 200
#define GREEN_LED 4
#define YELLOW_LED 5
#define RED_LED 6
#define BUZZER_PIN 7
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
pinMode(GREEN_LED, OUTPUT);
pinMode(YELLOW_LED, OUTPUT);
pinMode(RED_LED, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
delay(150);
float dist = sonar.ping_cm();
// Turn off all LEDs first
digitalWrite(GREEN_LED, LOW);
digitalWrite(YELLOW_LED, LOW);
digitalWrite(RED_LED, LOW);
noTone(BUZZER_PIN);
if (dist == 0 || dist > 100) {
digitalWrite(GREEN_LED, HIGH); // Safe - green on, no sound
} else if (dist > 50 && dist <= 100) {
digitalWrite(GREEN_LED, HIGH); // Yellow zone - slow beep
tone(BUZZER_PIN, 500);
delay(100);
noTone(BUZZER_PIN);
} else if (dist > 20 && dist <= 50) {
digitalWrite(YELLOW_LED, HIGH); // Caution - faster beep
tone(BUZZER_PIN, 800);
delay(50);
noTone(BUZZER_PIN);
} else {
digitalWrite(RED_LED, HIGH); // Danger - continuous alarm
tone(BUZZER_PIN, 1500);
}
}
Accuracy Tips for HC-SR04
The HC-SR04 is accurate to ±3mm in ideal conditions, but several factors can degrade readings in real projects:
- Temperature compensation: Speed of sound changes with temperature. At 30°C (common in India), it is ~349 m/s vs 343 m/s at 20°C. For high-precision work, add a temperature sensor and adjust:
speedOfSound = 331.3 + 0.606 * temperatureC - Minimum distance: The HC-SR04 cannot reliably detect objects closer than 2cm. The trigger pulse can overlap with the echo for very close objects.
- Angle: The sensor has a 15° cone angle. Objects at a steep angle reflect sound away from the sensor, giving no reading or false readings.
- Surface material: Soft surfaces (foam, fabric, carpet) absorb sound and reduce range. Hard, flat surfaces (walls, metal) give the best results.
- Averaging: Take 3–5 readings and average or take the median to filter noise:
sonar.ping_median(5) - Minimum delay between pings: Wait at least 50ms (preferably 60ms) between trigger pulses to allow the echo to fully dissipate. Shorter delays cause ghost echoes.
- Power supply: A noisy 5V supply causes erratic readings. Use a regulated 5V supply and add a 100µF decoupling capacitor near the sensor VCC pin.
Waterproof Alternatives
The standard HC-SR04 is not waterproof, which limits its use in outdoor or harsh environments. Consider these alternatives for demanding applications:
- JSN-SR04T: Waterproof ultrasonic sensor rated IP67. Uses the same protocol as HC-SR04. Single probe design with separate control board. Range: 20–600cm. Ideal for water level measurement, outdoor parking sensors, and industrial use.
- A02YYUW: Fully waterproof, compact, UART-based output. Excellent for liquid level sensing inside tanks.
- Maxbotix MB7389: High-quality waterproof ultrasonic sensor for professional applications. More expensive but extremely accurate and reliable.
For indoor projects like obstacle-avoiding robots and distance meters, the standard HC-SR04 is perfectly adequate and cost-effective.
Frequently Asked Questions
Q: Why does my HC-SR04 give 0 or wildly varying readings?
Common causes: insufficient delay between pings (use at least 50ms), sensor pointed at an absorptive surface, object too close (<2cm) or too far (>400cm), noisy power supply, or faulty sensor. Try adding a 100µF capacitor between VCC and GND and use ping_median(5) for averaging.
Q: Can I use HC-SR04 with ESP32?
Yes, but the HC-SR04 Echo pin outputs 5V, which can damage ESP32 (3.3V). Use a voltage divider (1kΩ and 2kΩ) on the Echo line, or use the HC-SR04P variant which works at 3.3V.
Q: How many HC-SR04 sensors can I use with one Arduino?
Each sensor needs 2 pins (Trig + Echo). An Arduino Uno has 14 digital pins, so theoretically 7 sensors. In practice, the NewPing library supports up to 15 sensors, but use a multiplexer or dedicated GPIO expander for more than 4–5 sensors.
Q: What is the minimum distance the HC-SR04 can measure?
The rated minimum is 2cm. At distances below 2cm, the trigger pulse and echo overlap, giving unreliable readings. Use an IR proximity sensor for very close-range detection.
Q: Is HC-SR04 accurate enough for a robotics project?
For most robotics projects (obstacle avoidance, navigation, distance estimation), ±3mm accuracy at Rs 40–60 is excellent. For precision measurement or outdoors, consider the waterproof JSN-SR04T or a LIDAR sensor.
Start Building Today!
Shop HC-SR04 sensors, Arduino boards, and all project components at Zbotic.in — India’s trusted electronics store.
Add comment