const int trigPin = 9; // Define the trig pin as 9
const int echoPin = 8; // Define the echo pin as 8
long duration; // Variable to store the duration of the sound wave
int distance_cm; // Variable to store the distance in centimeters
void setup() {
pinMode(trigPin, OUTPUT); // Set trig pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
[Link](9600); // Start serial communication at 9600 baud rate
}
void loop() {
digitalWrite(trigPin, LOW); // Set trig pin to low for 2 microseconds
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Set trig pin to high for 10 microseconds
delayMicroseconds(10);
digitalWrite(trigPin, LOW); // Set trig pin to low again
duration = pulseIn(echoPin, HIGH); // Measure the duration of the pulse received
by the echo pin in microseconds
distance_cm = duration * 0.034 / 2; // Calculate the distance in centimeters
using the speed of sound and the duration
[Link]("Distance: "); // Print the distance to the serial monitor
[Link](distance_cm);
[Link](" cm");
delay(500); // Wait for 500 milliseconds before repeating the measurement
}