const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
void setup() {
// Sets the trigPin as an Output
pinMode(trigPin, OUTPUT);
// Sets the echoPin as an Input
pinMode(echoPin, INPUT);
// Starts the serial communication
Serial.begin(9600);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the pulse width from the echoPin
duration = pulseIn(echoPin, HIGH);
// Calculates the distance in cm
distance = duration * 0.0343 / 2;
// Prints the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
}