The HC-SR04 ultrasonic sensor is a very affordable proximity/distance sensor that has been used mainly for object avoidance in various robotics projects. It essentially gives your Arduino eyes/spatial awareness and can prevent your robot crashing against a wall. It has also been used in turret applications, water level sensing, and even as a parking sensor.

The electronic circuit shown on the left is the standard mounting schema. And the Arduino sketch is shown here:

/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v 
 GND to arduino GND
 Echo to Arduino pin 7 
 Trig to Arduino pin 8
*/
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */ 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10); 
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
/* Calculate the distance (in cm) based on the speed of sound. */
 distance = duration/58.2; 	// distance = (duration/2) / 29.1

 if (distance >= maximumRange || distance <= minimumRange){
 /* Send a negative number to computer and Turn LED ON to indicate "out of range" */
 	Serial.println("-1"); 	// or Serial.println("Out of range");
 	digitalWrite(LEDPin, HIGH); 
 }
 
 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 	Serial.print(distance);
 	Serial.println(" cm");
 	digitalWrite(LEDPin, LOW); 
 }
 delay(50); 			// Delay 50ms before next reading.
}


♦ Case study
Providing a positive pulse of 10 µs to pin "Trigger Pulse Input", the SRF04 sensor generates a train of ultrasonic pulses at 40 kHz, these impulses are sent through the transmitter capsule, around the obstacle. The receiver capsule detects the echo and pin "Echo Pulse Output" get a pulse duration of 100 µs (3 cm) to 18 ms (3 m) proportional to the object distance. If the receiver does not detect any obstacle within 3 m, it produces a pulse duration of about 36 ms.



♦ Practice 1
Test HC-SR04 without needing a PC to show distance and check the accuracy of the sensor. Turn on a green LED during operation, but turn off it and turn on a red LED when distance of the objects is less than 4cm.
Connect the components and wires as shown in the next picture. Two 560 ohm resistors connect each LED cathode and GRD power rail.



Answer - Practice 1

if (distance < 4) {         // This is where the LED On/Off happens
  digitalWrite(led,HIGH); // When Red condition is met, Green LED should turn off
  digitalWrite(led2,LOW);
}
  else {
    digitalWrite(led,LOW);
    digitalWrite(led2,HIGH);
  }


Exercise 1
Calculate the distance (in cm) based on the speed of sound. The approximate speed of sound in dry air is given by the formula:

speed of sound = 331.5 + 0.6 * [air temperature in degrees Celsius]
At 20°C, speed of sound = 331.5 + 0.6 * 20 = 343.5 m/s

pulseIn() returns the length of the pulse in microseconds: if value is HIGH, waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing.
The length of the pulse is divided by 2, because this is the time to hit an object and to come back to the sensor.
If we convert the speed in centimetres per microseconds we get:

speed of sound = 343.5 * 100 / 1000000 = 0.03435 cm/µs = 1 / 29.1 cm/µs
distance [m] = duration [s] / speed of sound [m/s] / 2 ==>
==> distance [cm] = duration [µs] / 29.1 [µs/cm]  / 2 = duration [µs] / 58.2 [µs/cm]