RC522 RFID module with RFID card and key fob on a wooden table next to a Raspberry Pi 5

RFID RC522 on Raspberry Pi 5 — Current Guide (Without RPi.GPIO)

The RC522 is one of the most popular RFID modules for the Raspberry Pi — affordable, widely available, and used in countless projects. The problem: almost every tutorial online relies on RPi.GPIO, usually through the mfrc522 library from pip, and the original RPi.GPIO doesn’t run on the Raspberry Pi 5. This guide shows you how to get the RC522 working on the Pi 5 with spidev and gpiod instead — no RPi.GPIO required, on current Raspberry Pi OS.

TL;DR: Enable SPI → connect RC522 to SPI0 pins → use gpiod instead of RPi.GPIO → use the Python class from this guide. Takes about 20 minutes.

What is RFID — and what do you use the RC522 for?

RFID stands for Radio Frequency Identification — identification via radio. The RC522 operates at 13.56 MHz (High Frequency) and reads MIFARE-compatible cards and key fobs, as used in access control systems, libraries, and public transport.

Typical projects with the RC522:

  • Door opener and access control
  • Attendance tracking (school, office)
  • Authentication for projects instead of passwords
  • Time tracking and timesheets

The RC522 communicates via the SPI bus — which is why it requires special attention on the Pi 5 and why the old tutorials no longer work.

Why the original RPi.GPIO doesn’t work on the Raspberry Pi 5

The Pi 5 uses a new I/O controller: the RP1 southbridge chip. GPIO pins no longer run directly through the BCM2712 but through the RP1 — which is not compatible with the old RPi.GPIO library.

As a result, the original RPi.GPIO fails on the Pi 5. Older RFID libraries such as mfrc522 pull it in as a dependency when you install them with pip, for example inside a virtual environment. When you run them, you get:

RuntimeError: Cannot determine SOC peripheral base address

Current Raspberry Pi OS does ship python3-rpi-lgpio, a compatibility layer that emulates the RPi.GPIO API on top of lgpio. This guide doesn’t need it, though: it uses gpiod, the Linux kernel’s standard GPIO interface, and spidev for SPI communication. Both work on the Pi 5 and come straight from the official Raspberry Pi OS repositories.

More on GPIO alternatives for the Pi 5: Raspberry Pi 5 GPIO — RPi.GPIO Alternative.

Required hardware

ComponentNotesLink
Raspberry Pi 54 GB or 8 GB→ Amazon*
RC522 RFID moduleincl. RFID card and key fob→ Amazon*
Jumper wires (female-female)7 pieces needed→ Amazon*
Breadboard (optional)recommended for a clean setup→ Amazon*
Links marked with * are affiliate links, which makes them advertising. If you buy through one, I earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. Learn more

Important: The RC522 operates at 3.3 V. Never connect it to 5 V — the module will be permanently damaged.

Got a PN532 module instead of an RC522, or want to get by with just four wires? Check out PN532 on the Raspberry Pi 5: Read and Write NFC Cards.

Connecting the RC522 to the Raspberry Pi 5

The RC522 connects via the SPI0 bus. Use the following table for wiring:

RC522 PinPi 5 Pin (physical)GPIO (BCM)Function
VCCPin 13.3 V PowerPower supply (3.3 V)
GNDPin 6GroundGround
MOSIPin 19GPIO 10SPI Master Out
MISOPin 21GPIO 9SPI Master In
SCKPin 23GPIO 11SPI Clock
SDA (NSS)Pin 24GPIO 8SPI Chip Enable 0
RSTPin 22GPIO 25Reset
IRQ——not needed (leave open)
RC522 RFID module close-up showing the NXP MFRC522 chip, antenna coil and 8-pin header
RC522 RFID module — the NXP MFRC522 chip with antenna coil and 8-pin connector

For a full overview of all 40 GPIO pins, check the interactive GPIO Pinout Tool.

Enable SPI and install software

Enable SPI via raspi-config

SPI is disabled by default. Enable it with:

sudo raspi-config

Navigate to Interface Options → I4 SPI and confirm with Yes. Then reboot:

sudo reboot

After rebooting, verify that SPI is active:

ls /dev/spi*
# Expected output:
/dev/spidev0.0  /dev/spidev0.1

Install required packages

sudo apt update
sudo apt install python3-spidev python3-libgpiod -y

Both packages come directly from the Raspberry Pi OS repository — no pip, no external sources needed. python3-spidev handles SPI communication, python3-libgpiod provides GPIO access via the modern gpiod library. Current Raspberry Pi OS ships libgpiod 2.x, older images still 1.6 – the class below handles both.

Reading RFID tags — Python code for Pi 5

The following two files fully replace the old mfrc522 pip library. All code uses only spidev and gpiod — no RPi.GPIO dependency.

MFRC522 class for Pi 5 (spidev + gpiod)

Save the following file as mfrc522_pi5.py. The easiest way is the nano editor: open it with nano mfrc522_pi5.py, paste the code, press Ctrl+O and Enter to save, then Ctrl+X to exit.

import spidev
import gpiod
import time

class MFRC522:
    NRSTPD = 25  # RST pin (GPIO 25, physical pin 22)

    MAX_LEN = 16

    PCD_IDLE       = 0x00
    PCD_TRANSCEIVE = 0x0C
    PCD_RESETPHASE = 0x0F
    PCD_CALCCRC    = 0x03

    PICC_REQIDL    = 0x26
    PICC_REQALL    = 0x52
    PICC_ANTICOLL  = 0x93
    PICC_SELECTTAG = 0x93
    PICC_AUTHENT1A = 0x60
    PICC_READ      = 0x30
    PICC_WRITE     = 0xA0
    PICC_HALT      = 0x50

    MI_OK       = 0
    MI_NOTAGERR = 1
    MI_ERR      = 2

    Reserved00    = 0x00
    CommandReg    = 0x01
    CommIEnReg    = 0x02
    DivlEnReg     = 0x03
    CommIrqReg    = 0x04
    DivIrqReg     = 0x05
    ErrorReg      = 0x06
    Status1Reg    = 0x07
    Status2Reg    = 0x08
    FIFODataReg   = 0x09
    FIFOLevelReg  = 0x0A
    WaterLevelReg = 0x0B
    ControlReg    = 0x0C
    BitFramingReg = 0x0D
    CollReg       = 0x0E
    ModeReg       = 0x11
    TxControlReg  = 0x14
    TxASKReg      = 0x15
    CRCResultRegM = 0x21
    CRCResultRegL = 0x22
    TModeReg      = 0x2A
    TPrescalerReg = 0x2B
    TReloadRegH   = 0x2C
    TReloadRegL   = 0x2D

    def __init__(self):
        self.spi = spidev.SpiDev()
        self.spi.open(0, 0)
        self.spi.max_speed_hz = 1000000
        self.spi.mode = 0

        # RST pin via gpiod. The header GPIOs live on gpiochip0 on every
        # model (Pi 5 included) - only old Pi 5 images (before
        # autumn 2024) had them on gpiochip4.
        self._rst_open('/dev/gpiochip0')

        self.MFRC522_Init()

    def _rst_open(self, chip_path):
        """Claim the RST pin as output - works with libgpiod 1.6 and 2.x."""
        if hasattr(gpiod, 'request_lines'):
            # libgpiod 2.x (current Raspberry Pi OS)
            from gpiod.line import Direction, Value
            self._Value = Value
            self.rst_req = gpiod.request_lines(
                chip_path, consumer='rc522',
                config={self.NRSTPD: gpiod.LineSettings(
                    direction=Direction.OUTPUT, output_value=Value.INACTIVE)})
        else:
            # libgpiod 1.6 (older images)
            self.rst_req = None
            self.chip = gpiod.Chip(chip_path)
            self.rst_line = self.chip.get_line(self.NRSTPD)
            self.rst_line.request(consumer='rc522', type=gpiod.LINE_REQ_DIR_OUT)

    def _rst_set(self, level):
        if self.rst_req is not None:
            self.rst_req.set_value(
                self.NRSTPD, self._Value.ACTIVE if level else self._Value.INACTIVE)
        else:
            self.rst_line.set_value(level)

    def _rst_close(self):
        self._rst_set(0)
        if self.rst_req is not None:
            self.rst_req.release()
        else:
            self.rst_line.release()
            self.chip.close()

    def MFRC522_Reset(self):
        self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)

    def Write_MFRC522(self, addr, val):
        self.spi.xfer2([(addr << 1) & 0x7E, val])

    def Read_MFRC522(self, addr):
        val = self.spi.xfer2([((addr << 1) & 0x7E) | 0x80, 0])
        return val[1]

    def MFRC522_Init(self):
        self._rst_set(1)
        self.MFRC522_Reset()
        self.Write_MFRC522(self.TModeReg,      0x8D)
        self.Write_MFRC522(self.TPrescalerReg, 0x3E)
        self.Write_MFRC522(self.TReloadRegL,   0x1E)
        self.Write_MFRC522(self.TReloadRegH,   0x00)
        self.Write_MFRC522(self.TxASKReg,      0x40)
        self.Write_MFRC522(self.ModeReg,       0x3D)
        self.AntennaOn()

    def AntennaOn(self):
        temp = self.Read_MFRC522(self.TxControlReg)
        if (temp & 0x03) != 0x03:
            self.Write_MFRC522(self.TxControlReg, temp | 0x03)

    def MFRC522_Request(self, reqMode):
        self.Write_MFRC522(self.BitFramingReg, 0x07)
        TagType = [reqMode]
        (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
        if status != self.MI_OK or backBits != 0x10:
            status = self.MI_ERR
        return (status, backData)

    def MFRC522_Anticoll(self):
        serNumCheck = 0
        serNum = [self.PICC_ANTICOLL, 0x20]
        (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum)
        if status == self.MI_OK:
            if len(backData) == 5:
                for i in range(4):
                    serNumCheck = serNumCheck ^ backData[i]
                if serNumCheck != backData[4]:
                    status = self.MI_ERR
        return (status, backData)

    def MFRC522_ToCard(self, command, sendData):
        backData = []
        backLen  = 0
        status   = self.MI_ERR
        irqEn    = 0x77 if command == self.PCD_TRANSCEIVE else 0x12
        waitIRq  = 0x30 if command == self.PCD_TRANSCEIVE else 0x10
        self.Write_MFRC522(self.CommIEnReg,   irqEn | 0x80)
        self.Write_MFRC522(self.CommIrqReg,   0x7F)
        self.Write_MFRC522(self.FIFOLevelReg, 0x80)
        self.Write_MFRC522(self.CommandReg,   self.PCD_IDLE)
        for val in sendData:
            self.Write_MFRC522(self.FIFODataReg, val)
        self.Write_MFRC522(self.CommandReg, command)
        if command == self.PCD_TRANSCEIVE:
            self.Write_MFRC522(self.BitFramingReg, self.Read_MFRC522(self.BitFramingReg) | 0x80)
        i = 2000
        while True:
            n = self.Read_MFRC522(self.CommIrqReg)
            i -= 1
            if not (i != 0 and not (n & 0x01) and not (n & waitIRq)):
                break
        self.Write_MFRC522(self.BitFramingReg, 0x00)
        if i != 0:
            if (self.Read_MFRC522(self.ErrorReg) & 0x1B) == 0x00:
                status = self.MI_OK
                n = self.Read_MFRC522(self.FIFOLevelReg)
                backLen = self.Read_MFRC522(self.ControlReg) & 0x07
                backLen = (n - 1) * 8 + backLen if backLen != 0 else n * 8
                if n == 0: n = 1
                if n > self.MAX_LEN: n = self.MAX_LEN
                for _ in range(n):
                    backData.append(self.Read_MFRC522(self.FIFODataReg))
        return (status, backData, backLen)

    def cleanup(self):
        self._rst_close()
        self.spi.close()

Note on gpiochip0 and the libgpiod version: On current Raspberry Pi OS, the 40 header GPIOs sit on gpiochip0 on every model – including the Pi 5 with its RP1 chip. Only older Pi 5 images from before autumn 2024 had the controller at gpiochip4; there, enter /dev/gpiochip4 in _rst_open() instead. The class also detects on its own whether libgpiod 1.6 (older images) or 2.x (current Raspberry Pi OS) is installed – the two Python APIs are incompatible, hence the branch in _rst_open().

The complete code is available in the raspberry.tips GitHub repository. Clone it directly on your Pi. The first line installs git, which Raspberry Pi OS Lite doesn’t include. If you clone the repository, you can skip the two save steps for mfrc522_pi5.py and read_rfid.py, since both files are already in the rfid-rc522 folder.

sudo apt install git -y
git clone https://github.com/raspberry-tips/raspberry.tips-Resources.git
cd raspberry.tips-Resources/rfid-rc522
python3 read_rfid.py

Reading RFID tags — main script

Using nano again, save the following file as read_rfid.py in the same directory as mfrc522_pi5.py:

from mfrc522_pi5 import MFRC522
import time

reader = MFRC522()

print("Hold an RFID card or key fob up to the reader...")
print("(Press Ctrl+C to quit)\n")

try:
    while True:
        (status, TagType) = reader.MFRC522_Request(MFRC522.PICC_REQIDL)

        if status == MFRC522.MI_OK:
            (status, uid) = reader.MFRC522_Anticoll()

            if status == MFRC522.MI_OK:
                uid_str = "-".join([str(x) for x in uid[:4]])
                print(f"Tag detected! UID: {uid_str}")

        time.sleep(0.1)

except KeyboardInterrupt:
    reader.cleanup()
    print("\nProgram stopped.")

Run with:

python3 read_rfid.py

Example output:

Hold an RFID card or key fob up to the reader...
(Press Ctrl+C to quit)

Tag detected! UID: 163-49-218-90
Tag detected! UID: 24-177-53-11

Practical project — simple access control

With the UID of an RFID card you can build a simple access control system. First hold your authorized card up to the reader and note the UID. Save the script below with nano as access_control.py in the same directory as mfrc522_pi5.py, and enter your card’s UID in the AUTHORIZED_CARDS list:

from mfrc522_pi5 import MFRC522
import time

# UIDs of authorized cards -- read UIDs first using read_rfid.py
AUTHORIZED_CARDS = [
    "163-49-218-90",
    "24-177-53-11",
]

reader = MFRC522()
print("Access control active. Hold card up to reader...")

try:
    while True:
        (status, _) = reader.MFRC522_Request(MFRC522.PICC_REQIDL)

        if status == MFRC522.MI_OK:
            (status, uid) = reader.MFRC522_Anticoll()

            if status == MFRC522.MI_OK:
                uid_str = "-".join([str(x) for x in uid[:4]])

                if uid_str in AUTHORIZED_CARDS:
                    print(f"Access granted — UID: {uid_str}")
                    # Here: switch GPIO pin for relay / door lock
                else:
                    print(f"Access denied — UID: {uid_str}")

        time.sleep(0.1)

except KeyboardInterrupt:
    reader.cleanup()

Start the access control with:

python3 access_control.py

If the UID you read starts with 136, the card has a 7-byte UID and isn’t suitable for access control with this code (see the FAQ below).

To switch a relay from a GPIO pin, for example to drive a door opener, see Raspberry Pi as a Door Opener – Relay Module Wiring.

Common errors and solutions

RuntimeError: Cannot determine SOC peripheral base address

This error comes from the original RPi.GPIO, which doesn’t run on the Raspberry Pi 5 — usually pip installed it as a dependency of mfrc522. Make sure you are using the mfrc522_pi5.py from this guide and not the older MFRC522 library installed via pip install mfrc522.

/dev/spidev0.0 does not exist

SPI is not yet enabled. Enable it via sudo raspi-config → Interface Options → I4 SPI and reboot. If SPI was already enabled, check whether the kernel module entry exists in /boot/firmware/config.txt:

grep spi /boot/firmware/config.txt
# Expected output:
dtparam=spi=on

Card not detected

Check your wiring — especially that VCC is connected to Pin 1 (3.3 V) and RST to Pin 22 (GPIO 25). Swapped MOSI/MISO wires also prevent cards from being detected. Try replacing jumper wires if possible.

Further reading

Frequently asked questions

Does the RC522 also work with the Raspberry Pi 4?

Yes — on the Pi 4 both the approach from this guide (spidev + gpiod) and the older RPi.GPIO-based method work. For new projects we recommend the modern spidev + gpiod approach as it is future-proof and compatible with all Pi models.

Which RFID cards are compatible with the RC522?

The RC522 supports MIFARE Classic (1K and 4K) and MIFARE Ultralight — the most common 13.56 MHz cards. The white cards and key fobs included with the RC522 module are typically MIFARE Classic 1K and work right out of the box. Note, though, that the code in this guide only reads 4-byte UIDs in full. You can tell cards with a 7-byte UID, such as MIFARE Ultralight, by a displayed UID that starts with 136. That number isn’t part of the UID; it flags a longer UID, and only its first three bytes follow. With this code, such cards aren’t suitable for access control.

Can I run multiple RC522 modules at the same time?

Yes — each module needs its own chip-select line. SPI0 has two: CE0 (GPIO 8, pin 24) and CE1 (GPIO 7, pin 26). For more than two modules, also enable the second SPI bus, SPI1, by adding the line dtoverlay=spi1-3cs to /boot/firmware/config.txt. It uses its own pins and handles up to three more modules, so you don’t need an SPI multiplexer. Keep in mind that the class in this guide is built for a single module: it always calls spi.open(0, 0) and claims GPIO 25 as the RST pin. To run several modules, extend it with parameters for the bus, the chip select and a separate RST pin per module – a second module on CE1, for example, is then opened with spi.open(0, 1).

What is the read range of the RC522?

Typically 3–5 cm, and you shouldn’t plan on more: NXP rates the MFRC522 chip at a typical operating distance of up to 50 mm, depending on antenna size and tuning. That’s enough for most access control projects, since you hold the card right up to the reader. The read range depends heavily on card geometry and any nearby metal parts.

Similar Posts