// Define pins for the Ultrasonic sensor
const int trigPin = 12; // Trig pin connected to pin 9
const int echoPin = 11; // Echo pin connected to pin 10
// Variables to store the duration and distance
long duration;
int distance;
void setup() {
// Initialize the Serial Monitor
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 for 2 microseconds
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance (duration / 2) / 29.1
distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print(“Distance: “);
Serial.print(distance);
Serial.println(” cm”);
// Wait for 1 second before repeating
delay(1000);
}