// Define pin numbers
const int trigPin = 9;
const int echoPin = 8;
// Define variables for duration and distance
long duration;
float distance;
void setup() {
// Initialize the Serial Monitor
[Link](9600);
// Set trigPin as an OUTPUT and echoPin as an INPUT
pinMode(trigPin, OUTPUT);
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, and measure the duration of the pulse in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = duration * 0.034 / 2; // Speed of sound = 343 m/s or 0.034 cm/μs
// Print the distance to the Serial Monitor
[Link]("Distance: ");
[Link](distance);
[Link](" cm");
// Wait for a short period before the next measurement
delay(500);
}