// Define pins for the HC-SR04
const int trigPin = 9;
const int echoPin = 10;
// Define variables for duration and distance
long duration;
float distance;
void setup() {
// Initialize the serial monitor
Serial.begin(9600);
// Set trigPin as OUTPUT and echoPin as INPUT
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin
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
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = (duration * 0.034) / 2;
// Print the distance on the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Delay before next reading
delay(500);
}