C++ and Arduino: Aduino Uno with HC-SR04 Ultrasonic Sensor
Introduction:
This article shows you how we can work with HC-SR04 Ultrasonic Sensor to get the accurate distance of the objects and some other functionalities, etc. Ultrasonic Sensor has many uses in the medicine field.
Requirements:
- Arduino Uno
- Bread Board
- LED
- Jumper Wires
- Ultrasonic Sensor (HC-SR04)
Connection:
- HC-SR04 Sensor
- Vcc pin to the 5v
- Trig pin to digital pin 5
- Echo pin to digital pin 6
- Gnd to Gnd
LED:
- Anode pin to the Arduino digital pin13
- Cathode pin to the Arduino Gnd
Code:
# define echoPin 5 // Echo Pin
# define trigPin 6 // Trigger Pin
int LedPin=13;
int maxRange = 300; // Maximum range
int minRange = 0; // Minimum range
long dur, dist; // Duration used to calculate distance
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);
}
Explanation:
- #define echoPin, trigpin, Ledpin are the variables that take the values of the sensor and led pins during compile time.
- 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.
- The loop() function is used to set our own condition of what the Ultrasonic Sensor wants to do.
Example:
- dist = dur/58.2; //Calculate the distance (in cm) based on the speed of sound.
Condition:
- **if (dist >= maxRange || dist <= minRange) **
Set the condition to the ultrasonic sensor. Based up on this condition, when the object is detected in the ultrasonic sensor the LED will blink otherwise it will be in off mode.
Output:
What can Ultrasonic Sensors do?
- The HC-SR04 Ultrasonic Sensor used for detection of objects.
- Measurement of length.
- Measurement of thickness, amount and destruction of the objects, etc.