Getting the RFID-RC522 to work! [SOLVED]


#125

Copy/paste this. Save it as an .ino Sketch file for Arduino and it’s reading and writing.

  /**
 * ----------------------------------------------------------------------------
 * This is a MFRC522 library example.
 * 
 * Released into the public domain.
 * ----------------------------------------------------------------------------
 * This sample shows how to read and write data blocks on a MIFARE Classic PICC
 * (= card/tag).
 * 
 * BEWARE: Data will be written to the PICC, in sector #1 (blocks #4 to #7).
 * 
 * 
 * Typical pin layout used:
 * ------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino
 *             Reader/PCD   Uno           Mega      Nano v3

 * Signal      Pin          Pin           Pin       Pin
 * ------------------------------------------------------------
 * RST/Reset   RST          9             5         D9
 * SPI SS      SDA(SS)      10            53        D10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11
 * SPI MISO    MISO         12 / ICSP-1   50        D12
 * SPI SCK     SCK          13 / ICSP-3   52        D13
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

MFRC522::MIFARE_Key key;

/**
 * Initialize.
 */
void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    SPI.begin();        // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card

    // Prepare the key (used both as key A and as key B)
    // using FFFFFFFFFFFFh which is the default at chip delivery from the factory
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }

    Serial.println("Scan a MIFARE Classic PICC to demonstrate read and write.");
    Serial.print("Using key (for A and B):");
    dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
    Serial.println();
    
    Serial.println("BEWARE: Data will be written to the PICC, in sector #1");
}

/**
 * Main loop.
 */
void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print("Card UID:");
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print("PICC type: ");
    byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Check for compatibility
    if (    piccType != MFRC522::PICC_TYPE_MIFARE_MINI
        &&  piccType != MFRC522::PICC_TYPE_MIFARE_1K
        &&  piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
        Serial.println("This sample only works with MIFARE Classic cards.");
        return;
    }

    // In this sample we use the second sector,
    // that is: sector #1, covering block #4 up to and including block #7
    byte sector         = 1;
    byte blockAddr      = 4;
    byte dataBlock[]    = {
        0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
        0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
        0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
        0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
    };
    byte trailerBlock   = 7;
    byte status;
    byte buffer[18];
    byte size = sizeof(buffer);

    // Authenticate using key A
    Serial.println("Authenticating using key A...");
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print("PCD_Authenticate() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Show the whole sector as it currently is
    Serial.println("Current data in sector:");
    mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
    Serial.println();

    // Read data from the block
    Serial.print("Reading data from block "); Serial.print(blockAddr);
    Serial.println(" ...");
    status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
    if (status != MFRC522::STATUS_OK) {
        Serial.print("MIFARE_Read() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    Serial.print("Data in block "); Serial.print(blockAddr); Serial.println(":");
    dump_byte_array(buffer, 16); Serial.println();
    Serial.println();

    // Authenticate using key B
    Serial.println("Authenticating again using key B...");
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print("PCD_Authenticate() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Write data to the block
    Serial.print("Writing data into block "); Serial.print(blockAddr);
    Serial.println(" ...");
    dump_byte_array(dataBlock, 16); Serial.println();
    status = mfrc522.MIFARE_Write(blockAddr, dataBlock, 16);
    if (status != MFRC522::STATUS_OK) {
        Serial.print("MIFARE_Write() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    Serial.println();

    // Read data from the block (again, should now be what we have written)
    Serial.print("Reading data from block "); Serial.print(blockAddr);
    Serial.println(" ...");
    status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
    if (status != MFRC522::STATUS_OK) {
        Serial.print("MIFARE_Read() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    Serial.print("Data in block "); Serial.print(blockAddr); Serial.println(":");
    dump_byte_array(buffer, 16); Serial.println();
        
    // Check that data in block is what we have written
    // by counting the number of bytes that are equal
    Serial.println("Checking result...");
    byte count = 0;
    for (byte i = 0; i < 16; i++) {
        // Compare buffer (= what we've read) with dataBlock (= what we've written)
        if (buffer[i] == dataBlock[i])
            count++;
    }
    Serial.print("Number of bytes that match = "); Serial.println(count);
    if (count == 16) {
        Serial.println("Success :-)");
    } else {
        Serial.println("Failure, no match :-(");
        Serial.println("  perhaps the write didn't work properly...");
    }
    Serial.println();
        
    // Dump the sector data
    Serial.println("Current data in sector:");
    mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
    Serial.println();

    // Halt PICC
    mfrc522.PICC_HaltA();
    // Stop encryption on PCD
    mfrc522.PCD_StopCrypto1();

}

/**
 * Helper routine to dump a byte array as hex values to Serial.
 */
void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

This will do all the magic. Instructions for 522 Google is your Friend and the NPX datasheet shows even every bit you can acces.


#126

@peekay123 I’ve been trying to get your MFRC522/MFRC522.h library working, but Im having some trouble. It seems to compile fine but nothing is ever put out on the serial terminal. It just hangs. Is there something that needs to be changed for the library to work? Ive tested the hardware interface between the Sparkcore and the RC522 using your code I found on github and it works but I like the functionality of the other library in the IDE. Any pointers would be appreciated.
FILE: RC522_RFID_Module_Example
DATE: 23/03/14
VERSION: 0.2 Spark

REVISIONS:
23/03/14 Version 0.2, modified by Paul Kourany to run on Spark Core
with added support for Software SPI


#127

@Ambition1906, I am at a loss as to which MFRC522 library you are referring to. I don’t have a version 0.2 on the IDE! As well, which “other” library are you referring to that contains RC522_RFID_Module_Example?


#128

@peekay123 ok, the Spark Web IDE has the “MFRC522/MFRC522.h” library which I believe you ported via github. (by looking through previous posts on this topic, I came to this conclusion) If you do a search for MFRC522 in the library folder you will see it. This library compiles but does not work. Nothing ever gets put out on the serial line via USB to the PC. While looking through your github repositories I noticed you have another library call RC522_RFID for the SparkCore that is not ported to the Web IDE. I copied the files from your repository and those work with the spark and the RC522. So I know there is nothing wrong with my hardware because everything is wired the same. So there must be something I am missing in the ino file or there must be something wrong with the library cpp and h files themselves found in the library file in the Web IDE. Any ideas what could be wrong?


#129

@Ambition1906, you have to use the examples that come with each library since they don’t mix and match. So with the web IDE library, try using the dumpinfo.ino example.

One big problem with using the serial port is that the code usually runs faster than the time you have to open your terminal! So you end up not seeing any output thinking it is hung. One way to get around this is to wait for a key press on the serial port while still maintaining cloud connectivity like this:

while (!Serial.available()) SPARK_WLAN_Loop();

Add this line right after the Serial.begin(9600) line and that will give you time to open a terminal window and hit any key to get the rest of the code going. Keep me posted and let me know how it goes :smile:


#130

@peekay123 yes, I tried that before contacting you. Here’s a list of things I’ve already tried:

  1. Changed baud rate to 115200 from 9600 to see if that made a difference.
  2. added “while (!Serial.available()) SPARK_WLAN_Loop():” statement to capture output with keystrokes
  3. Tried to mirror library by renaming h and cpp files, but it will not compile because there are references to the library in the application.h file.
  4. I tried all 3 examples=dumpinfo.ino, MifareClassicValueBlock.ino, and ReadAndWrite.ino. They all compile but freeze my serial port.
  5. Tried Coolterm for serial reading, tried Spark CLI using “spark serial monitor” for serial reading, tried terminal command “screen /dev/tty.usbmodem1421 9600” for serial reading but none of them output anything.
  6. Pinout is
    RC522<=>SPARK
    SDA<=>A2
    SCK<=>A3
    MOSI<=>A5
    MISO<=>A4
    IRQ<=>NC
    GND<=>GND
    RST<=>D2
    3.3V<=>3V3*

Any ideas I haven’t listed? thanks for your help


#131

@Ambition1906, let’s recap:

  1. The other RF522 library on my github works with the exact same wiring?
  2. The above library outputs data to your PC using screen or coolterm?
  3. You are compiling on the IDE or CLI?
  4. Do you have the latest version of CLI (4.92 I believe)?
  5. When you say the serial port “freezes” do you get anything at all?
  6. Did you try adding Serial.print() debug message to see where it might be hanging?

I would not power the board from the 3.3V*. Use the 3.3V (unfiltered) line instead.


#132

@peekay123 heres the answers:


#133

@Ambition1906, the easiest way to see what CLI version you have is to type:

spark --version

in a terminal window. I will prepare a version of the files that you can put in a single directory and compile with Spark CLI using “spark compile directoryname”. It is super simple to use. I’ll post the files on my github later for you to grab. I unfortunately don’t have an RFC522 to play with but I know other members have used the code successfully. :smile:


#134

@peekay123 ok, thanks! its version 0.4.92


#135

@austinpe, Hey Im working on using the MFRC522 module with the Sparkcore and I can’t seem to get the library in the Web IDE to work. It looks like you got it to work at some point. I was able to get the older library to work and it oscillates between card detected and card not detected in the terminal window. The new library compiles but I don’t get anything on the serial print out. Can you tell me what you did to get it working? I talked to peekay123 and hes been trying to help me but he doesn’t have the hardware to actually see what Im talking about. Any help is appreciated.


#136

@Ambition1906, I sent you a PM with a link to the files. Let me know how it goes :smile:


#137

@peekay123, I tried the files you sent but still no output on the serial line. The files compiled fine using the CLI and had no problem flashing via the CLI but when I connect coolterm there is no output still. :frowning: I really appreciate your help. Any other ideas?


#138

@Ambition1906, I posted updated files in dropbox. I added some Serial.print statements which will show if either of the two card operations are working. I also uncommented some debug print statements which you should see on your terminal. Give this code a shot to see what you get. :smile:


#139

@peekay123 ok, great! downloading them now.


#140

@peekay123 Definitely progress!!! It is finally outputting something. I’ll take a look at the code to see if I can figure out the changes you made. Here’s the serial dump:

Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 2 bytes from register.
A new card was found
ANTICOLLISION: currentLevelKnownBits=0
Reading 5 bytes from register.
SELECT: currentLevelKnownBits=32
Reading 3 bytes from register.
SELECT: currentLevelKnownBits=232
Reading 2 bytes from register.
A new card was found
ANTICOLLISION: currentLevelKnownBits=0
Reading 5 bytes from register.
SELECT: currentLevelKnownBits=32
Reading 3 bytes from register.
SELECT: currentLevelKnownBits=232
Reading 2 bytes from register.
A new card was found
ANTICOLLISION: currentLevelKnownBits=0
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.
Reading 1 bytes from register.


#141

@Ambition1906, looks like it finds the card but it can’t seem to read it, getting into an ANTICOLLISION condition. I will have to do a bit of research on that.


#142

@peekay123 I did some additional troubleshooting and found that the issue seems to be with the type of card I am using. I tried 2 different types of cards, a MIFARE 1K and a MIFARE Ultralight. The cards I am using are MIFARE Ultralight and those are the ones which output the below. :wink:

A new card was found
ANTICOLLISION: currentLevelKnownBits=0
Reading 4 bytes from register.
SELECT: currentLevelKnownBits=32
Reading 2 bytes from register.
A new card was found
ANTICOLLISION: currentLevelKnownBits=0
Reading 5 bytes from register.
SELECT: currentLevelKnownBits=32
Reading 3 bytes from register.

I then tried a MIFARE 1K card and got this output continually dumped. So there must be something in the way the Ultralight cards are processed in the program. Do you know if this program can handle both 4 byte UIDs and 7 byte UIDs since the Ultralight cards are 7 bytes long?

Card read successfully
Card UID: 91 7E 48 B5
PICC type: MIFARE 1KB
Sector Block 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 AccessBits
15 63 Reading 18 bytes from register.
00 00 00 00 00 00 FF 07 80 69 FF FF FF FF FF FF [ 0 0 1 ]
62 Reading 18 bytes from register.
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 0 0 0 ]
61 Reading 18 bytes from register.
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 0 0 0 ]
60 Reading 18 bytes from register.
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 0 0 0 ]
59 Reading 1 bytes from register.
MIFARE_Read() failed: A MIFARE PICC responded with NAK.
58 MIFARE_Read() failed: Timeout in communication.
57 MIFARE_Read() failed: Timeout in communication.
56 MIFARE_Read() failed: Timeout in communication.
55 MIFARE_Read() failed: Timeout in communication.
54 MIFARE_Read() failed: Timeout in communication.
53 MIFARE_Read() failed: Timeout in communication.
52 MIFARE_Read() failed: Timeout in communication.
51 MIFARE_Read() failed: Timeout in communication.
50 MIFARE_Read() failed: Timeout in communication.
49 MIFARE_Read() failed: Timeout in communication.
48 MIFARE_Read() failed: Timeout in communication.
47 MIFARE_Read() failed: Timeout in communication.
46 MIFARE_Read() failed: Timeout in communication.
45 MIFARE_Read() failed: Timeout in communication.
44 MIFARE_Read() failed: Timeout in communication.
43 MIFARE_Read() failed: Timeout in communication.
42 MIFARE_Read() failed: Timeout in communication.
41 MIFARE_Read() failed: Timeout in communication.
40 MIFARE_Read() failed: Timeout in communication.
39 MIFARE_Read() failed: Timeout in communication.
38 MIFARE_Read() failed: Timeout in communication.
37 MIFARE_Read() failed: Timeout in communication.
36 MIFARE_Read() failed: Timeout in communication.
35 MIFARE_Read() failed: Timeout in communication.
34 MIFARE_Read() failed: Timeout in communication.
33 MIFARE_Read() failed: Timeout in communication.
32 MIFARE_Read() failed: Timeout in communication.
31 MIFARE_Read() failed: Timeout in communication.
30 MIFARE_Read() failed: Timeout in communication.
29 MIFARE_Read() failed: Timeout in communication.
28 MIFARE_Read() failed: Timeout in communication.
27 MIFARE_Read() failed: Timeout in communication.
26 MIFARE_Read() failed: Timeout in communication.
25 MIFARE_Read() failed: Timeout in communication.
24 MIFARE_Read() failed: Timeout in communication.
23 MIFARE_Read() failed: Timeout in communication.
22 MIFARE_Read() failed: Timeout in communication.
21 MIFARE_Read() failed: Timeout in communication.
20 MIFARE_Read() failed: Timeout in communication.
19 MIFARE_Read() failed: Timeout in communication.
18 MIFARE_Read() failed: Timeout in communication.
17 MIFARE_Read() failed: Timeout in communication.
16 MIFARE_Read() failed: Timeout in communication.
15 MIFARE_Read() failed: Timeout in communication.
14 MIFARE_Read() failed: Timeout in communication.
13 MIFARE_Read() failed: Timeout in communication.
12 MIFARE_Read() failed: Timeout in communication.
11 MIFARE_Read() failed: Timeout in communication.
10 MIFARE_Read() failed: Timeout in communication.
9 MIFARE_Read() failed: Timeout in communication.
8 MIFARE_Read() failed: Timeout in communication.
7 MIFARE_Read() failed: Timeout in communication.
6 MIFARE_Read() failed: Timeout in communication.
5 MIFARE_Read() failed: Timeout in communication.
4 MIFARE_Read() failed: Timeout in communication.
3 MIFARE_Read() failed: Timeout in communication.
2 MIFARE_Read() failed: Timeout in communication.
1 MIFARE_Read() failed: Timeout in communication.
0 MIFARE_Read() failed: Timeout in communication.
255 MIFARE_Read() failed: Timeout in communication.
254 MIFARE_Read() failed: Timeout in communication.
253 MIFARE_Read() failed: Timeout in communication…


#143

@Ambition1906, it should be able to read the Ultralight cards from what I can read. What happens when you use the other library you used?


#144

@peekay123, when I use the other library here is the output:

Card NOT detected:
Card NOT detected:
Card NOT detected:
Card detected:
88 4 3F C3 70
Card NOT detected:
Card detected:
88 4 3F C3 70
Card NOT detected:
Card detected:
88 4 3F C3 70
Card NOT detected:
Card NOT detected:
Card NOT detected:
Card NOT detected:
Card NOT detected:
Card NOT detected:
Card NOT detected:
Card detected:
83 B0 E3 C7 17
Card NOT detected:
Card detected:
83 B0 E3 C7 17
Card NOT detected:
Card detected:
83 B0 E3 C7 17
Card NOT detected:
Card NOT detected:
Card NOT detected:

It works for both card types. The Card ID “88 4 3F C3 70” is the Ultralight card and the Card ID “83 B0 E3 C7 17” is the 1K.