// define pins for the ultrasonic sensor
const int trigPin = 9;
const int echoPin = 10;
// variables for duration and distance
long duration;
int distance;
void setup() {
// initialize serial communication
Serial.begin(9600);
// set the trigger pin as output
pinMode(trigPin, OUTPUT);
// set the echo pin as input
pinMode(echoPin, INPUT);
}
void loop() {
// trigger a pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// measure the duration of the 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.print(distance);
Serial.println(" cm");
// wait for a short period before taking the next measurement
delay(500);
}