CODE
#include <SPI.h>
#include
#include
MFRC522 rfid(10, 9); // D10: pin of tag reader SDA. D9: pin of tag reader RST
unsigned char status;
unsigned char str[18]; // Maximum length of UID supported by MFRC522 library is 18 bytes
String accessGranted[2] = {"cee4e13f", "a1c1e21b"}; // RFID serial numbers to grant access to
int accessGrantedSize = 2; // The number of serial numbers
Servo lockServo; // Servo for locking mechanism
int lockPos = 0; // Locked position limit
int unlockPos = 90; // Unlocked position limit
boolean locked = true;
int redLEDPin = 5;
int greenLEDPin = 6;
void setup()
{
Serial.begin(9600); // Serial monitor is only required to get tag ID numbers and for troubleshooting
SPI.begin(); // Start SPI communication with reader
rfid.PCD_Init(); // initialization
pinMode(redLEDPin, OUTPUT); // LED startup sequence
pinMode(greenLEDPin, OUTPUT);
digitalWrite(redLEDPin, HIGH);
delay(200);
digitalWrite(greenLEDPin, HIGH);
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
digitalWrite(greenLEDPin, LOW);
lockServo.attach(3);
lockServo.write(lockPos); // Move servo into locked position
Serial.println("Place card/tag near reader...");
}
void loop()
{
if (rfid.PICC_IsNewCardPresent()) // Wait for a tag to be placed near the reader
{
if (rfid.PICC_ReadCardSerial()) // Anti-collision detection, read tag serial number
{
String temp = ""; // Temporary variable to store the read RFID number
Serial.print("The card's ID number is : ");
for (int i = 0; i < 4; i++) // Record and display the tag serial number
{
temp += String(rfid.uid.uidByte[i], HEX);
}
Serial.println(temp);
checkAccess(temp); // Check if the identified tag is an allowed to open tag
}
}
}
void checkAccess(String temp) // Function to check if an identified tag is registered to allow access
{
boolean granted = false;
for (int i = 0; i < accessGrantedSize; i++) // Runs through all tag ID numbers registered in the array
{
if (accessGranted[i] == temp) // If a tag is found then open/close the lock
{
Serial.println("Access Granted");
granted = true;
if (locked) // If the lock is closed then open it
{
lockServo.write(unlockPos);
locked = false;
}
else // If the lock is open then close it
{
lockServo.write(lockPos);
locked = true;
}
digitalWrite(greenLEDPin, HIGH); // Green LED sequence
delay(200);
digitalWrite(greenLEDPin, LOW);
delay(200);
digitalWrite(greenLEDPin, HIGH);
delay(200);
digitalWrite(greenLEDPin, LOW);
delay(200);
}
}
if (!granted) // If the tag is not found
{
Serial.println("Access Denied");
digitalWrite(redLEDPin, HIGH); // Red LED sequence
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
digitalWrite(redLEDPin, HIGH);
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
}
}
