#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
Servo myservo; // create servo object to control a servo
// Define the angles for the servo motor rotation
#define ANGLE_OPEN 90
#define ANGLE_CLOSE 0
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
myservo.attach(3); // attaches the servo on pin 3 to the servo object
myservo.write(ANGLE_CLOSE); // Close the servo initially
delay(500); // Give some time for servo to reach the initial position
}
void loop() {
// Look for new cards
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
// Show some details of the PICC (Card)
Serial.print("Card UID: ");
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
// Check if the detected card UID matches with the expected UID
if (checkUID(mfrc522.uid.uidByte, mfrc522.uid.size)) {
Serial.println("Access Granted!");
// Open the servo
myservo.write(ANGLE_OPEN);
delay(2000); // Keep the servo open for 2 seconds
// Close the servo
myservo.write(ANGLE_CLOSE);
} else {
Serial.println("Access Denied!");
}
}
mfrc522.PICC_HaltA(); // Halt PICC
delay(1000); // Pause for 1 second before next scan
}
// Helper function to print a byte array as a hex string
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
// Function to compare the detected UID with the expected UID
bool checkUID(byte uid[], byte uidSize) {
// Replace this with your expected UID
byte expectedUID[] = {0xAB, 0xCD, 0xEF, 0x12};
// Check if the sizes match
if (uidSize != sizeof(expectedUID)) {
return false;
}
// Check each byte of the UID
for (int i = 0; i < uidSize; i++) {
if (uid[i] != expectedUID[i]) {
return false;
}
}
return true;
}