/*The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
The sound travels through the air. If it finds an object, it bounces back to the
module.
The ultrasound receiver (echo pin) receives the reflected sound (echo).
The time between the transmission and reception of the signal allows us to calculate
the distance to an object. This is possible because we know the sound’s velocity in
the air. Here’s the formula:
distance to an object = ((speed of sound in the air)*time)/2
*/
#define echoPin 2 // it defines the ECHO pin of the sensor to pin 2 of Arduino
#define trigPin 3 // it defines the TRIG pin of the sensor to pin 3 of Arduino
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
// Serial Communication at the rate of 9600 bps
Serial.begin(9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// It first sets the TRIG pin at LOW for 2 microseconds
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// It now sets TRIG pin at HIGH for 20 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(20);
digitalWrite(trigPin, LOW);
// It will read the ECHO pin and will return the time
duration = pulseIn(echoPin, HIGH);
// distance formula
distance = duration * 0.034 / 2; // (speed in microseconds)
// Speed of sound wave (340 m/s)divided by 2 (forward and backward bounce)
// To display the distance on Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");//specified unit of distance
delay(1000);
}