For distance measuring applications HC-SR04 is the most common sensor used. This sensor uses sound waves to measure the distance between the sensor and the obstacle. It works on the principle of Doppler effect.
HC-SR04 also known as ultrasonic sensor have four pins:
Vcc ------ +5v
Trig------- Output
Echo ------Input
Gnd-------Gnd
Trig will send or generate the sound wave which is received at Echo pin and time of travel is calculated by the microcontroller.
So, Distance is calculated using the formula:
Distance = Speed * Time
Speed = 340m/s
Time Calculated by PulseIn function of Arduino
Hence, using the formula stated above distance can be easily calculated.
Source Code:
const int trig = 6;
const int echo =7;
float duration, distance;
void setup()
{
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(trig, LOW);
delayMicroseconds(5);
digitalWrite(trig, HIGH);
delayMicroseconds(5);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = (0.034*duration)/2;
Serial.println("Distance is: ");
Serial.println(distance);
delay(500);
}
Top Comments