#define trigPin 9 // define the trig pin
#define echoPin 10 // define the echo pin
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(trigPin, OUTPUT); // set trig pin as output
pinMode(echoPin, INPUT); // set echo pin as input
}
void loop() {
long duration, distance; // declare variables for duration and distance
// send a 10us pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// measure the duration of the pulse from the echo pin
duration = pulseIn(echoPin, HIGH);
// calculate the distance in centimeters
distance = duration / 58.2;
// print out the distance in centimeters
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500); // wait for 500ms before measuring again
}