How to Use Ultrasonic Sensor HC SR04 in Arduino

Introduction

 
An Ultrasonic Sensor is a module that is used to find the distance between the nearest object and the module itself.
 
 
Figure 1 Ultrasonic Sensor
 
So, it has two heads where one sends the ultrasound signal and the other receives one. And its range is from 2cm to 3m (with nominal errors).
 
The HC-SR04 module sends an ultrasonic short pulse signal from the trigger and listens to the signal from the echo when it bounces back from the object.
 
 
Figure 2 HC-SR04
 
If it doesn't find an error then it will either a large value or a very short. While coding, you must take care of the range and some exceptions.
 
As a default condition, we make an exception when it can't find any object above 200cm.
 
Background: As you can see, there are three pins for Vcc, Trigger, Echo, and GND. Vcc and GND are quite explanatory. And, Trigger sends the ultrasonic signal, and Echo listens for that signal after returning.
 
And, its connection would be like:
 
 
Figure 3 Signal Socit
 
Every Ultrasonic module has four legs and two are pre-defined. And, those are Vcc (5volt) and GND. Apart from these two, we have Trigger and Echo. Trigger is always a Digital PIN whereas Echo can be a PWM or any Digital PIN.
 
As an add-on, we have added a Red and a Green LED to notify whether it's in range or not. When the module detects nearby objects it then it will turn on Red else it'll constantly turn on Green.
 
Sketch
  1. // PIN CONMFIGRATION  
  2. int RED = 4; // Digital Pin 4  
  3. int GREEN = 8; // Digital Pin 8  
  4. int TRIGGER = 12; // Digital Pin 12  
  5. int ECHO = 11; // Digital Pin 4 (PWM)  
  6. int max_distance = 200; // 200cm  
  7. int min_distance = 0;  
  8. int duration;  
  9. int distance;  
  10. void setup() {  
  11.     Serial.begin(9600);  
  12.     pinMode(TRIGGER, OUTPUT);  
  13.     pinMode(ECHO, INPUT);  
  14.     pinMode(RED, OUTPUT);  
  15.     pinMode(GREEN, OUTPUT);  
  16. }  
  17. void loop() {  
  18.     distance = 0;  
  19.     duration = 0;  
  20.     digitalWrite(TRIGGER, LOW);  
  21.     delayMicroseconds(2);  
  22.     digitalWrite(TRIGGER, HIGH);  
  23.     delayMicroseconds(10);  
  24.     digitalWrite(TRIGGER, LOW);  
  25.     duration = pulseIn(ECHO, HIGH);  
  26.     // Convert in CM  
  27.     distance = (duration / 2) / 29.1;  
  28.     digitalWrite(GREEN, HIGH);  
  29.     if (distance >= max_distance || distance <= min_distance) {  
  30.         Serial.println("# Out Of Rage");  
  31.     } else {  
  32.         Serial.print(distance);  
  33.         Serial.println(" cm");  
  34.         digitalWrite(RED, HIGH);  
  35.         digitalWrite(GREEN, LOW);  
  36.         delay(1000);  
  37.         digitalWrite(RED, LOW);  
  38.     }  
  39.     delay(1000);  
  40. }
Before I explain its future perspective, you must understand the code.
 
First, we have declared the PINs. Since we have four pins in the module (one is Vcc and another is GND, then trigger and echo).
 
Then, there are another two PINs for the Red and Green LEDs.
 
Next, we assigned maximum and minimum distance values for the module. Factually, it's not necessary to do but, we keep a range until when it will respond. Then we have variables like duration and distance that we'll use in our further code.
 
Using pinMode() set all the PINs as per their Input/Output behavior.
 
Trigger is an output Lead since it sends the ultrasonic signal and Echo listens for that signal after getting a bounce back.
 
After successful completion, we calculate the duration first then the distance.
 
The following is how it will work.
  1. digitalWrite(TRIGGER, LOW);  
  2. delayMicroseconds(2);
So, it is writing a LOW value to the Ultrasonic module. That means that the module is not sending any signal or LOW signal. After sending the LOW signal it will wait for 2 microseconds.
 
After waiting for 2 microseconds: 
  1. digitalWrite(TRIGGER,HIGH);  
  2. delayMicroseconds(10);  
  3. digitalWrite(TRIGGER, LOW);
Write a HIGH value, in other words send an ultrasonic signal and wait for 10 microseconds. Then make it low.
 
What that actually means is that it sends a signal using the trigger PIN and then makes it low after 10 microseconds.
 
And now we'll try to listen to that signal that we have sent and that can be done with the ECHO pin.
  1. duration= pulseIn(ECHO, HIGH);
And it returns the time-duration. Depending on the duration value, we'll calculate the distance in centimeters or in inches.
  1. // Convert in CM  
  2. distance= (duration/2)/29.1;  
Next, we will check whether it's in range or not.
  1. if( distance >=max_distance || distance <= min_distance)  
  2. {  
  3. Serial.println("# Out Of Rage");  
  4. }
And if the object is in range then:
  1. Serial.print(distance);  
  2. Serial.println(" cm");  
  3. digitalWrite(RED, HIGH);  
  4. digitalWrite(GREEN, LOW);  
  5. delay(1000);  
  6. digitalWrite(RED,LOW);
It will then show a value in the Serial Monitor and at the same time turn on the Red LED. Each time the loop() method will show the measured value.
 
 
Figure 4 Serial Monitor
 
Troubleshoot
 
If your serial monitor constantly shows Out Of Range then you must check the connection or provide some time to calculate the distance.
 

Conclusion

 
This module is one of the most-used modules in any physical rotatory or automated device. It assumes the exact distance and processes accordingly.
 
You can use more than one module to judge more precisely. Until then, enjoy your work.