Arduino RFID with the RC522: read cards and open a door (wiring, code and live simulator)
The RC522 is a 13.56 MHz RFID reader that talks to an Arduino over SPI: four bus wires (SDA, SCK, MOSI, MISO), a reset wire, and 3.3 V power. The Arduino asks the reader whether a card is in its field, reads the card's UID and compares it with a list of allowed cards: a known card lights a green LED, any other a red one. On a MIFARE Classic card the sketch also counts the visits in the card's own memory. Try it below with a virtual card and key fob before you wire anything.
Run it in your browser (free simulator)
Press ▶ Simulate in the box above. Nothing to install and no account needed. Open it in the workbench to change it (free account).
Press Simulate
The Uno starts the sketch, resets the reader and reads its version register. The serial console prints "RC522 ready" and "Lay a card on the reader".
Hold the card to the reader
Press "Hold to reader" on the white card (in the workbench you can also drag the card onto the reader's antenna). The console prints the card's UID (B4 1E 7A 2C), its type, the visit number, and "Access granted"; the green LED lights for a second.
Try the key fob
Press "Take away" on the card, then "Hold to reader" on the blue key fob. Its UID is not in the allowed list, so the console says "Access denied" and the red LED lights.
Show the card again
Take the fob away and hold the card to the reader once more: the visit number goes up by one. The count is written to block 4 of the card itself, so the card remembers it, not the Arduino.
What you need
- An Arduino Uno (or Nano) and its USB cable
- An RC522 RFID module (the common blue board) with the white card and the key fob it usually comes with
- A green LED, a red LED and two 220 ohm resistors
- 7 female-to-male jumper wires for the reader, a breadboard and a few jumpers for the LEDs
- Arduino IDE (the sketch needs only the built-in SPI library)
Careful: The RC522 is a 3.3 V part. Power it from the Arduino 3.3V pin, never from 5V. Its signal pins take the Uno's 5 V logic in practice, but a 5 V supply on its 3.3V pin destroys it.
Wiring: Arduino Uno and RC522
The reader sits on the Uno's hardware SPI pins (D11, D12, D13), which are fixed. SDA (the chip select) and RST can be any free pins; the code uses D10 and D9. The two LEDs show the result.
| From | To | Why |
|---|---|---|
| RC522 SDA (SS) | Arduino D10 | Chip select: LOW while the Arduino talks to the reader |
| RC522 SCK | Arduino D13 | SPI clock |
| RC522 MOSI | Arduino D11 | Data from the Arduino to the reader |
| RC522 MISO | Arduino D12 | Data from the reader to the Arduino |
| RC522 IRQ | not connected | The code polls the reader, so the interrupt pin is not needed |
| RC522 GND | Arduino GND | Ground |
| RC522 RST | Arduino D9 | Reset: the code pulses it at start-up |
| RC522 3.3V | Arduino 3.3V | Power, 3.3 V only |
| Arduino D7 | 220 Ω, then green LED anode; cathode to GND | Access granted |
| Arduino D6 | 220 Ω, then red LED anode; cathode to GND | Access denied |
On an Arduino Mega the SPI pins are D50 (MISO), D51 (MOSI) and D52 (SCK); SDA and RST stay on D10 and D9. Keep the reader wires short: long jumpers on SPI are the most common reason the reader is not found.
How the code works
The sketch drives the RC522 register by register over SPI, which is exactly what the MFRC522 library does inside. Every register access is one SPI transfer with the register address shifted left (and the top bit set for a read) while SDA is held LOW. setup() pulses RST, sends a soft reset, sets the reader's timer to 25 ms so it gives up when no card answers, and switches the antenna on.
loop() sends a REQA command: any card in the field that has not been read yet answers. Then it runs the anticollision and select steps of ISO 14443 A, which return the UID (4 bytes for a MIFARE Classic, 7 for an NTAG). The UID is compared with the ALLOWED list at the top of the sketch: add your own card's UID there, as printed on the console.
On a MIFARE Classic 1K card the sketch also authenticates sector 1 with the factory key (FF FF FF FF FF FF), reads block 4, adds one to a counter stored in its first four bytes and writes it back. Finally it halts the card, so the same card is not read again until it is taken away and laid on again.
If you prefer the library, install MFRC522 by GithubCommunity and use rfid.PCD_Init(), rfid.PICC_IsNewCardPresent() and rfid.PICC_ReadCardSerial(); the wiring stays the same.
Put it on the real Arduino
Solder the header
Most RC522 boards come with a loose 8-pin header. Solder it on: a reader pushed onto bare holes makes contact only now and then.
Wire it as in the table
Seven wires to the reader, with 3.3V on 3.3V. Add the two LEDs with their resistors on D7 and D6.
Upload and open the Serial Monitor
Paste the code below into a new sketch, upload it and open the Serial Monitor at 9600 baud. It should print the chip version (0x91 or 0x92 on most boards).
Add your card
Hold your card to the reader and copy the UID the console prints into the ALLOWED list at the top of the sketch, as four hex bytes. Upload again: now your card opens the "door".
The code (Arduino C++)
This is the Arduino sketch for the real Uno, using only the built-in SPI library. The simulator runs the same code.
Show the code (268 lines)
#include <SPI.h>
// RC522 RFID door: lay a card or the key fob on the reader's antenna (drag it onto the reader, or "Hold to the reader" in its
// settings). The UID is printed; a known card switches the green LED on (access granted), any other the red one. On a
// MIFARE Classic card the program opens sector 1 with the factory key and counts the visits in block 4, so the card itself
// remembers how often it was shown. Take the card away and lay it on again to read it once more.
//
// The reader is driven register by register here (the same steps as the MFRC522 library, which you can use instead:
// #include <MFRC522.h>, MFRC522 rfid(10, 9); rfid.PCD_Init(); rfid.PICC_IsNewCardPresent(); rfid.PICC_ReadCardSerial(); ...).
//
// Wiring: SDA (SS) D10, SCK D13, MOSI D11, MISO D12, RST D9, 3.3V to 3V3 (not 5V!), GND to GND.
const byte SS_PIN = 10, RST_PIN = 9, GREEN = 7, RED = 6;
// the cards that may open the door
const byte ALLOWED[][4] = { { 0xB4, 0x1E, 0x7A, 0x2C } };
const byte KEY_A[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; // the key of a new card
// MFRC522 registers and commands
enum { CommandReg = 0x01, ComIrqReg = 0x04, DivIrqReg = 0x05, ErrorReg = 0x06, Status2Reg = 0x08, FIFODataReg = 0x09,
FIFOLevelReg = 0x0A, ControlReg = 0x0C, BitFramingReg = 0x0D, CollReg = 0x0E, ModeReg = 0x11, TxModeReg = 0x12,
RxModeReg = 0x13, TxControlReg = 0x14, TxASKReg = 0x15, CRCResultRegH = 0x21, CRCResultRegL = 0x22, ModWidthReg = 0x24,
TModeReg = 0x2A, TPrescalerReg = 0x2B, TReloadRegH = 0x2C, TReloadRegL = 0x2D, VersionReg = 0x37 };
enum { PCD_Idle = 0x00, PCD_CalcCRC = 0x03, PCD_Transceive = 0x0C, PCD_MFAuthent = 0x0E, PCD_SoftReset = 0x0F };
enum { OK, TIMEOUT, ERR, COLLISION, NAK };
byte uid[10], uidLen, sak, lastBits;
void writeReg(byte reg, byte v) {
digitalWrite(SS_PIN, LOW);
SPI.transfer(reg << 1);
SPI.transfer(v);
digitalWrite(SS_PIN, HIGH);
}
void writeFifo(const byte *d, byte n) {
digitalWrite(SS_PIN, LOW);
SPI.transfer(FIFODataReg << 1);
for (byte i = 0; i < n; i++) SPI.transfer(d[i]);
digitalWrite(SS_PIN, HIGH);
}
byte readReg(byte reg) {
digitalWrite(SS_PIN, LOW);
SPI.transfer(0x80 | (reg << 1));
byte v = SPI.transfer(0);
digitalWrite(SS_PIN, HIGH);
return v;
}
void setBits(byte reg, byte mask) { writeReg(reg, readReg(reg) | mask); }
void clearBits(byte reg, byte mask) { writeReg(reg, readReg(reg) & ~mask); }
// The chip computes the CRC_A the cards expect at the end of their frames.
bool calcCrc(const byte *d, byte n, byte *out) {
writeReg(CommandReg, PCD_Idle);
writeReg(DivIrqReg, 0x04);
writeReg(FIFOLevelReg, 0x80);
writeFifo(d, n);
writeReg(CommandReg, PCD_CalcCRC);
for (word i = 5000; i > 0; i--) {
if (readReg(DivIrqReg) & 0x04) {
writeReg(CommandReg, PCD_Idle);
out[0] = readReg(CRCResultRegL);
out[1] = readReg(CRCResultRegH);
return true;
}
}
return false;
}
// Sends `send` to the card (`txBits` bits of its last byte, 0 = all) and waits for the answer, or for the 25 ms timer
// when no card answers. The answer goes to `back` (at most *backLen bytes); lastBits = valid bits of its last byte.
byte transceive(byte cmd, const byte *send, byte sendLen, byte *back, byte *backLen, byte txBits = 0, byte waitIrq = 0x30) {
writeReg(CommandReg, PCD_Idle);
writeReg(ComIrqReg, 0x7F);
writeReg(FIFOLevelReg, 0x80);
writeFifo(send, sendLen);
writeReg(BitFramingReg, txBits);
writeReg(CommandReg, cmd);
if (cmd == PCD_Transceive) setBits(BitFramingReg, 0x80); // StartSend
unsigned long until = millis() + 36;
byte irq;
do {
irq = readReg(ComIrqReg);
if (irq & waitIrq) break;
if (irq & 0x01) return TIMEOUT;
} while (millis() < until);
if (!(irq & waitIrq)) return TIMEOUT;
byte err = readReg(ErrorReg);
if (err & 0x13) return ERR; // buffer overflow, parity or protocol error
if (back) {
byte n = readReg(FIFOLevelReg);
if (n > *backLen) return ERR;
*backLen = n;
for (byte i = 0; i < n; i++) back[i] = readReg(FIFODataReg);
lastBits = readReg(ControlReg) & 0x07;
}
return (err & 0x08) ? COLLISION : OK;
}
void rc522Begin() {
pinMode(SS_PIN, OUTPUT);
digitalWrite(SS_PIN, HIGH);
pinMode(RST_PIN, OUTPUT); // a pulse on RST: a hard reset
digitalWrite(RST_PIN, LOW);
delayMicroseconds(2);
digitalWrite(RST_PIN, HIGH);
delay(50);
writeReg(CommandReg, PCD_SoftReset);
delay(50);
while (readReg(CommandReg) & 0x10) {}
writeReg(TxModeReg, 0x00);
writeReg(RxModeReg, 0x00);
writeReg(ModWidthReg, 0x26);
writeReg(TModeReg, 0x80); // the timer starts at the end of every frame sent: 25 ms to answer
writeReg(TPrescalerReg, 0xA9);
writeReg(TReloadRegH, 0x03);
writeReg(TReloadRegL, 0xE8);
writeReg(TxASKReg, 0x40);
writeReg(ModeReg, 0x3D); // CRC preset 0x6363 (ISO 14443 A)
setBits(TxControlReg, 0x03); // antenna on
}
// REQA: a card in the field that has not been read yet answers with its ATQA.
bool cardPresent() {
clearBits(CollReg, 0x80);
byte req = 0x26, atqa[2], n = 2;
byte s = transceive(PCD_Transceive, &req, 1, atqa, &n, 7);
return (s == OK && n == 2 && lastBits == 0) || s == COLLISION;
}
// Anticollision and select, one cascade level for a 4-byte UID, two for a 7-byte one.
byte selectCard() {
uidLen = 0;
for (byte level = 0; level < 2; level++) {
byte buf[9] = { (byte)(level ? 0x95 : 0x93), 0x20 };
byte n = 5;
byte s = transceive(PCD_Transceive, buf, 2, buf + 2, &n);
if (s != OK) return s; // COLLISION: two cards lie on the reader
if (n != 5 || (buf[2] ^ buf[3] ^ buf[4] ^ buf[5]) != buf[6]) return ERR;
buf[1] = 0x70;
if (!calcCrc(buf, 7, buf + 7)) return TIMEOUT;
byte resp[3];
n = 3;
s = transceive(PCD_Transceive, buf, 9, resp, &n);
if (s != OK) return s;
if (n != 3) return ERR;
sak = resp[0];
if (buf[2] == 0x88) { memcpy(uid + uidLen, buf + 3, 3); uidLen += 3; } // the cascade tag: more of the UID follows
else { memcpy(uid + uidLen, buf + 2, 4); uidLen += 4; }
if (!(sak & 0x04)) return OK;
}
return ERR;
}
byte authenticate(byte block, const byte *key) {
byte d[12] = { 0x60, block }; // 0x60: key A
memcpy(d + 2, key, 6);
memcpy(d + 8, uid + uidLen - 4, 4);
return transceive(PCD_MFAuthent, d, 12, 0, 0, 0, 0x10);
}
byte readBlock(byte block, byte *out) { // out: 18 bytes (16 + CRC)
byte cmd[4] = { 0x30, block };
if (!calcCrc(cmd, 2, cmd + 2)) return TIMEOUT;
byte n = 18;
byte s = transceive(PCD_Transceive, cmd, 4, out, &n);
if (s != OK) return s;
if (n == 1 && lastBits == 4) return NAK;
if (n != 18) return ERR;
byte crc[2];
if (!calcCrc(out, 16, crc) || crc[0] != out[16] || crc[1] != out[17]) return ERR;
return OK;
}
byte sendWithAck(const byte *d, byte len) {
byte buf[18];
memcpy(buf, d, len);
if (!calcCrc(buf, len, buf + len)) return TIMEOUT;
byte ack, n = 1;
byte s = transceive(PCD_Transceive, buf, len + 2, &ack, &n);
if (s != OK) return s;
return (n == 1 && lastBits == 4 && (ack & 0x0F) == 0x0A) ? OK : NAK;
}
byte writeBlock(byte block, const byte *data) {
byte cmd[2] = { 0xA0, block };
byte s = sendWithAck(cmd, 2);
return s == OK ? sendWithAck(data, 16) : s;
}
// HLTA: the card stays quiet until it is taken away; then the cipher is switched off.
void haltCard() {
byte cmd[4] = { 0x50, 0x00 };
calcCrc(cmd, 2, cmd + 2);
transceive(PCD_Transceive, cmd, 4, 0, 0);
clearBits(Status2Reg, 0x08);
}
// Block 4 (sector 1) keeps a visit counter on the card.
void countVisit() {
byte block[18];
if (authenticate(4, KEY_A) != OK) { Serial.println(F("Sector 1: wrong key")); return; }
if (readBlock(4, block) != OK) { Serial.println(F("Could not read block 4")); return; }
unsigned long visits = block[0] | ((unsigned long)block[1] << 8) | ((unsigned long)block[2] << 16) | ((unsigned long)block[3] << 24);
visits++;
for (byte i = 0; i < 4; i++) block[i] = visits >> (8 * i);
if (writeBlock(4, block) != OK) { Serial.println(F("Could not write block 4")); return; }
Serial.print(F("Visit #"));
Serial.println(visits);
}
bool allowed() {
if (uidLen != 4) return false;
for (byte c = 0; c < sizeof(ALLOWED) / 4; c++)
if (memcmp(uid, ALLOWED[c], 4) == 0) return true;
return false;
}
void setup() {
Serial.begin(9600);
pinMode(GREEN, OUTPUT);
pinMode(RED, OUTPUT);
SPI.begin();
SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
rc522Begin();
byte v = readReg(VersionReg);
if (v == 0x00 || v == 0xFF) {
Serial.println(F("No RC522 found: check the wiring and 3.3V"));
} else {
Serial.print(F("RC522 ready, chip version 0x"));
Serial.println(v, HEX);
}
Serial.println(F("Lay a card on the reader"));
}
void loop() {
if (!cardPresent()) {
delay(50);
return;
}
byte s = selectCard();
if (s == COLLISION) {
Serial.println(F("Two cards on the reader: one at a time, please"));
delay(500);
return;
}
if (s != OK) return;
Serial.print(F("Card UID:"));
for (byte i = 0; i < uidLen; i++) {
Serial.print(uid[i] < 0x10 ? F(" 0") : F(" "));
Serial.print(uid[i], HEX);
}
Serial.println();
Serial.print(F("Type: "));
Serial.println(sak == 0x08 ? F("MIFARE Classic 1K") : sak == 0x00 ? F("NTAG / Ultralight") : F("other"));
if (sak == 0x08) countVisit();
bool ok = allowed();
Serial.println(ok ? F("Access granted") : F("Access denied"));
digitalWrite(ok ? GREEN : RED, HIGH);
haltCard();
delay(1000);
digitalWrite(GREEN, LOW);
digitalWrite(RED, LOW);
Serial.println();
}
Troubleshooting
- The console says "No RC522 found"
- The Arduino reads 0x00 or 0xFF from the version register, so SPI does not reach the reader. Check 3.3V and GND, then SDA on D10, SCK on D13, MOSI on D11 and MISO on D12 (MOSI and MISO are the ones most often swapped), and the soldering of the header.
- The reader is found but no card is ever read
- Hold the card flat on the antenna (the side with the coil printed on it), within 2 or 3 cm. Check RST on D9. Metal under the reader or a card inside a wallet with other cards blocks it.
- "Two cards on the reader"
- Two cards answered at once. Take one away: the RC522 reads one card at a time in this sketch.
- "Sector 1: wrong key"
- The card is not new and its key A was changed, or it is not a MIFARE Classic card. The UID and the access check still work; only the visit counter needs the factory key.
- My phone or bank card shows a UID that changes every time
- Phones and many bank cards send a random UID on each read for privacy. Use a plain MIFARE card or tag for access control.
Frequently asked questions
Does the RC522 work with 5 V Arduinos?
Yes, with its power on the 3.3V pin. Its SPI inputs tolerate the Uno's 5 V signals in practice and its outputs (3.3 V) are read as HIGH by the Uno. Never connect its supply pin to 5V.
Which cards does the RC522 read?
ISO 14443 A cards at 13.56 MHz: MIFARE Classic 1K and 4K, MIFARE Ultralight, NTAG213/215/216 stickers and tags. It does not read 125 kHz cards (EM4100 key fobs), which need a different reader.
Is the UID enough for security?
For a hobby door or a toy, yes. A UID can be copied to special "magic" cards, so for anything that matters use cards with real cryptography (MIFARE DESFire) and keep the reader and the lock inside.
How far does the RC522 read?
About 2 to 5 cm with the small antenna on the board, depending on the card size. Big cards read further than small tags.
Do I need the MFRC522 library?
No. This sketch talks to the reader with the built-in SPI library only, so you can see each step. The library does the same and is easier to use in bigger projects.
Can I try this without the hardware?
Yes. The simulator on this page runs the same sketch on a virtual Uno with a virtual RC522, a card and a key fob, for free in your browser. The card even keeps what the sketch writes to it while the page is open.
Embed this circuit on your own page
Copy this code into your blog, tutorial or course page. Visitors can run the circuit right there.
<iframe src="https://voltbench.click/embed/gallery/arduino-rfid-rc522-door-lock" width="100%" height="560" style="border:1px solid #2a3140;border-radius:8px" loading="lazy" allowfullscreen title="Arduino RFID with the RC522: read cards and open a door"></iframe>
Build your own version
Open this circuit in the VoltBench workbench, change the wiring or the code, and run it. When it works, flash a real board. Free to use.