const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
const int ledPin = 7; // LED pin
const int buzzerPin = 11; // Buzzer pin
void setup()
{
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop()
{
long duration, distance;
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the pulse duration on echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Output distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is below a threshold (adjust as needed)
if (distance < 20) {
// Turn on LED and buzzer
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 1000); // You can adjust the frequency
} else {
// Turn off LED and buzzer
digitalWrite(ledPin, LOW);
noTone(buzzerPin);
}
delay(1000); // Adjust delay as needed for your application
}