#define trigPin A0 // Trigger pin connected to D9
#define echoPin A2 // Echo pin connected to D10
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Trigger pin as output
pinMode(echoPin, INPUT); // Echo pin as input
Serial.begin(9600); // Start serial communication
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10µs HIGH pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and measure the duration of the pulse
duration = pulseIn(echoPin, HIGH);
// Calculate distance (speed of sound is 34300 cm/s)
distance = duration * 0.034 / 2;
// Print the distance on Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait a bit before next measurement
}