// Define pins
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 3;
// Variables to store distance data
long duration;
int distance;
void setup() {
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Begin Serial communication
Serial.begin(9600);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds to trigger the ultrasonic pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the time taken for the echo to return
duration = pulseIn(echoPin, HIGH, 30000); // Add timeout of 30ms for more stability
// Check if valid data is received (duration should be non-zero)
if (duration > 0) {
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Turn on the LED if an object is within 20 cm
if (distance <= 20) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
} else {
// If no valid data is received, keep LED off
digitalWrite(ledPin, LOW);
Serial.println("Out of range");
}
// Add a small delay before the next loop iteration
delay(1000); // 1 second delay for debouncing
}