const int trigPin = 9; // Trig pin of the sensor connected to pin 9
const int echoPin = 10; // Echo pin of the sensor connected to pin 10
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud rate
pinMode(trigPin, OUTPUT); // Set trigPin as an output
pinMode(echoPin, INPUT); // Set echoPin as an input
}
void loop() {
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the duration of the echo signal
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance (speed of sound is ~343 meters per second or 29.1 microseconds per cm)
int distance = duration * 0.034 / 2;
// Print the distance in centimeters
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait half a second before the next reading
}