#define echoPin 6 // Define the echo pin (receive)
#define triggerPin 7 // Define the trigger pin (transmit)
long duration; // Variable to store the duration of the sound wave travel
int distance; // Variable to store the calculated distance
void setup() {
pinMode(triggerPin, OUTPUT); // Set trigger pin as an OUTPUT
pinMode(echoPin, INPUT); // Set echo pin as an INPUT
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
}
void loop() {
digitalWrite(triggerPin, LOW); // Ensure the trigger pin is low
delayMicroseconds(2); // Short delay
digitalWrite(triggerPin, HIGH); // Send a 10us pulse to trigger the sensor
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH); // Measure the duration of the echo pulse
distance = duration * 0.034 / 2; // Calculate the distance based on the speed of sound
Serial.print("Calculated Distance: ");
Serial.print(distance);
Serial.println(" cm"); // Print the calculated distance in centimeters
delay(100); // Wait for a short time before taking the next measurement
}