#define ECHOpin 5 // defines the ECHO pin of the sensor to pin 5 of Arduino
#define TRIGpin 6
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
pinMode(TRIGpin, OUTPUT); // sets the TRIG pin as OUTPUT
pinMode(ECHOpin, INPUT); // sets the ECHO pin as INPUT
Serial.begin(9600); // Serial Communication at the rate of 9600 bps
Serial.println("Test of the Ultrasonic Sensor HC-SR04"); // text on Serial Monitor
Serial.println("with the Arduino Mega");
}
void loop() {
digitalWrite(TRIGpin, LOW); // sets the TRIG pin at LOW for 2 microseconds
delayMicroseconds(2);
digitalWrite(TRIGpin, HIGH); // sets TRIG pin at HIGH for 10 microseconds
delayMicroseconds(10);
digitalWrite(TRIGpin, LOW);
duration = pulseIn(ECHOpin, HIGH); // reads the ECHO pin and returns the time duration
// distance formula
distance = duration * 0.034 / 2; // 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); // optional delay for better readability
}