// Define pins for the ultrasonic sensor and LED
const int trigPin = 12;
const int echoPin = 11;
const int ledPin = 2;
// Define variable to store the distance
long duration;
int distance;
// Define the distance threshold for detecting an object
const int thresholdDistance = 20; // in centimeters
void setup() {
// Start the serial communication
Serial.begin(9600);
// Set the trigPin as an OUTPUT
pinMode(trigPin, OUTPUT);
// Set the echoPin as an INPUT
pinMode(echoPin, INPUT);
// Set the ledPin as an OUTPUT
pinMode(ledPin, OUTPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and return the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH, 30000); // 30ms timeout (approx 510cm)
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the duration and distance to the Serial Monitor for debugging
Serial.print("Duration: ");
Serial.print(duration);
Serial.print(" us | Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than the threshold
if (distance < thresholdDistance) {
// Turn the LED on
digitalWrite(ledPin, HIGH);
} else {
// Turn the LED off
digitalWrite(ledPin, LOW);
}
// Add a delay before the next measurement
delay(500);
}