#include <Servo.h>
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, pin connected to RST of MFRC522
#define SS_PIN 10 // Configurable, pin connected to SDA of MFRC522
#define SERVO_PIN 3 // Servo control pin
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
Servo myServo; // Create Servo object
// Define a known RFID UID (you can find your RFID tag's UID using the serial monitor)
byte knownUID[] = {0xDE, 0xAD, 0xBE, 0xEF}; // Replace with your card's UID
void setup() {
Serial.begin(9600); // Initialize serial communications
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
myServo.attach(SERVO_PIN); // Attach the servo to pin
myServo.write(0); // Initialize servo to 0 degrees
Serial.println("Place your RFID card near the reader...");
}
void loop() {
// Look for a card
if (!mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if (!mfrc522.PICC_ReadCardSerial()) {
return;
}
// Show UID on serial monitor
Serial.print("Card UID: ");
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.println();
// Check if the card UID matches the known UID
if (compareUID(mfrc522.uid.uidByte, knownUID, mfrc522.uid.size)) {
Serial.println("Access granted!");
myServo.write(90); // Rotate servo to 90 degrees (open door)
delay(3000); // Hold for 3 seconds
myServo.write(0); // Rotate servo back to 0 degrees (close door)
} else {
Serial.println("Access denied!");
}
// Halt PICC to stop further communication
mfrc522.PICC_HaltA();
}
// Function to compare two UIDs
bool compareUID(byte *uid1, byte *uid2, byte size) {
for (byte i = 0; i < size; i++) {
if (uid1[i] != uid2[i]) {
return false;
}
}
return true;
}