Learn to code

ARDUINO & CODES

Previous Post
Create multiple proximity buttons with MPR121 for Arduino
Next Post
Create a Marble Maze / Labyrinth for Arduino

RFID door Lock with multiple RFID readers for Arduino

in Arduino Project

In this project tutorial, you will use the multiple MFRC522 to control a solenoid lock and three LEDs. The MFRC522 uses Radio Frequence Identification (RFID). RFID uses electromagnetic fields to identify and track tags attached to an object. These tags contain electronic stored information. If the tag is placed in front of the reader the reader read the tags. A benefit of RFID is that it does not require to be in line of sight of the reader. In other words, you can attach the reader behind material and it will still read the tag. The distance with cheaper readers is around 5cm. So if the tag is placed within that distance the reader will read the tag. In this tutorial, you will learn how to connect two mfrc522 readers to an Arduino Uno and detect if the tags are placed at the right reader.

MFRC522 RFID 

The RFID-RC522 module is an RFID reader, which can read RFID tags in close-range. In order to read an RFID tag, the reader and the tag must have the same frequency. The RFID-RC522 module reads only High frequency tags at 13.56 MHz. The voltage that the MFRC522 can handle is 3.3V. So, be catious when you connect a power line from the breadboard to it. The reader can read tags from to a maximum distance of 5cm.

Parts you will need

Circuit Diagram

Prepare The BreadBoard

Connect power and ground on the breadboard to power and ground from the microcontroller. On the Arduino Uno, use the 3.3V. Toy will use the power rails on the breadboard to power the MFRC522 RFID readers. These readers can handle up to 3V. Therefore, do not use the 5V to power the RFID readers since that can damage the readers.

The Arduino Uno’s 5V output pin is connected to the relay module. Don’t forget to also connect the GND tot the relay module.

How to connect the MFRC522

RFID-RC522 PIN ARDUINO UNO PIN
dadas10
SCK13
MOSI11
MISO12
IRQUNUSED
GNDGND
RST9
3.3V 3.3V

The RFID-RC522 module comes with eight pins (of which seven pins are used in this tutorial). In the following, the pin layout is shown as recommended by the documentation of the MFRC522 library (used later in the programming section). The RFID-RC522 module runs with 3.3V. Therefore, the module’s 3.3V pin must be connected to the Arduino’s 3.3V. The module might get damaged, if it is accidentally connected to the Arduino’s 5V pin. The complete pin layout is shown by the following table (works only for the Arduino Uno! Mega, Nano etc. have different recommended pin layouts!):

The Code

/**
* This codes enables you to read multiple rfid readers to
* turn a LED on. If both readers detect the right tag 
* the two leds will light up. 
*
* http://www.arduinoplatform.com
*/

#include <SPI.h>
// Download and install from https://github.com/miguelbalboa/rfid
#include <MFRC522.h>

// CONSTANTS
// The number of RFID readers
const byte numReaders = 2;
// Each reader has a unique Slave Select pin
const byte ssPins[] = {2, 3};
// They'll share the same reset pin
const byte resetPin = 8;
// The correct IDs should be changed by you!!!
// The sequence of NFC tag IDs required to unlock the Solenoid Lock
const String correctIDs[] = {"3944c98" , "79404498"};
// Pins that are connected to the LEDs
int pin_LED[] = {5, 6};
int pinRFID = 7;
int lockpin = A0;

// GLOBALS
// Initialise an array of MFRC522 instances representing each reader
MFRC522 mfrc522[numReaders];
// The tag IDs currently detected by each reader
String currentIDs[numReaders];


/**
   Initialisation
*/
void setup() {

#ifdef DEBUG
  // Initialise serial communications channel with the PC
  Serial.begin(9600);
  Serial.println(F("Serial communication started"));
#endif


  // set all LED pins to an output mode
  pinMode(pinRFID, OUTPUT);
  pinMode(lockpin, OUTPUT);
  for (int y = 0; y < numReaders; y++) {
    pinMode(pin_LED[y], OUTPUT);
  }

  // Initialise the SPI bus
  SPI.begin();

  for (uint8_t i = 0; i < numReaders; i++) { // Initialise the reader // Note that SPI pins on the reader must always be connected to certain // Arduino pins (on an Uno, MOSI=> pin11, MISO=> pin12, SCK=>pin13)
    // The Slave Select (SS) pin and reset pin can be assigned to any pin
    mfrc522[i].PCD_Init(ssPins[i], resetPin);

    // Set the gain to max - not sure this makes any difference...
    // mfrc522[i].PCD_SetAntennaGain(MFRC522::PCD_RxGain::RxGain_max);

#ifdef DEBUG
    // Dump some debug information to the serial monitor
    Serial.print(F("Reader #"));
    Serial.print(i);
    Serial.print(F(" initialised on pin "));
    Serial.print(String(ssPins[i]));
    Serial.print(F(". Antenna strength: "));
    Serial.print(mfrc522[i].PCD_GetAntennaGain());
    Serial.print(F(". Version : "));
    mfrc522[i].PCD_DumpVersionToSerial();
#endif

    // Slight delay before activating next reader
    delay(100);
  }

#ifdef DEBUG
  Serial.println(F("--- END SETUP ---"));
#endif
}

/**
   Main loop
*/
void loop() {

  // Assume that the rfids tags are at the right readers
  boolean rfidSolved = true;

  // Assume that the tags have not changed since last reading
  boolean changedValue = false;

  // Loop through each reader
  for (uint8_t i = 0; i < numReaders; i++) {

    // Initialise the sensor
    mfrc522[i].PCD_Init();

    // String to hold the ID detected by each sensor
    String readRFID = "";

    // If the sensor detects a tag and is able to read it
    if (mfrc522[i].PICC_IsNewCardPresent() && mfrc522[i].PICC_ReadCardSerial()) {
      // Extract the ID from the tag
      readRFID = dump_byte_array(mfrc522[i].uid.uidByte, mfrc522[i].uid.size);
    }

    // If the current reading is different from the last known reading
    if (readRFID != currentIDs[i]) {
      // Set the flag to show that the rfid state has changed
      changedValue = true;
      // Update the stored value for this sensor
      currentIDs[i] = readRFID;
    }

    // If the reading fails to match the correct ID for this sensor
    if (currentIDs[i] != correctIDs[i]) {
      digitalWrite(pin_LED[i], LOW);
      digitalWrite(pinRFID, LOW);
      digitalWrite(lockpin, HIGH);
      // The tags are not placed correct.
      rfidSolved = false;
    }

    // If the reading is correct with corresponding ID
    if (currentIDs[i] == correctIDs[i]) {
      //turn on led

      digitalWrite(pin_LED[i], HIGH);

    }

    // Halt PICC
    mfrc522[i].PICC_HaltA();
    // Stop encryption on PCD
    mfrc522[i].PCD_StopCrypto1();
  }

#ifdef DEBUG
  // If the changedValue flag has been set, at least one sensor has changed
  if (changedValue) {
    // Dump to serial the current state of all sensors
    for (uint8_t i = 0; i < numReaders; i++) {
      Serial.print(F("Reader #"));
      Serial.print(String(i));
      Serial.print(F(" on Pin #"));
      Serial.print(String((ssPins[i])));
      Serial.print(F(" detected tag: "));
      Serial.println(currentIDs[i]);
    }
    Serial.println(F("---"));
  }
#endif

  // If the rfidSolved flag is set, all sensors detected the correct ID
  if (rfidSolved) {
#ifdef DEBUG
    // Print debugging message
    Serial.println(F("RFID Solved!"));
#endif

    digitalWrite(pinRFID, HIGH);
    digitalWrite(lockpin, LOW);

    delay(7000);
    rfidSolved = false;
  }

}

/**
   Helper function to return a string ID from byte array
*/
String dump_byte_array(byte *buffer, byte bufferSize) {
  String read_rfid = "";
  for (byte i = 0; i < bufferSize; i++) {
    read_rfid = read_rfid + String(buffer[i], HEX);
  }
  return read_rfid;
}
 

Code Explanation

Import the MFRC522 Library

To use the servo library, you’ll first need to import it. This makes the additions from the library available to your sketch. The code makes use of an existing RFID library which can be found here: https://github.com/miguelbalboa/rfid. If you are using the Arduino IDE, the library can be easily installed by clicking “Sketch->Include Library->Manage Libraries”. Then, search for “RFID” and you will find an entry with the title “MFRC522 by GithubCommunity”. If you cannot find such an entry, I recommend to visit the official website of the library for further assistance.

#include <SPI.h>
// Download and install from https://github.com/miguelbalboa/rfid
#include <MFRC522.h>
Create constant variables

The constants in this tutorial allows you to read an RFID reader and light up the corresponding LED. The constant numReaders is used to define the number of RFID readers connected to the Arduino Board. Every reader has a unique slave pin and shares a reset pin. We declare a string variable for the Correct IDs of the tags. Furthermore, two int variables are created for the pins that are connected to the three LEDs used in the tutorial.

// CONSTANTS
// The number of RFID readers
const byte numReaders = 2;
// Each reader has a unique Slave Select pin
const byte ssPins[] = {2, 3};
// They'll share the same reset pin
const byte resetPin = 8;
// The sequence of NFC tag IDs required to solve the puzzle
const String correctIDs[] = {"3944c98" , "79404498"};
// Pins that are connected to the LEDs
int pin_LED[] = {5, 6};
int pinRFID = 7;

 

Declare global variabels
The global variables in this tutorial are used for the number of readers and the the TAG ID that is detected by the reader.
 
// GLOBALS
// Initialise an array of MFRC522 instances representing each reader
MFRC522 mfrc522[numReaders];
// The tag IDs currently detected by each reader
String currentIDs[numReaders];
Void setup() part

In our void setup part we set all LEDs to an output mode and start Serial Communication. Furhermore, a loop is created to initialize all the readers and print some debug information to the Serial Monitor.

void setup() {
 
  #ifdef DEBUG
  // Initialise serial communications channel with the PC
  Serial.begin(9600);
  Serial.println(F("Serial communication started"));
  #endif
  
  
   // set all LED pins to an output mode
  pinMode(pinRFID, OUTPUT);
  for(int y=0; y<numReaders; y++){
    pinMode(pin_LED[y], OUTPUT);
   }
  
  // Initialise the SPI bus
  SPI.begin();
 
  for (uint8_t i=0; i<numReaders; i++) { // Initialise the reader // Note that SPI pins on the reader must always be connected to certain // Arduino pins (on an Uno, MOSI=> pin11, MISO=> pin12, SCK=>pin13)
    // The Slave Select (SS) pin and reset pin can be assigned to any pin
    mfrc522[i].PCD_Init(ssPins[i], resetPin);
    
    // Set the gain to max - not sure this makes any difference...
    // mfrc522[i].PCD_SetAntennaGain(MFRC522::PCD_RxGain::RxGain_max);
    
	#ifdef DEBUG
    // Dump some debug information to the serial monitor
    Serial.print(F("Reader #"));
    Serial.print(i);
    Serial.print(F(" initialised on pin "));
    Serial.print(String(ssPins[i]));
    Serial.print(F(". Antenna strength: "));
    Serial.print(mfrc522[i].PCD_GetAntennaGain());
    Serial.print(F(". Version : "));
    mfrc522[i].PCD_DumpVersionToSerial();
	#endif
    
    // Slight delay before activating next reader
    delay(100);
  }
  
  #ifdef DEBUG
  Serial.println(F("--- END SETUP ---"));
  #endif
}

Reading the RFID readers

You arrived at the part of the sketch where the tags will be read by the MFRC522 readers. Firstly, we assume that the tags are in the correct place and that there has not been any change in the last reading. The loop functions ensure that all the readers are read. It will “remember” the ID that is detected by the sensor. There are a couple of if statements that allow us to detect whether the tag is removed or places at a reader and if the reading is correct. If the right tag is placed at the right RFID reader a LED will light up.

// Assume that the rfids tags are at the right readers
  boolean rfidSolved = true;
 
  // Assume that the tags have not changed since last reading
  boolean changedValue = false;
 
  // Loop through each reader
  for (uint8_t i=0; i<numReaders; i++) {
 
    // Initialise the sensor
    mfrc522[i].PCD_Init();
    
    // String to hold the ID detected by each sensor
    String readRFID = "";
    
    // If the sensor detects a tag and is able to read it
    if(mfrc522[i].PICC_IsNewCardPresent() && mfrc522[i].PICC_ReadCardSerial()) {
      // Extract the ID from the tag
      readRFID = dump_byte_array(mfrc522[i].uid.uidByte, mfrc522[i].uid.size);
    }
    
    // If the current reading is different from the last known reading
    if(readRFID != currentIDs[i]){
      // Set the flag to show that the rfid state has changed
      changedValue = true;
      // Update the stored value for this sensor
      currentIDs[i] = readRFID;
    }
    
    // If the reading fails to match the correct ID for this sensor 
    if(currentIDs[i] != correctIDs[i]) {
      digitalWrite(pin_LED[i], LOW);
      digitalWrite(pinRFID, LOW);
      // The tags are not placed correct.
      rfidSolved = false;
    }
 
     // If the reading is correct with corresponding ID
    if(currentIDs[i] == correctIDs[i]) {
     //turn on led
     Serial.println(F("turn on LED"));
     digitalWrite(pin_LED[i], HIGH);
 
    }
 
    // Halt PICC
    mfrc522[i].PICC_HaltA();
    // Stop encryption on PCD
    mfrc522[i].PCD_StopCrypto1(); 
  }
Tags are in the correct place

You arrived at the part of sketch where the tags will be read by the MFRC522 readers. Firstly, we assume that the tags are in the correct place and that there has not been anay change in the last reading. The loop functions ensures that all the readers are read. It will “remember” the ID that is detected by the sensor. There are a couple of if statements that allow us to detect whether the tag is removed or places at a reader and if the reading is correct. If the right tag is placed at the right rfid reader a LED will light up.

// Assume that the rfids tags are at the right readers
  boolean rfidSolved = true;
 
  // Assume that the tags have not changed since last reading
  boolean changedValue = false;
 
  // Loop through each reader
  for (uint8_t i=0; i<numReaders; i++) {
 
    // Initialise the sensor
    mfrc522[i].PCD_Init();
    
    // String to hold the ID detected by each sensor
    String readRFID = "";
    
    // If the sensor detects a tag and is able to read it
    if(mfrc522[i].PICC_IsNewCardPresent() && mfrc522[i].PICC_ReadCardSerial()) {
      // Extract the ID from the tag
      readRFID = dump_byte_array(mfrc522[i].uid.uidByte, mfrc522[i].uid.size);
    }
    
    // If the current reading is different from the last known reading
    if(readRFID != currentIDs[i]){
      // Set the flag to show that the rfid state has changed
      changedValue = true;
      // Update the stored value for this sensor
      currentIDs[i] = readRFID;
    }
    
    // If the reading fails to match the correct ID for this sensor 
    if(currentIDs[i] != correctIDs[i]) {
      digitalWrite(pin_LED[i], LOW);
      digitalWrite(pinRFID, LOW);
      // The tags are not placed correct.
      rfidSolved = false;
    }
 
     // If the reading is correct with corresponding ID
    if(currentIDs[i] == correctIDs[i]) {
     //turn on led
     Serial.println(F("turn on LED"));
     digitalWrite(pin_LED[i], HIGH);
 
    }
 
    // Halt PICC
    mfrc522[i].PICC_HaltA();
    // Stop encryption on PCD
    mfrc522[i].PCD_StopCrypto1(); 
  }

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu