Skip to content

RC522 Module Integration

RC522 Module Integration

This section covers the software integration of the MFRC522 library with the ESP32, including library installation, SPI initialization, and basic communication verification. Learning this section will enable you to:

  • Install the MFRC522 library for Arduino/PlatformIO
  • Initialize the RC522 module via SPI in ESP32 code
  • Verify communication between ESP32 and RC522
  • Understand the library’s object model and key functions

Before starting this section, ensure you have:

  • Hardware wiring completed per 05-02
  • Arduino IDE or PlatformIO IDE set up (see Chapter 01)
  • Basic sketch template (WiFi + MQTT) from Chapter 01
  • RC522 module properly connected to ESP32

The MFRC522 library by Miguel Balboa is the most widely used Arduino library for the RC522 RFID module. It provides:

  • Full SPI communication handling
  • Tag detection and UID reading
  • MIFARE card read/write operations
  • Built-in helper functions for common operations

Library Details:

PropertyValue
Library NameMFRC522
AuthorMiguel Balboa
RepositoryGitHub - miguelbalboa/MFRC522
LicenseLGPL-2.1
Last Updated2024 (actively maintained)

The ESP32 communicates with the RC522 over the SPI (Serial Peripheral Interface) bus:

SPI Communication Path:
┌─────────┐ ┌─────────┐
│ ESP32 │ │ RC522 │
│ │ MOSI (GPIO 23)──→│ │
│ Master │←──MISO (GPIO 19) │ Slave │
│ │ SCK (GPIO 18)──→│ │
│ │ SS (GPIO 5)───→│ │
└─────────┘ └─────────┘
  • MOSI: Master Out, Slave In (ESP32 sends commands to RC522)
  • MISO: Master In, Slave Out (RC522 responds to ESP32)
  • SCK: Serial Clock (synchronizes data transfer)
  • SS: Slave Select (selects RC522 for communication)

PlatformIO Method:

Add to platformio.ini:

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps =
miguelbalboa/MFRC522 @ ^1.4.11
pubsubclient

Arduino IDE Method:

Sketch → Include Library → Manage Libraries
Search: "MFRC522" by Miguel Balboa
Click "Install" (version 1.4.11 or later)

Create a new sketch with the MFRC522 library included:

#include <SPI.h>
#include <MFRC522.h>
// RC522 Pin Definitions
#define RST_PIN 4 // Reset pin
#define SS_PIN 5 // Slave Select (SDA) pin
// Create MFRC522 instance
MFRC522 rfid(SS_PIN, RST_PIN);
// LED Pin Definitions
#define LED_GREEN 22
#define LED_RED 21

Code Explanation:

  • SS_PIN (GPIO 5) matches the SDA/SS wire from Step 2
  • RST_PIN (GPIO 4) is the hardware reset for the module
  • The MFRC522 object is instantiated with these two pins
  • LED pins are defined for visual feedback (used later)
void setup() {
Serial.begin(115200);
// Initialize LED pins
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
// Initialize SPI bus
SPI.begin(); // SCK=18, MOSI=23, MISO=19 (ESP32 default)
// Initialize MFRC522
rfid.PCD_Init();
// Verify module is responding
rfid.PCD_DumpVersionToSerial();
Serial.println("RFID Reader ready.");
// Initial LED test
digitalWrite(LED_GREEN, HIGH);
delay(500);
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, HIGH);
delay(500);
digitalWrite(LED_RED, LOW);
}

Expected Serial Output:

RFID Reader ready.
Firmware Version: 0x92 (2.0) ← or similar version number

⚠️ Important: If the firmware version returns 0x00 or 0xFF, the SPI wiring is incorrect or the module is not responding.

Here is a complete minimal sketch to verify RC522 communication:

#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 4
#define SS_PIN 5
MFRC522 rfid(SS_PIN, RST_PIN);
#define LED_GREEN 22
#define LED_RED 21
void setup() {
Serial.begin(115200);
while (!Serial); // Wait for Serial (Leonardo/Micro only)
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
SPI.begin(); // Initialize SPI
rfid.PCD_Init(); // Initialize RFID
Serial.print("RFID Firmware Version: 0x");
Serial.println(rfid.PCD_ReadRegister(MFRC522::VersionReg), HEX);
if (rfid.PCD_ReadRegister(MFRC522::VersionReg) == 0x00 ||
rfid.PCD_ReadRegister(MFRC522::VersionReg) == 0xFF) {
Serial.println("ERROR: RFID module not responding!");
digitalWrite(LED_RED, HIGH); // Red LED = error
while (1); // Halt
}
Serial.println("RFID Reader ready.");
digitalWrite(LED_GREEN, HIGH); // Green LED = ready
}
void loop() {
// Check for new RFID tags
if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
Serial.print("Tag detected! UID: ");
String uid = "";
for (byte i = 0; i < rfid.uid.size; i++) {
uid += String(rfid.uid.uidByte[i], HEX);
}
uid.toUpperCase();
Serial.println(uid);
// Flash green LED on tag detection
digitalWrite(LED_GREEN, LOW);
delay(100);
digitalWrite(LED_GREEN, HIGH);
// Halt PICC and stop encryption
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
delay(1000); // Avoid multiple reads of same tag
}
}
FunctionDescriptionWhen to Use
PCD_Init()Initialize the RC522 moduleOnce in setup()
PICC_IsNewCardPresent()Check if a new tag is near the readerIn loop() before reading
PICC_ReadCardSerial()Read the tag’s UIDAfter PICC_IsNewCardPresent() returns true
PICC_HaltA()Stop communication with current tagAfter reading UID
PCD_StopCrypto1()Stop encryption on the PCDAfter read/write operations
PCD_DumpVersionToSerial()Print firmware version to SerialFor debugging/verification
PCD_SetAntennaGain()Adjust antenna sensitivityTo increase or decrease read range
// rfid.uid is a struct containing:
struct MFRC522::Uid {
byte size; // Number of bytes in UID (4 or 7)
byte uidByte[10]; // The UID bytes
byte sak; // Select Acknowledge byte
};
  • 4-byte UID: Standard MIFARE classic tags
  • 7-byte UID: Extended UID for newer tags (NXP NTAG, MIFARE Ultralight)

Upload the verification sketch and test:

// Expected Serial Monitor Output:
// RFID Firmware Version: 0x92
// RFID Reader ready.
// Tag detected! UID: 04A3B2C1
// Tag detected! UID: E5F81234

Physical Test:

  1. Open Serial Monitor (115200 baud)
  2. Hold an RFID tag close to the RC522 antenna (~3cm)
  3. Observe the UID printed in the Serial Monitor
  4. The green LED should flash briefly on each tag detection
  5. Test with multiple tags to verify different UIDs

Symptom: Serial shows Firmware Version: 0x00 or 0xFF

Causes:

  • SPI wiring incorrect
  • Module not powered
  • Module damaged

Solution:

// Check each SPI connection:
// 1. Verify 3.3V on RC522 VCC pin using multimeter
// 2. Verify GND continuity between ESP32 and RC522
// 3. Swap MOSI and MISO if using non-standard pinout
// 4. Try a different RC522 module

Issue 2: “PICC_IsNewCardPresent” Always Returns False

Section titled “Issue 2: “PICC_IsNewCardPresent” Always Returns False”

Symptom: Tags never detected

Causes:

  • Tag is not 13.56 MHz (e.g., using 125 kHz tag)
  • Read distance too far (>5cm)
  • Antenna damaged

Solution:

  1. Verify tag type (should say “13.56 MHz” or “MIFARE”)
  2. Bring tag very close (almost touching the antenna)
  3. Check antenna coil on RC522 for visible damage

Symptom: Holding a tag steady causes continuous repeated reads

Solution: Add a delay and detection state:

bool tagRecentlyRead = false;
unsigned long lastReadTime = 0;
void loop() {
if (millis() - lastReadTime > 2000) { // 2 second cooldown
tagRecentlyRead = false;
}
if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
if (!tagRecentlyRead) {
// Process tag
tagRecentlyRead = true;
lastReadTime = millis();
}
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
}
}
  • Recommended: Always call PICC_HaltA() after reading to prevent continuous re-read
  • Recommended: Use the PCD_SetAntennaGain(MFRC522::RxGain_max) for maximum range
  • Recommended: Verify firmware version at startup to detect wiring issues early
  • Avoid: Reading tags faster than 2-3 reads per second (may cause SPI buffer overflow)
  • Avoid: Using very long (>30cm) SPI wires, which can cause communication errors
  1. Library: Use MFRC522 by Miguel Balboa — the standard Arduino library for RC522
  2. Initialization: Start SPI bus, then call PCD_Init() — always verify firmware version
  3. Detection: Use PICC_IsNewCardPresent() + PICC_ReadCardSerial() in loop
  4. UID Format: 4-byte or 7-byte identifier, accessible via rfid.uid.uidByte[]
  5. Debugging: Firmware version 0x00 or 0xFF indicates wiring issue

Writing Date: 2026-05-17
Based on Source File: 校正版/10 Time recording witht RFID und TimeTagger.md
Target Audience: Alibaba.com IoT Pre-sales Engineer
Status: ✅ Completed