This project shows how to use a RFID reader with Arduino, by showing how to read the embedded id inside some magnetic smartcards and smarttags.
The MFRC522 library is used. To include it in your project, just add
#include "SPI.h"
#include "MFRC522.h"
to the header of your project.
The following hardware was used:
- A MF522-AN RFID scanner.
- An Arduino Mega 2560.
- A LCD 1602 keypad shield.
There are some important sections for the MFRC library that need to be addressed.
At the top of your code, the following pin mapping has to be added:
#define SS_PIN 53
#define RST_PIN 49
#define SP_PIN 50
MFRC522 rfid(SS_PIN, RST_PIN);
And the following pins need to be connected from the Arduino Mega to the RFID scanner:
- MISO - Pin 50 - SP_PIN.
- SCK - Pin 52.
- SS - Pin 53 - SS_PIN.
- MOSI - Pin 51.
- GND - GND.
- 3.3V - 3.3V or 5V if the 3.3V is in use.
- RST - Pin 49 - RST_PIN.
To initialize the library, just add in your setup() the following:
void setup() {
Serial.begin(9600);
SPI.begin();
}
Note: This project prints the tag id to the serial port where the Arduino is connected. If you want to use a different port or different baudrate, change the port and baudrate in the previous code.
In the loop(), we have
void loop() {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
return;
...
}
This code keeps waiting until a smarttag is read by the RFID scanner. When this happens, it continues with the rest of the code:
void loop() {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial())
return;
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
// Check is the PICC of Classic MIFARE type
if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
Serial.println(F("Your tag is not of type MIFARE Classic."));
return;
}
String strID = "";
for (byte i = 0; i < 4; i++) {
strID +=
(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +
String(rfid.uid.uidByte[i], HEX) +
(i!=3 ? ":" : "");
}
strID.toUpperCase();
Serial.print("Tap card key: ");
Serial.println(strID);
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
}
Here, the id is print to serial port in
Serial.print("Tap card key: ");
Serial.println(strID);
so if you want to print to a different port, change Serial for your new port and remember to initialize it in the setup().
After implementing this code and connecting the RFID scanner to the Arduino Mega, we can read the tag ids of different smartcards in serial monitor.