Contents
Introduction
The HC-SR04 uses sound waves to measure distance, exactly like a bat. It is one of the most useful and affordable sensors for Arduino projects. In this tutorial we cover wiring, calibration, and three practical projects.
How It Works
- Trigger pin: 10µs HIGH pulse fires ultrasonic burst.
- Echo pin: HIGH pulse duration proportional to distance.
- Formula: Distance (cm) = Echo duration (µs) / 58
Wiring to Arduino Uno
| HC-SR04 | Arduino |
|---|---|
| VCC | 5V |
| GND | GND |
| Trig | Pin 9 |
| Echo | Pin 10 |
Project 1: Distance Meter
#define TRIG 9
#define ECHO 10
void setup() { Serial.begin(9600); pinMode(TRIG,OUTPUT); pinMode(ECHO,INPUT); }
long getDist() {
digitalWrite(TRIG,LOW); delayMicroseconds(2);
digitalWrite(TRIG,HIGH); delayMicroseconds(10); digitalWrite(TRIG,LOW);
return pulseIn(ECHO,HIGH)/58;
}
void loop() { Serial.println(String(getDist())+" cm"); delay(200); }
Project 2: Parking Sensor with Buzzer
#define TRIG 9
#define ECHO 10
#define BUZZER 11
void setup() { pinMode(TRIG,OUTPUT); pinMode(ECHO,INPUT); pinMode(BUZZER,OUTPUT); }
long getDist() {
digitalWrite(TRIG,LOW); delayMicroseconds(2);
digitalWrite(TRIG,HIGH); delayMicroseconds(10); digitalWrite(TRIG,LOW);
return pulseIn(ECHO,HIGH)/58;
}
void loop() {
long d=getDist();
if(d<10) { digitalWrite(BUZZER,HIGH); }
else if(d<30) { digitalWrite(BUZZER,HIGH); delay(100); digitalWrite(BUZZER,LOW); delay(100); }
else { digitalWrite(BUZZER,LOW); delay(200); }
}
Project 3: Water Tank Level Monitor
Mount the HC-SR04 at the top of a tank pointing down. As water rises, echo time decreases. Convert this to a percentage.
#define TRIG 9
#define ECHO 10
#define TANK_H 100
void setup() { Serial.begin(9600); pinMode(TRIG,OUTPUT); pinMode(ECHO,INPUT); }
void loop() {
digitalWrite(TRIG,LOW); delayMicroseconds(2);
digitalWrite(TRIG,HIGH); delayMicroseconds(10); digitalWrite(TRIG,LOW);
long dist=pulseIn(ECHO,HIGH)/58;
int pct=constrain(((TANK_H-dist)*100)/TANK_H,0,100);
Serial.println("Water Level: "+String(pct)+"%");
delay(1000);
}
Conclusion
The HC-SR04 is a must-have for every maker. From robotics to smart home automation, its applications are nearly limitless!