Site icon AranaCorp

Using a RFID module with Arduino

The RFID module is a smart card reader which allows among others, to activate a mechanism when the correct card is presented to the reader. We will use here the RC522 module, which is the most common.

Hardware

Scheme

The RFID RC522 module uses the SPI protocol to communicate with Arduino. SPI communication uses specific Boche of Arduino.Le microcontroller pin is as follows (left side RC522, right side Arduino UNO):  
– Vcc (Power) <-> 3V3 (or 5V depending on the module) 
– RST (Reset) <-> 9  
– GND (Ground) <-> GND  
– MISO (Master Input Slave Output) <-> 12
– MOSI (Master Output Slave Input) <-> 11 
– SCK (Serial Clock) <-> 13  
– SS/SDA (slave select) <-> 10
The RFID module must be connected as shown below.

Warning: Depending on the module version, the power voltage may be different (3.3V or 5V). Check the module datasheet to power the module correctly.

Code

To use the subject RFID module we use SPI and MFRC522 libraries that are used as follows

#include <SPI.h>
#include <MFRC522.h>

// INPUT
#define SS_PIN 10
#define RST_PIN 9
 
MFRC522 rfid(SS_PIN, RST_PIN);

// Init array that will store new NUID
byte nuidPICC[4];

void setup() {
 Serial.begin(9600);
 SPI.begin(); // Init SPI bus
 rfid.PCD_Init(); // Init MFRC522
 
 Serial.println(F("Scan RFID NUID..."));
}

void loop() {
      readRFID();
      delay(200);
}

//
void readRFID()
{ 
  // Look for new card
  if ( ! rfid.PICC_IsNewCardPresent()) 
  return;

    // Verify if the NUID has been readed
  if (  !rfid.PICC_ReadCardSerial())
  return;
  
  if (rfid.uid.uidByte[0] != nuidPICC[0] || 
    rfid.uid.uidByte[1] != nuidPICC[1] || 
    rfid.uid.uidByte[2] != nuidPICC[2] || 
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }
   
    Serial.print(F("RFID tag in dec: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
   
  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}


/**
 * Helper routine to dump a byte array as dec values to Serial.
 */
void printDec(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], DEC);
  }
}

 

Applications

Sources

Find other examples and tutorials in our Automatic code generator
Code Architect

Exit mobile version