// Define the pins for the ultrasonic sensor
const int trigPin = 9; // Trigger pin connected to Arduino Pin 9
const int echoPin = 10; // Echo pin connected to Arduino Pin 10
// Variables to store the duration and distance
long duration; // Duration of the pulse in microseconds
int distance; // Calculated distance in centimeters
void setup() {
// Start the serial communication
Serial.begin(9600);
// Set the trigPin as OUTPUT and echoPin as INPUT
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10-microsecond pulse to the trigPin to initiate the ultrasonic pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse duration from the echoPin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance (speed of sound in air is 0.0344 cm per microsecond)
distance = duration * 0.0344 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a while before the next reading
delay(500);
}