const int trigPin = 9; // Trig pin
const int echoPin = 10; // Echo pin
long duration; // Variable to store the time of flight
int distance; // Variable to store the calculated distance
void setup() {
pinMode(trigPin, OUTPUT); // Set the trig pin as output
pinMode(echoPin, INPUT); // Set the echo pin as input
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Send the ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(trigPin, HIGH); // Trigger the pulse
delayMicroseconds(10); // Wait for 10 microseconds
digitalWrite(trigPin, LOW); // Stop the pulse
// Measure the time taken for the echo to return
duration = pulseIn(echoPin, HIGH); // Get the duration in microseconds
// Calculate the distance based on the speed of sound (0.034 cm per microsecond)
distance = duration * 0.034 / 2;
// Display the distance in the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(1000); // Wait 1 second before repeating the measurement
}