const int echoPin = 2;
const int trigPin = 3;
const int pirPin = 4;
int pirState = LOW;
const int buzzer = 8;
const int redLed = 9;
const int greenLed = 10;
float duration_us, distance_cm;
void setup() {
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
pinMode(pirPin,INPUT);
pinMode(buzzer,OUTPUT);
pinMode(redLed,OUTPUT);
pinMode(greenLed,OUTPUT);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration_us = pulseIn(echoPin, HIGH);
distance_cm = 0.017 * duration_us;
pirState = digitalRead(pirPin);
if (pirState == HIGH) {
Serial.println("Motion Detected!");
if (distance_cm <= 20){
digitalWrite(buzzer, HIGH);
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, LOW);
tone(8, 250, 250);
}
else if(distance_cm > 20){
digitalWrite(buzzer, HIGH);
digitalWrite(redLed, LOW);
digitalWrite(greenLed, LOW);
tone(8, 250, 250);
}
delay(500);
}
if (pirState == LOW) {
Serial.println("NO Motion!");
if (distance_cm >= 20 && distance_cm <= 50){
digitalWrite(buzzer, LOW);
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, HIGH);
}
delay(500);
}
}