const int trigPin = 2; // Trig pin of the ultrasonic sensor
const int echoPin = 3; // Echo pin of the ultrasonic sensor
const int redLedPin = 4; // Red LED pin
const int greenLedPin = 5; // Green LED pin
const int buzzerPin = 6; // Buzzer pin
void setup() {
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration * 0.0343) / 2;
if (distance < 50) {
digitalWrite(redLedPin, HIGH);
digitalWrite(greenLedPin, LOW);
tone(buzzerPin, 1000); // Activate the buzzer
} else {
digitalWrite(redLedPin, LOW);
digitalWrite(greenLedPin, HIGH);
noTone(buzzerPin); // Deactivate the buzzer
}
delay(1000); // Adjust the delay as needed
}