// Define pins for ultrasonic sensor
const int trigPin = 5;
const int echoPin = 4;
// Variable for distance calculation
long duration;
int distanceCm;
void setup() {
// Initialize serial communication at 9600 baud rate
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigger pin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the duration in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distanceCm = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
// Add a small delay for readability
delay(500);
}