// Define the pins for the ultrasonic sensor
int trigPin = 2;
int echoPin = 3;
int distance;
int duration;
void setup() {
// Initialize Serial Communication
Serial.begin(9600);
// Set the trigPin as an OUTPUT and echoPin as an INPUT
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Send a short pulse to the ultrasonic sensor to trigger a reading
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the duration of the pulse from the echoPin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters based on the speed of sound (343 meters/second)
// Distance = (duration / 2) * speed of sound
// Distance = (duration / 2) * 0.0343 (since speed of sound is approximately 343 meters/second)
distance = (duration / 2) * 0.0343;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short delay before taking the next reading
delay(1000); // You can adjust the delay according to your requirement
}