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 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.
const int trig = 6;
const int echo =7;
float duration, distance;
duration = pulseIn(echo, HIGH);
distance = (0.034*duration)/2;
Serial.println("Distance is: ");