#include <SPI.h>
#include <MFRC522.h>
#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define SS_PIN 5
#define RST_PIN 22
#define PIR_PIN 27
#define BUZZER 2
#define SERVO_PIN 4
MFRC522 mfrc522(SS_PIN, RST_PIN);
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo myServo;
String correctUID = "A1B2C3D4"; // Replace with your card UID
String correctPIN = "1234";
String enteredPIN = "";
// Keypad Setup
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] = {13, 12, 14, 26};
byte colPins[COLS] = {25, 33, 32, 15};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
Serial.begin(115200);
SPI.begin();
mfrc522.PCD_Init();
pinMode(PIR_PIN, INPUT);
pinMode(BUZZER, OUTPUT);
myServo.attach(SERVO_PIN);
myServo.write(0); // Lock position
lcd.init();
lcd.backlight();
lcd.print("Security System");
delay(2000);
lcd.clear();
}
void loop() {
if (digitalRead(PIR_PIN) == HIGH) {
lcd.setCursor(0,0);
lcd.print("Scan Card/PIN");
checkRFID();
checkKeypad();
}
}
void checkRFID() {
if (!mfrc522.PICC_IsNewCardPresent()) return;
if (!mfrc522.PICC_ReadCardSerial()) return;
String uidStr = "";
for (byte i = 0; i < mfrc522.uid.size; i++) {
uidStr += String(mfrc522.uid.uidByte[i], HEX);
}
uidStr.toUpperCase();
if (uidStr == correctUID) {
grantAccess();
} else {
denyAccess();
}
}
void checkKeypad() {
char key = keypad.getKey();
if (key) {
if (key == '#') {
if (enteredPIN == correctPIN) {
grantAccess();
} else {
denyAccess();
}
enteredPIN = "";
} else {
enteredPIN += key;
}
}
}
void grantAccess() {
lcd.clear();
lcd.print("Access Granted");
myServo.write(90); // Unlock
delay(5000);
myServo.write(0); // Lock
lcd.clear();
}
void denyAccess() {
lcd.clear();
lcd.print("Access Denied");
digitalWrite(BUZZER, HIGH);
delay(2000);
digitalWrite(BUZZER, LOW);
lcd.clear();
}