Bird
0
0
Arduinoprogramming~5 mins

Ultrasonic distance sensor (HC-SR04) in Arduino

Choose your learning style9 modes available
Introduction

The HC-SR04 sensor helps measure how far away something is by using sound waves. It sends a sound pulse and listens for the echo to find the distance.

To detect if an object is close or far, like a parking sensor in a car.
To measure the level of liquid in a tank without touching it.
To help a robot avoid bumping into walls or obstacles.
To count how many items pass by on a conveyor belt.
To create interactive projects that respond to how close a person is.
Syntax
Arduino
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500);
}

The trigPin sends a short sound pulse.

The echoPin listens for the returning sound to measure time.

Examples
This sends a 10 microsecond pulse to start the sensor's measurement.
Arduino
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
This waits for the echo pin to go HIGH and measures how long it stays HIGH, which is the time for the sound to travel to the object and back.
Arduino
duration = pulseIn(echoPin, HIGH);
This converts the time into distance in centimeters. Sound travels at about 0.034 cm per microsecond, and we divide by 2 because the sound goes to the object and back.
Arduino
distance = duration * 0.034 / 2;
Sample Program

This program measures the distance using the HC-SR04 sensor and prints it every half second to the Serial Monitor.

Arduino
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = duration * 0.034 / 2;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500);
}
OutputSuccess
Important Notes

Make sure the sensor's VCC and GND are connected correctly to power it.

Keep the sensor steady and avoid obstacles in front to get accurate readings.

The sensor works best for distances between 2 cm and 400 cm.

Summary

The HC-SR04 uses sound pulses to measure distance.

Send a short pulse on the trigger pin, then measure the echo time.

Convert the echo time to distance using the speed of sound.