// Define pin numbers
const int trigPin = 3; // Trigger pin connected to Pin 9
const int echoPin = 2; // Echo pin connected to Pin 10
long duration; // Variable to store the echo duration
float distance; // Variable to store the calculated distance
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Set the trigPin as an output
pinMode(trigPin, OUTPUT);
// Set the echoPin as an input
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, return the duration in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Small delay before next reading
delay(500);
}