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
- Vcc pin to the 5v
- Trig pin to digital pin 5
- Echo pin to digital pin 6
- Gnd to Gnd
Program
- # define echoPin 5 // Echo Pin
- # define trigPin 6 // Trigger Pin
- # define LedPin 13 // Led
- int maxRange = 300;
- int minRange = 0;
- long dur, dist;
- void setup()
- {
- Serial.begin(9600);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- pinMode(LedPin, OUTPUT);
- }
- void loop()
- {
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- dur = pulseIn(echoPin, HIGH);
- dist = dur / 58.2;
- if (dist >= maxRange || dist <= minRange)
- {
- Serial.println("-1");
- digitalWrite(LedPin, HIGH);
- }
- else
- {
- Serial.println(dist);
- digitalWrite(LedPin, LOW);
- }
- delay(50);
- }
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.