const int trigPin = 5;
const int echoPin = 18;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Configure the pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the duration of the echo
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance (duration / 2) / 29.1
int distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay before next reading
delay(1000);
}