// Define the pins for the ultrasonic sensor
const int trigPin = 9;
const int echoPin = 8;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the trigger pin as output and echo pin as input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Calculate the distance
float distance = measureDistance();
// Print the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // Wait for half a second
}
float measureDistance() {
// Send a short pulse to the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the pulse duration on the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
float distance = duration * 0.034 / 2;
return distance;
}