Arduino RC522 RFID Reader Module Tutorial - How RFID Module Works and Interfacing It With Arduino
Arduino RC522 RFID Reader Module Tutorial - How RFID Module Works and Interfacing It With Arduino
Published
Published May 18, 2022 !0
Have you ever wondered how the antitheft system in a supermarket works? Or how do automatic toll payment systems like
fast tag work? All the answer to your doubts is RFID or Radio Frequency Identification. As the name indicates, RFID uses
electromagnetic waves in the radio frequency spectrum for communication and data transfer. RFID tags are used in many
industries and you can find them in product tags from stores to security access cards. RFID tags can expedite the checkout
and can be used for antitheft measures. They can be also used for identifying livestock, products, etc. In this tutorial, we will
learn how we can use
use the
the RFID
RFID technology
technology with
with the
the Arduino
Arduino. We will learn how to interface
interface an
an RC522
RC522 RFID
RFID reader
reader
with
with the
the Arduino
Arduino.
:
RC522 RFID Reader/Writer Module Pinout
The RC522 module has a total of 8 pins. This module supports various communication protocols and each pin has a different
function for each communication protocol. The pinout
pinout of
of aa RFID
RFID Reader
Reader module
module is as follows:
SS SCK MOSI MISO SPI communication pins. Slave Select, Clock, MOSI, and MISO.
IRQ Interrupt signal from the module to indicate RFID tag detection.
GND Ground pin that needs to be connected to the GND pin on the Arduino.
The RFID reader consists of an antenna to emit high-frequency EM waves and a reader/writer. MFRC522 from NXP is an
example of such an integrated circuit. Since we are using high-frequency waves in the megahertz range, the size of the
antenna can be small.
:
The RFID tag can be either passive or active. Active tags are powered by batteries while the passive RFID tags are powered by
energy from the reader’s interrogating EM waves. The tags are available in different forms or shapes like cards, tags, key forbs,
or stickers. Whatever the shape, the RFID tag will consist of an antenna and the RFID chip, which will store all the data. When
triggered by an electromagnetic interrogation pulse from a nearby RFID reader, the tag will transmit data back to the reader.
The reader will then analyze this data to identify the tag. Unlike a barcode or a QR code, the tag does not need to be within the
reader’s line of sight. This makes it easier to process and can be used for tracking objects in closed space.
RFID tags are a type of tracking system that uses radiofrequency to search, identify, track, and communicate with items and
people.
How
How is
is RFID
RFID used
used in
in healthcare?
healthcare?
RFID helps to mitigate drug counterfeiting, simplifies the clinical trial process, improves the accuracy of patient identification,
eases inventory management, streamlines patient tracking, improves communications between caregivers and patients, and
eradicates the risk of administering the wrong medications.
Can
Can Wi-Fi
Wi-Fi interfere
interfere with
with RFID?
RFID?
:
Interference from other radio-frequency (RF) emitting devices (RFI), such as other RFID readers and Wi-Fi access points, can
negatively impact RFID system performance.
SPI
SPI with Speed up to 10Mbit/s
I2C
I2C interface with speed up to 400kBd in Fast mode and up to 3400kBd in High-Speed mode
:
RS232
RS232 Serial
Serial UART
UART with speed up to 1228.8kBd
The RC522 module usually comes with an RFID card and a key fob. And each of these comes with a 1KB of memory. We can
not only read these tags but can also program these with the RC522 module. Here is the picture showing the tags along with
the RC522 module.
Once the library is installed, we can test our setup with an example code. For that, open the DumpInfo
DumpInfo example from the
MFRC522 library. Here is the example code.
:
#include <SPI.h>
#include <MFRC522.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
void setup() {
Serial.begin(115200); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
delay(4); // Optional delay. Some board do need more time after init to be
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}
void loop() {
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
Once it’s compiled and uploaded to the Arduino, open the serial monitor and show any tag near the RC522 module. When the
tag is in the vicinity, the reader will read all the data from the tag and will dump it into the serial monitor as shown below.
:
The data dump will contain all the details like Card UID, Card SAK, PICC type, and all the memory maps. The UID or Unique ID
is Unique for each tag as the name suggests. If you get any communication failed error, that’s because our serial baud rate is
too slow. Increase the baud rate to 115200 in the code and it will resolve the issue. Here in the data dump, we can see that the
PICC type is MIFARE 1KB. That means the tag contains a MIFARE chip with a memory of 1KB.
Once the code is compiled and uploaded, open the serial monitor. Then scan a tag with the module. The module will write two
data to the tag and will read back once it’s written. This data will be then printed to the serial monitor. See the screenshot
below.
:
Code Explanation
In the first lines, we have included the necessary libraries and defined
defined the reset
reset and SS
SS pins. Since we are using the SPI
protocol, we have included the SPI library and then the MFRC522 library for the RFID reader. The reset and SS pins can be
connected to any other digital pin. The users may change it at their convenience.
void setup()
{
Serial.begin(115200); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
Serial.println("Scan a MIFARE Classic card");
for (byte i = 0; i < 6; i++)
{
key.keyByte[i] = 0xFF; // Prepare the security key for the read and write operations.
}
}
The function we are using to write data to the tag is the writeblock
writeblock function. When this function is called, it will check if the
provided block number corresponds to the data block or the trailer block. The trailer block will hold the Access Bit which
controls the read and write access to the reaming blocks. Block number 3 is the trailer block. If the provided block number
does not correspond to a data block, the function will return an error message. If it’s a data block, the function will
authenticate the tag with a security key and if the authentication is successful, the data will be written to the corresponding
block.
For reading data from the tag, we are using the readBlock
readBlock function. It is similar to the write function. Once the function is
called, it will determine the trailer block for the sector and then it will authenticate. If the authentication is successful, the
function will read the data from the tag.
:
int readBlock(int blockNumber, byte arrayAddress[])
{
int largestModulo4Number = blockNumber / 4 * 4;
int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector
//authentication of the desired block for access
byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print("Authentication failed : ");
Serial.println(mfrc522.GetStatusCodeName(status));
return 3;//return "3" as error message
}
//reading data from the block
byte buffersize = 18;
status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable; MIFA
if (status != MFRC522::STATUS_OK) {
Serial.print("Data read failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return 4;//return "4" as error message
}
Serial.println("Data read successfully");
}
In the loop
loop function, the microcontroller will check if a tag is present or not periodically. If a tag is present and readable, the
function will write two data arrays to the tag, and then it will read back and printed to the serial monitor.
void loop()
{
// Look for new cards if not found rerun the loop function
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// read from the card if not found rerun the loop function
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
Serial.println("card detected. Writing data");
writeBlock(1, data1); //write data1 to the block 1 of the tag
writeBlock(2, data2); //write data2 to the block 2 of the tag
Serial.println("reading data from the tag");
readBlock(1, readbackblock); //read block 1
//print data
Serial.print("read block 1: ");
for (int j = 0 ; j < 14 ; j++)
{
Serial.write (readbackblock[j]);
}
Serial.println("");
readBlock(2, readbackblock); //read block 2
//print data
Serial.print("read block 2: ");
for (int j = 0 ; j < 12 ; j++)
{
Serial.write (readbackblock[j]);
}
Serial.println("");
//mfrc522.PICC_DumpToSerial(&(mfrc522.uid));//uncomment below line if want to see the entire memory dump.
}
Code Explanation
At first, we have included all the necessary libraries, declared the global variables, and created an instance for the RFID
library.
:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED 8
byte readCard[4];
String tag_UID = "39C3BB99"; // Replace this with the UID of your tag!!!
String tagID = "";
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
Here the LED pin is connected to the Arduino pin D8. The tag_UID
tag_UID is unique for each tag and replace it with your own tag’s
UID. You can get the UID by using the Dumpinfo example.
In the setup()
setup() function, we have initialized the pin D8 as an output and set its initial state to LOW. And then initialized the SPI
bus and the MFRC522 instance.
void setup()
{
pinMode(LED, OUTPUT);// initialize digital pin LED_BUILTIN as an output.
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
SPI.begin(); // SPI bus
mfrc522.PCD_Init(); // Initialise MFRC522
}
boolean readID()
{
//Check if a new tag is detected or not. If not return.
if ( ! mfrc522.PICC_IsNewCardPresent()
{
return false;
}
//Check if a new tag is readable or not. If not return.
if ( ! mfrc522.PICC_ReadCardSerial())
{
return false;
}
tagID = "";
// Read the 4 byte UID
for ( uint8_t i = 0; i < 4; i++)
{
//readCard[i] = mfrc522.uid.uidByte[i];
tagID.concat(String(mfrc522.uid.uidByte[i], HEX)); // Convert the UID to a single String
}
tagID.toUpperCase();
mfrc522.PICC_HaltA(); // Stop reading
return true;
}
In the loop
loop function, the Arduino will check for a valid tag reading periodically. If it receives a valid tag reading the read UID
matches with the UID we have declared earlier, the LED state will be toggled.
:
void loop()
{
//Wait until new tag is available
while (readID())
{
if (tagID == tag_UID)
{
digitalWrite(LED, !digitalRead(LED)); // Turn on or off the onboard led
}
}
}
Supporting Files
(https://github.com/Circuit-Digest/Basic-Arduino-Tutorials-for-Beginners-
/tree/main/Interfacing%20RFID%20Reader%20With%20Arduino)
(https://github.com/Circuit-Digest/Basic-Arduino-Tutorials-for-Beginners-/archive/refs/heads/main.zip )
Code
LED Control
:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED 8
byte readCard[4];
String tag_UID = "39C3BB99"; // Replace this with the UID of your tag!!!
String tagID = "";
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
void setup()
{
pinMode(LED, OUTPUT);// initialize digital pin LED_BUILTIN as an output.
digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW
SPI.begin(); // SPI bus
mfrc522.PCD_Init(); // Initialise MFRC522
}
void loop()
{
//Wait until new tag is available
while (readID())
{
if (tagID == tag_UID)
{
digitalWrite(LED, !digitalRead(LED)); // Turn on or off the onboard led
}
}
}
//Read new tag if available
boolean readID()
{
//Check if a new tag is detected or not. If not return.
if ( ! mfrc522.PICC_IsNewCardPresent())
Tags
RFID (/Tags/Rfid)
(Https://Chat.whatsapp.com/JR4e0Fc0V20H6jTMDd1daT)
Log in (/user/login?destination=/microcontroller-projects/interfacing-rfid-reader-module-with-arduino%23comment-form)
or register (/user/register?destination=/microcontroller-projects/interfacing-rfid-reader-module-with-
arduino%23comment-form) to post comments
:
ADP2230 Mixed Signal Oscilloscope (MSO) (https://bit.ly/4cowLzQ )
Digilent's ADP2230 MSO allows users to measure, visualize, generate, record, and control circuits.
(https://bit.ly/4cowLzQ )
(https://bit.ly/4eHQcoV )
(https://bit.ly/45IflvL )
(https://bit.ly/3R5kpUL )
(https://bit.ly/3VUjEkP )
(https://bit.ly/3xHSuUr )
(https://bit.ly/3KlhxPP )
(https://bit.ly/453b0D5 )
:
JJooiinn 10
1 0 00K
K
K+++ SSuubbssc
c ri
r ib
b eer
errs
s
Your email is safe with us, we don’t spam.
(https://www.facebook.com/circuitdigest/) (https://twitter.com/CircuitDigest)
(https://www.youtube.com/channel/UCy3CUAIYgZdAOG9k3IPdLmw) (https://www.linkedin.com/company/circuit-
digest/)
COMPANY
COMPANY
Privacy Policy (/privacy-policy) Cookie Policy (/cookie-policy) Terms of Use (/terms-of-use) Contact
PROJECT
PROJECT
555 Timer Circuits (/555-timer-circuits) Op-amp Circuits (/op-amp-circuits) Audio Circuits (/audio-
OUR
OUR NETWORK
NETWORK
(https://circuitdigest.com)
:
(https://components101.com)
(https://iotdesignpro.com)