// ---------------------------------------------------------------- //
// Arduino Ultrasoninc Sensor HC-SR04
// Re-writed by Arbi Abdul Jabbaar
// Using Arduino IDE 1.8.7
// Using HC-SR04 Module
// Tested on 17 September 2019
// ---------------------------------------------------------------- //
#define echoPin 11 // attach pin 11 Arduino to pin Echo of HC-SR04
#define trigPin 12 //attach pin 12 Arduino to pin Trig of HC-SR04
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
}
void loop(){
// defines variables
int duration1; // variable for the travel duration of the first sound wave
int distance1; // variable for the distance measurement of the first sound wave
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the first sound wave travel time in microseconds
duration1 = pulseIn(echoPin, HIGH);
// Calculating the distance
distance1 = duration1*(0.034/2); // Speed of sound wave divided by 2 (go and back)
delayMicroseconds(200000); // delay of 0.2 seconds
// defines variables
int duration2; // variable for the travel duration of the second sound wave
int distance2; // variable for the distance measurement of the second sound wave
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration2 = pulseIn(echoPin, HIGH);
// Calculating the distance
distance2 = duration2*(0.034/2); // Speed of sound wave divided by 2 (go and back)
int velocity = (distance2 - distance1)/(duration1/(2*10E6) + 0.1 + duration2/(2*10E6));
// Displays the distance on the Serial Monitor
Serial.print("Distances: ");
Serial.print(distance1);
Serial.print(" cm, ");
Serial.print(distance2);
Serial.print(" cm. ");
Serial.print("Velocity: ");
Serial.print(velocity);
Serial.println(" cm/s.");
}