const int trigPin = 7;
const int echoPin = 6;
void setup() {
Serial.begin(9600); // Start Serial Monitor
pinMode(trigPin, OUTPUT); // Set Trig as output
pinMode(echoPin, INPUT); // Set Echo as input
}
void loop() {
// Send a 10µs pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo time
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
float distance = (duration / 2.0) * 0.0343;
// Display the result
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait half a second before next reading
}