Working With HC-SR04 Ultrasonic Sensor

Introduction

 
In my previous article I explained working with LM35 Temperature to get accurate room temperature value and in this article, I'll show you how can we work with HC-SR04 Ultrasonic Sensor to get accurate distance of the objects and some other functionalities. etc. Ultrasonic Sensor has many uses in the Medicine field.
 
Requirements
  • Arduino
  • Bread Board
  • Ultrasonic Sensor (HC-SR04)
  • Led
  • Jumper Wires 
  • Ultrasonic Sensor (HC-SR04)
 
Figure 1: HC-SR04 Ultrasonic Sensor 
 
What Ultrasonic Sensors can do? 
  • The HC-SR04 Ultrasonic Sensor uses detection of objects
  • Measurement of length 
  • Thickness, amount and destruction of the objects, etc.
Connection
  1. Vcc pin to the 5v
  2. Trig pin to digital pin 5
  3. Echo pin to digital pin 6
  4. Gnd to Gnd  
Program
  1. # define echoPin 5 // Echo Pin    
  2. # define trigPin 6 // Trigger Pin    
  3. # define LedPin 13 // Led    
  4. int maxRange = 300; // Maximum range     
  5. int minRange = 0; // Minimum range     
  6. long dur, dist; // Duration used to calculate distance    
  7. void setup()    
  8. {    
  9.     Serial.begin(9600);    
  10.     pinMode(trigPin, OUTPUT);    
  11.     pinMode(echoPin, INPUT);    
  12.     pinMode(LedPin, OUTPUT);    
  13. }    
  14. void loop()    
  15. {    
  16.     digitalWrite(trigPin, LOW);    
  17.     delayMicroseconds(2);    
  18.     digitalWrite(trigPin, HIGH);    
  19.     delayMicroseconds(10);    
  20.     digitalWrite(trigPin, LOW);    
  21.     dur = pulseIn(echoPin, HIGH);    
  22.     dist = dur / 58.2;    
  23.     if (dist >= maxRange || dist <= minRange)    
  24.     {    
  25.         Serial.println("-1");    
  26.         digitalWrite(LedPin, HIGH);    
  27.     }    
  28.     else    
  29.     {    
  30.         Serial.println(dist);    
  31.         digitalWrite(LedPin, LOW);    
  32.     }    
  33.     delay(50);    
  34. }   
Output
 
 
Figure 2: Output 
 
 Explanation
  • #define echoPin, trigpin, ledpin are the variables that take the values of these pins during compile time.
  • And set the maximum range and minimum range duration to find out the distance of the objects.
  • The Setup() function is used to set the pinMode to the trigpin, echopin, and the ledpin.
  • And the  loop() function is used to set our own condition what the Ultrasonic Sensor wants to do.
  • dist = dur/58.2; //Calculate the distance (in cm) based on the speed of sound.
  • if (dist >= maxRange || dist <= minRange) and set the condition to the ultrasonic sensor. Based up on this condition when the object is found in the ultrasonic sensor the led is blink otherwise it will be a static one.

Conclusion

 
And finally, we conclude that with the ultrasonic sensor we made the object finder.