Tutorial Arduino Project How to Measure Distances with Ultrasonic Sensor HC-SR04


Measuring distances automatically and continuously comes in handy in many situations. Many different types of sensors for measuring distances are available, and the Arduino plays well with most of them. Some sensors use ultra-sound, while others use infrared light or even laser.



But in principle all sensors work the same way, they emit a signal, wait for the echo to return, and measure the time the whole process took. In this project, will build a device that measures the distance to the nearest object and outputs it on the serial port.



Table of Contents



Simulation





Wiring Diagram



<img src="arduino_hcsr04.png" alt="arduino_hcsr04">


Ultrasonic sensors usually do not return the distance to the nearest object. Instead, they return the time the sound needed to travel to the object and back to the sensor. HC-SR04 is no exception, and its innards are fairly complex. Fortunately, they are hidden behind four simple pins, VCC, GND, TRIGGER, and ECHO. This makes it easy to connect the sensor to the Arduino. First, connect Arduino’s ground and 5V power supply to the corresponding pins. Then connect the HC-SR04's sensor pins to Arduino’s digital IO pins.

Source Code


Here is the source code (sketch) for measuring distances using Arduino Uno and HC-SR04.

/*
How to Measure Distances
Arduino Uno Ultrasonic Sensor HC-SR04

Loki Lang
*/

#define echoPin 2
#define trigPin 3
long duration, distance, ultraSensor;

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

void loop()
{
  sensorUltrasonic(trigPin, echoPin);
  ultraSensor = distance;
  Serial.println(ultraSensor);
}

void sensorUltrasonic(int pinTrigger, int pinEcho)
{
  digitalWrite(pinTrigger, LOW);
  delayMicroseconds(2);
  digitalWrite(pinTrigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(pinTrigger, LOW);
  duration = pulseIn(pinEcho, HIGH);
  distance = (duration / 2) / 29.1;
  delay(100);
}