const int trigPin = 9; // Trig pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the trigPin as an OUTPUT
pinMode(trigPin, OUTPUT);
// Set the echoPin as an INPUT
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, return the sound wave travel time in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
// Speed of sound wave divided by 2 (go and back) is 34300 cm/s
// (duration * 0.0343) / 2 gives the distance in cm
float distance = (duration * 0.0343) / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short period before the next measurement
delay(1000);
}