const int trigPin = 2; // Trigger pin of the ultrasonic sensor
const int echoPin = 3; // Echo pin of the ultrasonic sensor
const int buzzerPin = 8; // Buzzer pin
const int warningDistance = 20; // Distance in centimeters, below which the warning will be triggered
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
long duration, distance;
// Generate pulse for the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = (duration * 0.0343) / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is below the warning threshold
if (distance < warningDistance) {
// If so, trigger the warning (turn on the buzzer)
digitalWrite(buzzerPin, HIGH);
} else {
// Otherwise, turn off the buzzer
digitalWrite(buzzerPin, LOW);
}
delay(500); // Adjust the delay according to your needs
}