// Define pin connections
const int trigPin = 10;
const int echoPin = 9;
// Define variables
long duration;
int distance;
void setup() {
// Begin serial communication at a baud rate of 9600:
Serial.begin(9600);
// Configure the trigger pin as an output:
pinMode(trigPin, OUTPUT);
// Configure the echo pin as an input:
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(9);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (round-trip)
// Print the distance on the Serial Monitor:
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a short while before the next loop:
delay(500);
}