// Define pins for the ultrasonic sensor
const int trigPin = 9;
const int echoPin = 8;
// Variables to store the duration of the echo and the calculated distance
long duration;
float distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Configure trigger and echo pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Print a start message to the Serial Monitor
Serial.println("HC-SR04 Ultrasonic Sensor Test");
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10-microsecond pulse to the trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
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.println(distance);
// Serial.println(" cm");
// Wait 500 milliseconds before the next measurement
delay(500);
}