RC522 Module Integration
RC522 Module Integration
Overview
Section titled “Overview”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
Prerequisites
Section titled “Prerequisites”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
Key Concepts
Section titled “Key Concepts”MFRC522 Library
Section titled “MFRC522 Library”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:
| Property | Value |
|---|---|
| Library Name | MFRC522 |
| Author | Miguel Balboa |
| Repository | GitHub - miguelbalboa/MFRC522 |
| License | LGPL-2.1 |
| Last Updated | 2024 (actively maintained) |
SPI Communication Overview
Section titled “SPI Communication Overview”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)
Implementation Steps
Section titled “Implementation Steps”Step 1: Install MFRC522 Library
Section titled “Step 1: Install MFRC522 Library”PlatformIO Method:
Add to platformio.ini:
[env:esp32dev]platform = espressif32board = esp32devframework = arduinolib_deps = miguelbalboa/MFRC522 @ ^1.4.11 pubsubclientArduino IDE Method:
Sketch → Include Library → Manage LibrariesSearch: "MFRC522" by Miguel BalboaClick "Install" (version 1.4.11 or later)Step 2: Include Library and Define Pins
Section titled “Step 2: Include Library and Define Pins”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 instanceMFRC522 rfid(SS_PIN, RST_PIN);
// LED Pin Definitions#define LED_GREEN 22#define LED_RED 21Code Explanation:
SS_PIN(GPIO 5) matches the SDA/SS wire from Step 2RST_PIN(GPIO 4) is the hardware reset for the module- The
MFRC522object is instantiated with these two pins - LED pins are defined for visual feedback (used later)
Step 3: Initialize SPI and RC522 in Setup
Section titled “Step 3: Initialize SPI and RC522 in Setup”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.
Step 4: Complete Verification Sketch
Section titled “Step 4: Complete Verification Sketch”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 }}Library API Reference
Section titled “Library API Reference”Key MFRC522 Functions
Section titled “Key MFRC522 Functions”| Function | Description | When to Use |
|---|---|---|
PCD_Init() | Initialize the RC522 module | Once in setup() |
PICC_IsNewCardPresent() | Check if a new tag is near the reader | In loop() before reading |
PICC_ReadCardSerial() | Read the tag’s UID | After PICC_IsNewCardPresent() returns true |
PICC_HaltA() | Stop communication with current tag | After reading UID |
PCD_StopCrypto1() | Stop encryption on the PCD | After read/write operations |
PCD_DumpVersionToSerial() | Print firmware version to Serial | For debugging/verification |
PCD_SetAntennaGain() | Adjust antenna sensitivity | To increase or decrease read range |
UID Data Structure
Section titled “UID Data Structure”// 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)
Verification
Section titled “Verification”Upload the verification sketch and test:
// Expected Serial Monitor Output:// RFID Firmware Version: 0x92// RFID Reader ready.// Tag detected! UID: 04A3B2C1// Tag detected! UID: E5F81234Physical Test:
- Open Serial Monitor (115200 baud)
- Hold an RFID tag close to the RC522 antenna (~3cm)
- Observe the UID printed in the Serial Monitor
- The green LED should flash briefly on each tag detection
- Test with multiple tags to verify different UIDs
Troubleshooting
Section titled “Troubleshooting”Issue 1: No Firmware Version
Section titled “Issue 1: No Firmware Version”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 moduleIssue 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:
- Verify tag type (should say “13.56 MHz” or “MIFARE”)
- Bring tag very close (almost touching the antenna)
- Check antenna coil on RC522 for visible damage
Issue 3: Same Tag Triggers Multiple Times
Section titled “Issue 3: Same Tag Triggers Multiple Times”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(); }}Best Practices
Section titled “Best Practices”- ✅ 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
Summary
Section titled “Summary”- Library: Use MFRC522 by Miguel Balboa — the standard Arduino library for RC522
- Initialization: Start SPI bus, then call
PCD_Init()— always verify firmware version - Detection: Use
PICC_IsNewCardPresent()+PICC_ReadCardSerial()in loop - UID Format: 4-byte or 7-byte identifier, accessible via
rfid.uid.uidByte[] - Debugging: Firmware version
0x00or0xFFindicates wiring issue
References
Section titled “References”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