#include <Servo.h>
const int ultrasonicTrigPin = 9;
const int ultrasonicEchoPin = 10;
const int pirPin = 8;
const int servoPin = 7;
const int ledPin = 6;
const int buzzerPin = 5;
Servo myservo;
long duration;
int distance;
void setup() {
pinMode(ultrasonicTrigPin, OUTPUT);
pinMode(ultrasonicEchoPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
myservo.attach(servoPin);
Serial.begin(9600);
}
void loop() {
// Read distance from ultrasonic sensor
digitalWrite(ultrasonicTrigPin, LOW);
delayMicroseconds(2);
digitalWrite(ultrasonicTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(ultrasonicTrigPin, LOW);
duration = pulseIn(ultrasonicEchoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Move the servo motor to lock/unlock the door
if (distance < 10) {
myservo.write(90); // Unlock the door
} else {
myservo.write(0); // Lock the door
}
// Read motion from PIR sensor
int pirValue = digitalRead(pirPin);
// Turn on/off the light based on the motion value
if (pirValue == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// Sound the buzzer if there is motion detected and the door is closed
if (pirValue == HIGH && distance < 10) {
digitalWrite(buzzerPin, HIGH);
delay(500);
digitalWrite(buzzerPin, LOW);
delay(500);
}
delay(500);
}