#include <LiquidCrystal.h>
#include <Servo.h>
#include <Keypad.h>
#define PIR_PIN 0
#define BUZZER_PIN 1
#define BUTTON_PIN 4
#define SERVO_PIN 6
#define KEYPAD_PIN A0
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2};
byte colPins[COLS] = {A3, A2, A1, A0};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
Servo servoMotor;
enum SystemState {
ID,
MOTION_DETECTED,
ENTER_PASSCODE,
DOOR_OPENED,
DOOR_CLOSED
};
SystemState currentState = ID;
bool personInside = false;
void setup() {
pinMode(PIR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
lcd.begin(16, 2);
servoMotor.attach(SERVO_PIN);
}
void loop() {
switch(currentState) {
case ID:
handleIdleState();
break;
case MOTION_DETECTED:
handleMotionDetectedState();
break;
case ENTER_PASSCODE:
handleEnterPasscodeState();
break;
case DOOR_OPENED:
handleDoorOpenedState();
break;
case DOOR_CLOSED:
handleDoorClosedState();
break;
}
}
void handleIdleState() {
bool motionDetected = digitalRead(PIR_PIN);
if (motionDetected) {
tone(BUZZER_PIN, 1000, 1000); // تنشيط الإنذار عند اكتشاف حركة
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Motion detected");
currentState = MOTION_DETECTED;
} else {
deactivateAlarm();
lcd.clear();
lcd.print("No motion detected");
}
delay(500);
}
void handleMotionDetectedState() {
char key = keypad.getKey();
if (key == '#') {
lcd.clear();
lcd.print("Enter passcode:");
currentState = ENTER_PASSCODE;
}
delay(500);
}
void handleEnterPasscodeState() {
char key = keypad.getKey();
if (key) {
if (key == '#') {
personInside = true;
openDoor();
lcd.clear();
lcd.print("Door opened");
lcd.setCursor(0, 1);
lcd.print("Welcome!");
delay(5000);
currentState = DOOR_OPENED;
}
}
}
void handleDoorOpenedState() {
bool buttonPressed = digitalRead(BUTTON_PIN);
if (buttonPressed && personInside) {
personInside = false;
closeDoor();
lcd.clear();
lcd.print("Door closed");
delay(2000);
currentState = DOOR_CLOSED;
}
delay(500);
}
void handleDoorClosedState() {
currentState = ID;
}
void deactivateAlarm() {
noTone(BUZZER_PIN);
}
void openDoor() {
servoMotor.write(90);
}
void closeDoor() {
servoMotor.write(0);
}