# 米米的博客

0%

In this Raspberry Pi RFID RC522 tutorial, I will be walking you through the steps on how to set up and wire the RFID RC522 chip with your Raspberry Pi. This project is a cool circuit to play around with and opens you up to quite a wide variety of different projects from using it as an attendance system to using it to open a lock.

The RFID RC522 is a very low-cost RFID (Radio-frequency identification) reader and writer that is based on the MFRC522 microcontroller. This microcontroller provides its data through the SPI protocol and works by creating a 13.56MHz electromagnetic field that it uses to communicate with the RFID tags.
RFID RC522 是基于 MFRC522 微控制器的非常低成本的 RFID（射频识别）读写器。该微控制器通过 SPI 协议提供数据，并通过创建一个 13.56MHz 的电磁场来工作，该电磁场用于与 RFID 卡片进行通信。

Make sure that the tags you purchase for your RFID RC522 operate on the 13.56MHz frequency otherwise we will fail to read them.

We will be showing you how to wire up the RC522 as well as showing you how to write Python scripts to interact with the chip so you can both read and write your RFID Tags. You can extend this tutorial to use something like a 16×2 LCD for the Raspberry Pi, handy if you want to show some information.

## Equipment List

Below are all the bits and pieces that I used for this Raspberry Pi RFID RC522 tutorial.

Recommended:

• Raspberry Pi 2 or 3
树莓派 2 或 3

• Micro SD Card
Micro SD 卡

• Power Supply
电源供应

• RC522 RFID Reader
RC522 RFID 读卡器

面包板

面包板接线

Optional:

• Raspberry Pi Case
树莓派外壳

• Ethernet Network Connection or Wifi dongle (The Pi 3 has WiFi inbuilt)
以太网或 Wifi 适配（树莓派 3 自带了）

## Assembling the RFID RC522

One thing you will notice when purchasing an RFID RC522 Reader is that 90% of them don't come with the header pins already soldered in. The missing pins mean you will have to do it yourself, luckily soldering header pins is a rather simple task, even for beginners.

First off, if the header pins you received with your RC522 isn't the correct size, then snap them down, so you only have a single row of eight pins.

Place the header pins up through the holes of your RC522. One handy trick is to put the long side of the header pins into a breadboard and then putting the circuit over the top of the header pins. The breadboard will hold the pins tightly making it easier to solder them to the RFID RC522 circuit.

Now using a hot soldering iron and some solder, slowly solder each of the pins. Remember it is best to heat the joint slightly before applying solder to it, this will ensure that the solder will adhere more to the joint and reduce the chances of creating a cold joint. We also recommend being careful with the amount of solder you apply.

With the header pins now soldered to your RFID circuit, it is now ready to use, and you can continue with the tutorial.

## Wiring the RFID RC522

On your RFID RC522 you will notice that there are 8 possible connections on it, these being SDA (Serial Data Signal), SCK (Serial Clock), MOSI (Master Out Slave In), MISO (Master In Slave Out), IRQ (Interrupt Request), GND (Ground Power), RST (Reset-Circuit) and 3.3v (3.3v Power In). We will need to wire all of these but the IRQ to our Raspberry Pi's GPIO pins.

You can either wire these directly to the GPIO Pins or like we did in this tutorial, plug the RFID RC522 into our Breadboard then wire from there to our Raspberry Pi's GPIO Pins.

Wiring your RFID RC522 to your Raspberry Pi is fairly simple, with it requiring you to connect just 7 of the GPIO Pins directly to the RFID reader. Follow the table below, and check out our GPIO guide to see the positions of the GPIO pins that you need to connect your RC522 to.

• SDA connects to Pin 24.
SDA 连接到引脚 24。

• SCK connects to Pin 23.
SCK 连接到引脚 23。

• MOSI connects to Pin 19.
MOSI 连接到引脚 19。

• MISO connects to Pin 21.
MISO 连接到引脚 21。

• GND connects to Pin 6.
GND 连接到引脚 6。

• RST connects to Pin 22.
RST 连接到引脚 22。

• 3.3v connects to Pin 1.
3.3V 连接到引脚 1。

## Setting up Raspbian for the RFID RC522

Before we begin the process of utilizing the RFID RC522 on our Raspberry Pi, we will first have to make changes to its configuration. By default, the Raspberry Pi has the SPI (Serial Peripheral Interface) disabled, which is a bit of a problem as that is what our RFID reader circuit runs through.

Don't worry though as it is fairly simple to re-enable this interface, just follow our steps below to configure your Raspberry Pi and Raspbian to utilize the SPI interface.

Let's begin by first opening the raspi-config tool, and we can do this by opening the terminal and running the following command.

This tool will load up a screen showing a variety of different options. If you want a more in-depth look into these options, you can check out our raspi-config guide.

On here use the arrow keys to select "5 Interfacing Options". Once you have this option selected, press Enter.

Now on this next screen, you want to use your arrow keys to select "P4 SPI", again press Enter to select the option once it is highlighted.

You will now be asked if you want to enable the SPI Interface, select Yes with your arrow keys and press Enter to proceed. You will need to wait a little bit while the raspi-config tool does its thing in enabling SPI.

Once the SPI interface has been successfully enabled by the raspi-config tool you should see the following text appear on the screen, "The SPI interface is enabled".

Before the SPI Interface is fully enabled we will first have to restart the Raspberry Pi. To do this first get back to the terminal by pressing Enter and then Esc.

Type the following Linux command into the terminal on your Raspberry Pi to restart your Raspberry Pi.

Once your Raspberry Pi has finished rebooting, we can now check to make sure that it has in fact been enabled. The easiest way to do this is to run the following command to see if spi_bcm2835 is listed.

If you see spi_bcm2835, then you can proceed on with this tutorial and skip on to the next section. If for some reason it had not appeared when you entered the previous command, try following the next three steps.

If for some reason the SPI module has not activated, we can edit the boot configuration file manually by running the following command on our Raspberry Pi.

Within the configuration file, use Ctrl+W to find "dtparam=spi=on".

If you have found it, check to see if there is a # in front of it. If there is, remove it as this is commenting out the activation line. If you can't find the line at all, add "dtparam=spi=on" to the bottom of the file.

Once you have made the changes, you can press Ctrl+X then pressing Y and then Enter to save the changes.

You can now proceed from Step 5 again, rebooting your Raspberry Pi then checking to see if the module has been enabled.

## Getting Python ready for the RFID RC522

Now that we have wired up our RFID RC522 circuit to the Raspberry Pi we can now power it on and begin the process of programming simple scripts in Python to interact with the chip.

The scripts that we will be showing you how to write will show you how to read data from the RFID chips and how to write to them. These will give you the basic idea of how data is dealt with and will be the basis of further RFID RC522 tutorials.

Before we start programming, we first need to update our Raspberry Pi to ensure it's running the latest version of all the software. Run the following two commands on your Raspberry Pi to update it.

Now the final thing we need before we can proceed is to install the python2.7-dev package, simply run the following command on your Raspberry Pi to install it.

To begin, we must first clone the Python Library SPI Py and install it to our Raspberry Pi. This library helps handle interactions with the SPI and is a key component to this tutorial as we need it for the Raspberry Pi to interact with the RFID RC522.

Run the following two commands on your Raspberry Pi to clone the source code.

With the SPI Py Python Library now cloned to our Raspberry Pi, we need to install it, this is incredibly simple, as all we need to do is change into its directory and run a simple Python command on our Raspberry Pi.

Now that we have installed SPI-Py we can now clone our RFID RC522 Python code from the PiMyLifeUp Github. There are two files included in this repository:

• MFRC522.py which is an implementation of the RFID RC522 circuit.
MFRC522.py 是 RFID RC522 电路的一个实现。

• SimpleMFRC522.py that takes the MFRC522.py file and greatly simplifies it.
SimpleMFRC522.py 采用 MFRC522.py 文件，并大大简化它。

To clone this repository, you can type the following two commands into your Raspberry Pi.

With the repository now saved to our Raspberry Pi, we can begin programming for our RFID RC522. To start off with we will be showing you how to write data to your RFID cards by using the RC522. Simply go onto our next section to begin programming our first Python script.

## Writing with the RFID RC522

For our first Python script, we will be showing you how to write data from the RC522 to your RFID tags. Thanks to the SimpleMFRC522 script this will be relatively simple, but we will still go into how each part of the code words.

Begin by changing directory into our newly cloned folder, and begin writing our Write.py Python script.

Within this file, write the following lines of code. This code will basically ask you for text to input and then write that text to the RFID Tag.

The first line of this segment of code helps tell the terminal how to interpret the file, and it lets it know that it should use Python when executing it and not something else such as Bash.

Our first import, RPi.GPIO has all the functions needed to interact with the GPIO Pins, and we need this to make sure they are cleared when the script finishes running.

The second import, imports in our SimpleMFRC522 library, this is what we will use actually to talk with the RFID RC522, it greatly simplifies dealing with the chip compared to the base MFRC522 library.

This line creates a copy of the SimpleMFRC522 as an object, runs its setup function then stores it all in our reader variable.

Our next block of code we keep within a try statement, this is so we can catch any exceptions and clean up properly. Make sure that you retain the 'tabs' after try: as Python is whitespace sensitive, and it is how it differs between blocks of code.

The second line here reads in an input from the command line, and we use raw_input in Python 2.7 to read in all input and store it in our text variable.

With the third line, we utilize print() to notify the user that they can now place their RFID tag down onto the reader for writing.

Afterward, on our fourth line of code we use our reader object to write the values we stored in the text variable to the RFID tag, this will tell the RFID RC522 Circuit to write the text values to a certain sector.

Finally, on the 5th line of code, we use print() again to notify the user that we have successfully written to the RFID tag.

Our final two lines of code handle exiting of the script. Finally, always occurs after the try statement, meaning no matter what we run the GPIO.cleanup() function. These lines are crucial as failing to clean up can prevent other scripts from working correctly.

Once you have finished writing in your script, it should look something like below.

Once you are happy that the code looks correct, you can save the file by pressing Ctrl+X then pressing Y and then finally hitting Enter.

Now that we have written our script, we will want to test it out. Before testing out the script make sure that you have an RFID tag handy. Once ready, type the following command into your Raspberry Pi's terminal.

You will be asked to write in the new data, in our case we are going to just type in pimylifeup as its short and simple. Press Enter when you are happy with what you have written.

With that done, simply place your RFID Tag on top of your RFID RC522 circuit. As soon as it detects it, it will immediately write the new data to the tag. You should see "Written" appear in your command line if it was successful.

You can look at our example output below to see what a successful run looks like.

You have now successfully written your Write.py script, and we can now proceed to show you how to read data from the RFID RC522 in the next segment of this tutorial.

## Reading with the RFID RC522

Now that we have written our script to write to RFID tags using our RC522 we can now write a script that will read this data back off the tag.

Let's start off by changing the directory to make sure we are in the right place, and then we can run nano to begin writing our Read.py script.

Within this file, write the following lines of code. This script will basically sit and wait till you put your RFID tag on the RFID RC522 reader, it will then output the data it reads off the tag.

The first line of code tells the operating system how to handle the file when a user executes it. Otherwise, it will try and just run it as a regular script file and not a Python file.

The first import is, RPi.GPIO. This library contains all the functions to deal with the Raspberry Pi's GPIO pins, and we mainly import this to ensure that we clean up when the script finishes executing.

The second import is, SimpleMFRC522. This script contains a few helper functions to make it an awful lot easier to deal with writing and reading from the RFID RC522, without it the scripts would become quite long.

This line is quite important as it calls SimpleMFRC522's creation function and then stores that into our reader variable as an object so we can interact with it later.

This next block of code is contained within a try statement, and we use this so we can catch any exceptions that might occur and deal with them nicely. You need to ensure that you use the ‘tabs‘ as shown after try: as Python is whitespace sensitive.

The second line in this block of code makes a call to our reader object, in this case, it tells the circuit to begin reading any RFID tag that is placed on top of the RC522 reader.

With the third and fourth lines we utilize print() to print out the information that we received from reading the RFID Chip, this includes the ID associated with the RFID tag and the text that is stored on the tag.

The two last lines of code handle the termination of the script. The finally statement always triggers after the try statement even if we get an exception.

This try statement ensures that no matter what we run the GPIO.cleanup() function. It is quite crucial as failing to clean up the GPIO can prevent other scripts from working correctly.

Now that you have finished writing your Read.py script for your RFID RC522 it should look something like what is shown below.

Once you are sure you have entered the code correctly, you can save the file by pressing Ctrl+X then pressing Y and then finally hitting Enter.

Now that we have finally finished our Read.py script we need to test it out. Before we test out the script, grab one of the RFID tags that you want to read. Once that you are ready, type the following command into your Raspberry Pi's terminal.

With the script now running, all you need to do is place your RFID Tag on top of your RFID RC522 circuit. As soon as the Python script detects the RFID tag being placed on top, it will immediately read the data and print it back out to you.

An example of what a successful output would look like is displayed below.

If you successfully receive data back from your Read.py script with the text that you pushed to the card using your Write.py script then you have successfully set up your Raspberry Pi to connect with your RFID RC522 Circuit.

## 后记

We will be going into more depth with these scripts and the RFID chip in later tutorials. It will include exploring how to set up an attendance system among other cool DIY Pi projects.

If you have enjoyed this Raspberry RFID RC522 tutorial or have any feedback, then feel free to drop a comment over at our forum.

🍭支持一根棒棒糖！