const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 11;
const int ledPin = 12;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // For debugging purposes
}
void loop() {
// Clear the trigger pin before sending the signal
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to the trigger pin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse duration and calculate the distance
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
// Debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than 100cm
if (distance < 100) {
digitalWrite(buzzerPin, HIGH);
digitalWrite(ledPin, HIGH);
Serial.print(" the object is identified");
} else {
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
Serial.print(" the object is far away");
}
delay(100); // Wait a bit before doing the next measurement
}