Contents


Overview

Skill Level: Intermediate

You need to have some level of confidence plugging cables from the Pi GPIO header to the card reader pin header, and in using the commandline to control your Pi

Details how to connect an RC522 MiFare card read to your Raspberry Pi 3, using NodeRed and a small Python script, and feed the card IDs to Watson IoT Platform.

Ingredients

Raspberry Pi 3 (may work on other Pis - not tested) with Raspbian Jessie

RC522 MiFare card reader (includes PCB antenna) with SPI interface (e.g. found on ebay) with soldered-on pin header - I had to solder this on myself but some vendors appear to offer these pre-soldered

1+ MiFare RFID card/tag (often available with the RC522 card reader board - mine came with one of each)

7x female-female jumper cable - preferably in flat strip form - 10cm long, to connect the RC522 to your Pi (e.g. found on ebay)

Optional - with a bit of 'knife and fork' hobbyist work, and shortening the jumper cables, it should be possible to fit the RC522 card reader PCB into the lid of a case such as THIS to make a more handleable unit (rather than have the card dangling on the end of the wires)

Step-by-step

  1. Introduction and Overview

    In this recipe you will learn how to attach an RFID reader to your Pi and send tag information to Watson IoT Platform.

    The reader is attached to the GPIO pins of the Pi and interfaces using a peripheral called the SPI. A python script is used to read card IDs – this is called by a Node-RED “Daemon” node to push the card data into Node-RED, and your flow in Node-RED will send the data to IoT Platform using the Pi as a gateway.

    Many of the principles used here can be applied to interfacing other peripherals into IoT Platform – in particular, the Daemon node can run any script and process its output into a Node-RED flow, and python is widely used on Pi for interfacing and data processing.

    The following sections will take you through the recipe in baby steps, making sure that each part is working before moving onto more complex steps.

    2. Connect the RC522 card reader to your Pi 3

    3. Install needed software on your Pi 3

    4. Test your card reader and RFID tag from the commandline

    5. Create a NodeRed flow on the Pi to read your RFID tag

    6. Prepare your IoT Platform application to receive the RFID tag data

    7. Complete your Node-RED flow so it sends RFID tag data to IoT Platform

    8. Ideas for extensions/modifications

     

     

  2. Connect the RC522 card reader to your Pi 3

    Using the jumper cables, connect the RC522 pin header to your Pi using the following table. I included the jumper colour I used, which made it easier for me to check the connections – you can use a different colours, of course, but it is definitely a good idea to not repeat a colour. Also, I found that if I took a joined strip of cables the wiring was much neater than if I tore each jumper off the strip.

    NOTE on the Pi header, even numbered pins are nearest the outside edge of the Pi, starting at #2 farthest away from the USB connectors. Odd numbered pins are on the inboard side of the connector, starting at 1# furthest away from the USB connectors.

    NOTE: the jumper wires arrived as a flat 40-conductor cable with only the ends loose for the connectors Рthe wiring definitely ends up neatest if you keep seven adjacent wires together as one flat strip because they push straight onto the RC522 end (apart from the gap for IRQ), and twist them to the appropriate pin at the Pi end. 

    NOTE: Here's an electronics hobbyist tip: once you have the seven wires plugged onto the RC522, gently wrap some sticky-back plastic (i.e. sellotape) completely around just the eight connector shells – this holds them in shape if they become disconnected, makes it much easier to reconnect them.

    IMG_1916

     

    From the RC522 end, the connections are:

    RC522 Pin Cable colour Pi GPIO pin PI GPIO signal and function
    SDA Black 24 CS0 – This is the SPI chip select, active low
    SCK White  23 SCLK Рthis is the SPI clock
    MOSI Gray  19 MOSI Рdata to the RC522
    MISO Violet  21 MISO Рdata from the RC522
    IRQ  
    GND Blue  20 GND
    RST Green  22 GPIO25 Рthis is configured by Pi software for output, resets the RC522, active low
    3.3V Yellow  17 3.3V

     

    IMG_1917 

    From the Raspberry Pi GPIO end, the connections (using the same colors) are:

     

    RC522 Pin Color GPIO Pin GPIO Pin Color RC522 Pin
        1 2    
        3 4    
        5 6    
        7 8    
        9 10    
        11 12    
        13 14    
        15 16    
    3.3V  Yellow 17 18    
    MOSI Gray  19 20 Blue  GND
    MISO Violet  21 22 Green  RST
    SCK White  23 24 Black  SDA
        25 26    
        27 28    
        29 30    
        31 32    
        33 34    
        35 36    
        37 38    
        39 40    

    PLEASE double-triple-extra-check your wiring- you are doing this at your own risk and I suppose it might be possible to brick your Pi or the RC522 reader if you get it wrong. If in doubt but you really want to proceed, it might be a good idea to get someone else to do a final check that you have wired everything correctly.

    When you have convinced yourself that you have wired the RC522 to the Pi correctly, make sure there is no risk of pins or components on the RC522 touching anything metallic, and plug the Pi in.

    If the red light on the RC522 does not illuminate, unplug immediately and double-check everyhting! It should light up, or at least it does on my RC522 reader.

    NOTE: the RC522 has a pin labelled SDA – which is a reference to I2C, and the chip used on these boards does potentially allow I2C communication but AFAICT the PCB only allows SPI connection, and the the pin labelled SDA is actually performaing a different function as the SPI chip select to the RC522, active low. This means that when “SDA” is low, the RC522 transmits and receives SPI data using the SCLK/MISO/MOSI pins – the SCLK and MOSI are driven by the Pi, the MISO is driven by the RC522.

    NOTE: This recipe works even with the sensehat still plugged into my Pi 3, although I had to replace the Sensehat connector (it unplugs from the bottom of the sensehat) with a long-tailed GPIO header extender (see for example here) so the Pi GPIO pins are extended and stick out above the sensehat. The pin connections are unchanged by this.

     

  3. Install needed software on your Pi 3

    Connect to the Pi to get a command prompt

    The first step is to connect to your raspberry pi using an SSH terminal like Putty, and login using an id which has sudo privileges, such as the default id pi.

    Enable the SPI

    At the command prompt:

    sudo raspi-config

    Highlight 5 Interfacing Options and press Enter:

    conf1

    Highlight P4 SPI and press Enter:

    conf2

    Select Yes and press Enter, then on OK press Enter, press tab twice to select Finish and press Enter to exit the configuration utility.

    Run updates

    Reconnect putty.

    It is good practice to keep your Pi software up to date – but not required. Skip this if you want, or come back here if the recipe hits unexpected glitches later. YHBW.

    At the command prompt:

    • sudo apt-get update
    • sudo apt-get upgrade

    And if you really want to make sure things are up to date:

    • sudo apt-get dist-upgrade

    Install python-dev and git

    At the command prompt:

    • sudo apt-get install python-dev git

    Ensure NodeRed has been run

    Node-RED is already installed in Raspbian. In this recipe you will add a custom node, and you can only do that if Node-RED has been run at least once because this creates a folder ~/.node-red in your home folder.

    Run the command:

    • node-red-start

    When the server finishes loading, you can test the Node-RED by accessing the user interface using your browser point to the address http://<iprasberrypi>:1880. For example my Pi is on my home office network on address 192.168.1.8, so to access Node-RED I browse to http://192.168.1.8:1880/

    You now have to stop the Node-RED server – in the ternminal window type ctrl+C and then type the command:

    • node-red-stop

    Install needed nodes into Node-RED

    The Bluemix nodes node-red-bluemix-nodes include nodes to send data to IoT Platform, specifically the Watson IoT output node.

    The Daemon node in node-red-node-daemon can execute a long-running program and capture output from its stdout. In this recipe, the daemon node will call the rfidreader.py script.

    At the command prompt:

    • cd ~/.node-red
    • npm i node-red-node-daemon
    • npm i node-red-bluemix-nodes

    Install code to allow reading RFID tags from python

    Install SPI-Py. At the command prompt, type the following commands:

    Copy the python scripts to read RFID tags

    There are two files to copy into your user's home folder:

    • MFRC522.py – this has been slightly modified for Pi3 from¬†https://github.com/mxgxw/MFRC522-python – the changes are to use pin 22 as the pin identifier for RST to the RC522 card reader instead of 11 (changed two lines).
    • rfidreader.py – this is derived from MFRC522-python/Read.py¬†– this¬†waits to detect a card, when a different card (or the same card is found after not being seen for a few seconds), prints the uid and card type to the command line as a json-formatted string. This script will be run by the Node-RED daemon node and sent into the Node-Red flow.

    Extract both of these files from the zip file HERE. Put them in your user's home directory Рi.e. /home/pi.

    If you put these files in a different folder (they must be together), the Node-RED flow you will import into Node-RED later in this recipe will not work because the path to these files is assumed to be /home/pi. You will have to edit the Daemon node with the path to where you put the files. Suggest you first get everything working with the files in the location indicated here, then move them and update the Daemon node.

    Reboot and reconnect to the Pi

    Run the following command:

    • sudo reboot

    When the Pi has restarted, connect to the command prompt again, and start Node-RED:

    • node-red-start

     

     

  4. Test your card reader and RFID tag from the commandline

    In this section, rather than going straight to creating a Node-RED flow and risking that if it doesn't work you don't know where the problem is likely to be, it makes sense to first check that the card reader is working with your RFID tag. This confirms that your wiring is correct, the RC522 reader is working and the tag is recognized.

    Run the script from the commandline:

    • cd ~
    • python rfidreader.py

    When you wave a tag within ~1cm of the main area of the card reader, the script will print the unique UID of the card, and it's type. There are various types of card, the most common are called MIFARE 1KB, but there are others. Not all cards use the same RF communication protocol so don't be surprised if a random card that you pick up is not recognized. However if you received a card or tag with your RFID reader these should work!

    read1

    NOTE: If you remove and quickly replace the same RFID tag it won't be re-read. If you remove the tag for a few seconds it will be reread.

    Press control-c to exit.

    This script will be run from Node-RED to collect the card ID and send to IoT Platform.

    NOTE: When the script is being run by Node-RED, you must not run it from the commandline at the same time.

     

  5. Create a Node-RED flow on the Pi to read your RFID tag

    In this section we will create a flow to test that the RFID cards can be read by Node-RED.

    Connect to Node-RED on your Pi using a browser – either from another computer or on the Pi itself.

    You will import the flow into Node-Red ‚Äď to do this you need the json on your clipboard, which you can do in either of two ways:

    1. Copy the entire contents of the text box below ‚Äď be careful to copy only the text beginning with the first [ and ending with the final ], nothing else:

    [{"id":"9d7835c5.46986","type":"daemon","z":"9df3b382.bba0b8","command":"python","args":"-u /home/pi/rfidreader.py","cr":true,"redo":true,"op":"string","name":"RFIDReader","x":122.19999694824219,"y":131.1999969482422,"wires":[["86c452ae.f6a8f"],[],[]]},{"id":"86c452ae.f6a8f","type":"function","z":"9df3b382.bba0b8","name":"JSON to Object","func":"msg.payload = JSON.parse(msg.payload);\n\nreturn msg;","outputs":1,"noerr":0,"x":345.20001220703125,"y":118.70001220703125,"wires":[["a3a2d2d.8aff0b"]]},{"id":"a3a2d2d.8aff0b","type":"debug","z":"9df3b382.bba0b8","name":"","active":true,"console":"false","complete":"false","x":562.2000122070312,"y":190.90000915527344,"wires":[]}]

    2. Download and extract the same content from the zip file HERE, open the json file in a text editor and copy the entire contents

    With the flow on your clipboard, in the Node-RED flow editor, click the beefburger icon->Import->Clipboard

    import

    Paste the text you copied, then click Import:

    paste

    This creates the following flow which will work without any further editing to show RFID tag data on the debug node.

    flow

    Click Deploy.

    Click to select the debug tab and when you put a tag by the reader you will see the data from it, very similar to what you saw on the commandline in the previous section.

    data

    You are now ready to create and prepare an IoT Platform application to receive the RFID tag data.

  6. Prepare your IoT Platform application to receive the RFID tag data

    To create and prepare your IoT Platform application follow section 5 of my recipe HERE EXCEPT instead of creating a device type called SensortagType, use the name RFIDReaderType.

     

     

  7. Complete your Node-RED flow so it sends RFID tag data to IoT Platform

    This is the final step, where you will connect your Pi as a gateway and send RFID tag data to IoT Platform. In the Pi, in Node-RED you will add a Watson IoT node and configure it to connect to your IoT Platform application as a gateway, and you will specify the device type and name to be used as source of the data. I chose to configure the Pi as a gateway because it was convenient as I was developing another recipe at the same time which needed the gateway Рthere is no basic reason why you couldn't configure this Node-RED flow to connect as a device (you will have to create the device in your IoT application for this to work).

    In the Pi Node-RED in your browser, in the Output section of the palette, add a Watson IoT output node.

    iotnode

    Drag this from the palette and create a connection from the output of the JSON to Object node to the input of the Watson IoT node (when dropped on the canvas this appears with a default name IBM IoT Device).

    updatedflow

    Double-click the IBM IoT Device node and change the settings to Connect as Gateway, Registered, Device Type RFIDReaderType and Device Id RFIDReader:

    iotnodesettings

    For the credentials, click on the pencil to edit and insert the values for the Organisation of your IoT application (mine was nfyj21, yours will be different), the Device Type gwtype, Device ID id gw01 and Auth Token qwert123:

    cred-1

    Click Add and Done to finished editing the node.

    Click Deploy.

    In the IoT Platform dashboard, you should see that the gateway is connected:

    gwconnected

    Put an RFID tag against the reader.

    Once you see the tag data on the Debug tab on your Pi, if you refresh the device list in your IoT Platform dashboard you will see a new device with the name of your has appeared. This has happened because a gateway can create devices, although the device type has to already exist.

    newdev

    If you click on the device RFIDReader and scroll down, then scan your tag again once or twice, you will see the RFID tag data.

    rfiddata

    You have finished ‚Äď well done!

    Next time you start Node-RED this flow will automatically start and connect to your IoT Platform application

  8. Ideas for extensions/modifications

    • Add some output control on the Pi – for example drive a relay/solenoid to unlock a door – easy to do from Node-RED using the GPIO nodes.
    • I'm sure the RC522 integration with NodeRed could be done from a custom Node-RED node – there are ones already which use the SPI, such as node-red-node-pi-mcp3008 – this recipe is probably incompatible with such nodes.
    • Write data to the RFID tag – this is supported by the python MFRC522 library.

17 comments on"Reading RFID MiFare cards into Watson IoT Platform using your Raspberry Pi 3"

  1. The mifare rc522 card is not getting detected, even if the wiring is correct. I am using the latest version of the raspbian jesse with PIXEL operating system which is fully upgraded and updated. The RFID reader is working on my arduino( so no problem in that) . Please give me a solution for this.

    • Ian Barnard April 05, 2017

      I‚Äôve used this recipe with several people on Pi3 now without problems ‚Äď there must be something about your wiring/pi/reader that is preventing it working. Most basic thing is if you haven‚Äôt enabled the SPI in raspi-config, as per section 3. Are you getting any error messages when you run the python script from the commandline in section 4?

  2. Ian Barnard March 13, 2017

    I just did a complete update, made sure Pixel is running (Pixel is just the customised desktop X11 server, not the OS, that is Raspbian Jessie) and the commandline test works fine. I can’t help much from here – there are many things which might go wrong – but if you want me to help you will have to give me more information about the symptoms you are seeing – start with whether running the python script at the commandline as per section 4 gives any errors. You haven’t got any other hardware attached to the GPIO ports have you? I have the RFID reader running with the sensehat attached and working (sensors being read, display being updated) at the same time as the commandline running the python script, and I’m connected to the pixel desktop using VNC viewer.

    • KevinsPies April 05, 2017

      Hi, I’m new here and trying to do this for a project in my school.
      How do you check if your running pixel or lite in Raspberry pi?
      Also does using GPIO cobbler affect it apparently? I’m using a T-Cobbler cable from Raspberry pi 1.
      I followed this step and even used “sudo apt-get dist-upgrade”
      It wouldn’t read on Node Red or “python rfidreader.py”.

      The wring is correct though. I was able to read it on Arduino. Nothing wrong with the card or wires.

      • Ian Barnard April 05, 2017

        For this tutorial on Pi 3 it doesn’t matter if you are running pixel. Not sure what “lite” means, I’m just using the latest vanilla Raspbian downloaded March 13th. I wouldn’t expect the cobbler to affect this, most likely the Pi 1 has some differences in I/O pin operation/wiring – sorry cant help you with that as I only have a Pi 3. There’s no point trying in NodeRED if running the python script from the commandline doesn’t work. Most basic thing is probably to confirm that the SPI is enabled in raspi-config.

        • KevinsPies April 06, 2017

          I got through the GPIO pin issue SDA is using CE0 and RST was CE1. I’m at Watson IOT part and finished the qwert123. When I click deploy I get

          “BMIoT: Error: getaddrinfo ENOTFOUND nfy22.messaging.internetofthings.ibmcloud.com nfy22.messaging.internetofthings.ibmcloud.com:8883”

          Am I missing something?

          • Ian Barnard April 06, 2017

            Your organisation id ‘nfy22’ doesn’t look correct – AFAIK they are always six characters. BTW you shouldn’t really share your org ID on here, anyone could access it unless you secure it. This receipe doesn’t go into securing the IoTP app.

        • KevinsPies April 06, 2017

          Well too bad I can’t edit it. I kind of copied yours and change it by 1 number. I figured out I’m suppose to sign up for the 30 day trial Bluemix and create my own organisation id right?

  3. hello sir,
    I am beginner , I have question : suppose we have a temperature sensor , now I want to take decision on raspberry automatically (for example :for a critical value Led on & for normal value led off) Is there python program required to turn led on /off in raspberry pi ,1) if yes then how we can run saved program in raspberry pi automatically according to temperature 2)if no then how we’ll do that?

    • Ian Barnard April 05, 2017

      I‚Äôm sure what you want is possible, but I can‚Äôt help you with it ‚Äď I‚Äôm sure if you use a well-known search engine to find information about, for example, _raspberry pi led flash python_ that you will find some examples.

  4. Hi Ian,

    where can i found latest vanilla Raspbian (downloaded March 13th) for download?

    • Ian Barnard June 21, 2017

      I’m pretty sure if you use a well-known search engine to look for “raspbian download” the top result will probably be what you want, but look for yourself.

  5. Very new and not a coder. Is there a node that will let me strip out just the CardUID value as a payload so that I can use that in an other node?
    thank you in advance,

    • AFAIK there wasn’t a self-contained node which would read Mifare cards when I wrote this recipe, but that was a few months ago, you should search for it yourself. If you use this recipe the output is a payload with the CardUID – yes of course you can use that in another node.

  6. hey, I wanted to export the data which is being read into an excel file. Could you guide me on how to do it?

    • You can do this in Node Red on the Pi by formatting the data however you need e.g. in a template node or even simpler by converting the payload to json, then writing that to a file using a file output node. I can’t help with any more detail than that – and anyway this sounds like a good learning exercise ūüôā

Join The Discussion