// Define the pins for the ultrasonic sensor
const int trigPin = 9; // Trigger pin
const int echoPin = 10; // Echo pin
// Variables to store the duration and distance
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set trigPin as an OUTPUT
pinMode(trigPin, OUTPUT);
// Set echoPin as an INPUT
pinMode(echoPin, INPUT);
}
void loop() {
// Trigger the ultrasonic sensor by sending a 10us pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo duration in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters (you can change this to inches by dividing by 148 instead)
distance = duration / 58;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Add a small delay between measurements
delay(500); // Adjust this delay as needed
}