Introduction
The HC-SR04 ultrasonic sensor can measure distances from 2cm to 400cm with reasonable accuracy. It works by sending out an ultrasonic pulse and measuring how long it takes for the echo to return.
Components Required
- Arduino Uno
- HC-SR04 Ultrasonic Sensor
- Breadboard and jumper wires
Wiring
| HC-SR04 Pin | Arduino Pin |
|---|---|
| VCC | 5V |
| Trig | Pin 9 |
| Echo | Pin 10 |
| GND | GND |
The Code
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Send a 10μs pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo duration
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}How It Works
- The Trig pin sends a short ultrasonic burst
- The sensor waits for the echo to bounce back
- The Echo pin goes HIGH for the duration of the round trip
- We calculate distance using: Distance = (Time × Speed of Sound) / 2
- Speed of sound ≈ 0.034 cm/μs
Testing
Upload the code, open Serial Monitor at 9600 baud, and point the sensor at objects at various distances. You should see accurate distance readings.
Applications
- Obstacle avoidance robots
- Parking sensors
- Liquid level measurement
- Proximity alarms