Unable to get RFID-RC522 module to save into a array and test it

I'm trying to use a RFID-RC522 module and read a RFID tag and take the data (a number) and save it into a variable and use it to test for conditions.

I'm using the MFRC522 library ver1.4.1 by ryand1011 (ryand1011 (Ryan Diaz) · GitHub)

I can successfully read and write to RFID tags. I want to read the tag and test it in an if statement. I tried printing the buffer array and I keep getting numbers not matching the number in the RFID.

Thank you for any help.

Here is my code of the stripped down reader example (fid_write_personal_data.ino)

/*
 * Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * More pin layouts for other boards can be found here: https://github.com/miguelbalboa/rfid#pin-layout
*/

#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

//*****************************************************************************************//
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);

  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read
}

//*****************************************************************************************//
void loop() 
{
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {    return;  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())   {    return;  }

  Serial.println(F("**Card Detected:**"));

  //-------------------------------------------

  Serial.print(F("Name: "));

  byte buffer1[18];
  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  status = mfrc522.MIFARE_Read(block, buffer1, &len);

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();

}

I don;t see your efforts in the code.

Hi,
when you successfully read what you print on the serial?

Sorry, I removed the code to make it cleaner.

I just added Serial.print(buffer1[i]); and tried various nunbers for i i.e. 0, 1,15,16

I added my code at line 84

To program the tag I use the "rfid_write_personal_data.ino" example to add a number instead of a first name. I would use the number 7 and I would then switch to the "rfid_read_personal_data.ino" and see the number 7 in serial monitor.

It can be what you are looking for:

void readRFID()
{
  int j = -1;
  byte card_ID[4];                                                                                                                                            // card UID size 4byte

  const int numOfCards = 5;                                                                                                                                   // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x69, 0x38, 0xFD, 0x6E},{0x29, 0xCE, 0xE2, 0x6E},{0xD9, 0x45, 0xE5, 0x6E},{0xA9, 0x76, 0x47, 0xB8},{0x59, 0x3F, 0x16, 0x98}}; // array of UIDs of rfid cards

  if (!mfrc522.PICC_IsNewCardPresent())                                                                                                                       // look for new card
  {
    return;                                                                                                                                                   // got to start of loop if there is no card present
  }
  if (!mfrc522.PICC_ReadCardSerial())                                                                                                                         // Select one of the cards
  {
    return;                                                                                                                                                   // if read card serial(0) returns 1, the uid struct contians the ID of the read card.
  }

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    card_ID[i] = mfrc522.uid.uidByte[i];
  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {
      j = i;
    }
  }

  if(j == -1)  // check the card validity
  {
    Serial.println("Invalid");
  }
  else
  {
    Serial.println("Valid");
  }
}

Take a look in this example. I have used it as reference in a project.

I looked at the function and the reference project. Where would you call the function? Where in the code should i call your function? What variable or array can i test?

Try:

#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

void readRFID()
{
  int j = -1;
  byte card_ID[4];                                                                                                                                            // card UID size 4byte

  const int numOfCards = 5;                                                                                                                                   // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x73, 0x38, 0xD1, 0x02},{0x29, 0xCE, 0xE2, 0x6E},{0xD9, 0x45, 0xE5, 0x6E},{0xA9, 0x76, 0x47, 0xB8},{0x59, 0x3F, 0x16, 0x98}}; // array of UIDs of rfid cards

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    card_ID[i] = mfrc522.uid.uidByte[i];
  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {
      j = i;
    }
  }

  if(j == -1)  // check the card validity
  {
    Serial.println("Invalid");
  }
  else
  {
    Serial.println("Valid");
  }
}

void setup()
{
  Serial.begin(115200); // Initialize serial communications with the PC
  while (!Serial)       // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  {
  }
  SPI.begin();                       // Init SPI bus
  mfrc522.PCD_Init();                // Init MFRC522
  delay(4);                          // Optional delay. Some board do need more time after init to be ready, see Readme
  mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

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);
  }
}

void loop()
{
  if (mfrc522.PICC_IsNewCardPresent())
  {
    if (mfrc522.PICC_ReadCardSerial())
    {
      Serial.println(F("UID:"));
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println();
      readRFID();
    }
  }
}

Thank you for your help. I took your code and modified it a bit. I want a correct RFID to turn a pin high while it is present and to go low when the card is pulled away. The code makes the output_pin HIGH when the right RFID is read but stays on and goes LOW when the wrong RFID is read. Is there a function at that can be used where i marked in it in my code near the bottom that will test when a RFID is present.

Here is my code

#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

int card_status=0;
int output_pin=6;

void readRFID()
{
  int j = -1;
  byte card_ID[4];                                                                                                                                            // card UID size 4byte

  const int numOfCards = 1;                                                                                                                                   // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x4D, 0xD5, 0x93, 0xDA}}; // array of UIDs of rfid cards

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {    card_ID[i] = mfrc522.uid.uidByte[i];  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {      j = i;    }
  }

  if(j == -1)  // check the card validity
  {
        Serial.println("Invalid");
        card_status=0;
  }
  else
  {    
        Serial.println("Valid");  
        card_status=1;
  }
}

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(output_pin, OUTPUT);

  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial)       // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  {
  }
  SPI.begin();                       // Init SPI bus
  mfrc522.PCD_Init();                // Init MFRC522
  delay(4);                          // Optional delay. Some board do need more time after init to be ready, see Readme
  mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

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);
  }
}

void loop()
{
  if (mfrc522.PICC_IsNewCardPresent())
  {
    if (mfrc522.PICC_ReadCardSerial())
    {
      Serial.println(F("UID:"));
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println();
      readRFID();
      Serial.println(card_status);
    }
  }
      if(card_status==1 && "function that is true when a card is present" ){ digitalWrite(output_pin, HIGH);}
      else { digitalWrite(output_pin, LOW);}
}

Try:

#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

int menuIndex = 0;
const int output_pin = 6;

void readRFID()
{
  int j = -1;
  byte card_ID[4];                                        // card UID size 4byte

  const int numOfCards = 1;                               // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x4D, 0xD5, 0x93, 0xDA}}; // array of UIDs of rfid cards

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    card_ID[i] = mfrc522.uid.uidByte[i];
  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {
      j = i;
    }
  }

  if(j == -1)  // check the card validity
  {
    Serial.println("Invalid");
    menuIndex = 2;
  }
  else
  {
    Serial.println("Valid");
    menuIndex = 1;
  }
}

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(output_pin, OUTPUT);

  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial)     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  {
  }
  SPI.begin();                       // Init SPI bus
  mfrc522.PCD_Init();                // Init MFRC522
  delay(4);                          // Optional delay. Some board do need more time after init to be ready, see Readme
  mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

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);
  }
}

void loop()
{
  switch (menuIndex)
  {
    case 0:
      if (mfrc522.PICC_IsNewCardPresent())
      {
        if (mfrc522.PICC_ReadCardSerial())
        {
          Serial.println(F("UID:"));
          dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
          Serial.println();
          readRFID();
        }
      }
      break;
    case 1: // Access granted.
      digitalWrite(output_pin, HIGH);
      break;
    case 2: // Acess denied.
      digitalWrite(output_pin, LOW);
      menuIndex = 0;
      break;

    default:
      break;
  }
}

I tried your new code out. When i read a wrong card the serial monitor shows the following continuously

Invalid
UID:
89 9C C1 17

with the output LOW, but when i put the correct RFID the serial monitor outputs the following ONCE

UID:
4D D5 93 DA
Valid

and the OUTPUT is set HIGH and stays HIGH when i move the card away. Putting a wrong RFID on the scanner doesn't change the output or show anything on the serial monitor.

Thank you for your continued help.

Friend, it's only an example do you have to work on the code complete your goal.

You can make something like this

    case 1: // Access granted.
      digitalWrite(output_pin, HIGH);
      menuIndex = 3;
      break;
    case 3: // Restrict area
      digitalWrite(output_pin, LOW);
      // Do somenthing
      break;

I worked on the code and I have a sketch that behaves the way i want it. When the correct card the output goes high and when no card or the wrong card is near the output goes low. The only issue is when I bring the correct card near then far multiple times it stops responding for a while before it starts responding again after waiting a while. Is there something that is causing it to get stuck or there a buffer that gets filled?

#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

int card_status=0;
int output_pin=6;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(output_pin, OUTPUT);

  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial)       // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  {
  }
  SPI.begin();                       // Init SPI bus
  mfrc522.PCD_Init();                // Init MFRC522
  delay(4);                          // Optional delay. Some board do need more time after init to be ready, see Readme
  mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

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);
  }
}

void loop()
{
  if(mfrc522.PICC_IsNewCardPresent())
  {
    if (mfrc522.PICC_ReadCardSerial())
    {
      Serial.println(F("UID:"));
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println();
      readRFID();
      Serial.println(card_status);

      if(card_status==1)
      { digitalWrite(output_pin, HIGH);}
      if(card_status==0) 
      { digitalWrite(output_pin, LOW); }

    }
  }
  else if(mfrc522.PICC_IsNewCardPresent()!= HIGH)
  {
    digitalWrite(output_pin, LOW);  
    card_status=0;
    return;
  }

}

void readRFID()
{
  int j = -1;
  byte card_ID[4];                                                                                                                                            // card UID size 4byte

  const int numOfCards = 1;                                                                                                                                   // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x4D, 0xD5, 0x93, 0xDA}}; // array of UIDs of rfid cards

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {    card_ID[i] = mfrc522.uid.uidByte[i];  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {      j = i;    }
  }

  if(j == -1)  // check the card validity
  {   Serial.println("Invalid");  card_status=0;  }
  else
  {   Serial.println("Valid");  card_status=1;    }
}

Since you have ignored my code substantially I"ll quit from this discussion.

Sorry I was busy and had to take a break from the project and didn't get a chance to revisit the code and try your code segment.

I added your code segment to the code you posted before and when i use the correct RFID it reads it the UID and says valid and doesnt activate the output then any attempt with any RFID does activate the code.

#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

int menuIndex = 0;
const int output_pin = 6;

void readRFID()
{
  int j = -1;
  byte card_ID[4];                                        // card UID size 4byte

  const int numOfCards = 1;                               // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x4D, 0xD5, 0x93, 0xDA}}; // array of UIDs of rfid cards

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    card_ID[i] = mfrc522.uid.uidByte[i];
  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {
      j = i;
    }
  }

  if(j == -1)  // check the card validity
  {
    Serial.println("Invalid");
    menuIndex = 2;
  }
  else
  {
    Serial.println("Valid");
    menuIndex = 1;
  }
}

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(output_pin, OUTPUT);

  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial)     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  {
  }
  SPI.begin();                       // Init SPI bus
  mfrc522.PCD_Init();                // Init MFRC522
  delay(4);                          // Optional delay. Some board do need more time after init to be ready, see Readme
  mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

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);
  }
}

void loop()
{
  switch (menuIndex)
  {
    case 0:
      if (mfrc522.PICC_IsNewCardPresent())
      {
        if (mfrc522.PICC_ReadCardSerial())
        {
          Serial.println(F("UID:"));
          dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
          Serial.println();
          readRFID();
        }   
      }
      break;
    case 1: // Access granted.
      digitalWrite(output_pin, HIGH);
      menuIndex = 3;
      break;
    case 2: // Acess denied.
      digitalWrite(output_pin, LOW);
      menuIndex = 0;
      break;
    case 3: // Restrict area
      digitalWrite(output_pin, LOW);
      // Do somenthing
      break;

    default:
      break;
  }
}

Change your readRFID() this way:

boolean readRFID()
{
 
  byte card_ID[4];                                        // card UID size 4byte

  const int numOfCards = 1;                               // the nuber of cards used. this can change as you want
  byte cards[numOfCards][4] = {{0x4D, 0xD5, 0x93, 0xDA}}; // array of UIDs of rfid cards

  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    card_ID[i] = mfrc522.uid.uidByte[i];
  }

  for (int i = 0; i < numOfCards; i++)
  {
    if ((card_ID[0] == cards[i][0]) && (card_ID[1] == cards[i][1]) && (card_ID[2] == cards[i][2]) && (card_ID[3] == cards[i][3]))
    {
    return true;
    }
  }

 return false;
}

and loop() like this:

void loop()
{
 
      if (mfrc522.PICC_IsNewCardPresent())
      {
        if (mfrc522.PICC_ReadCardSerial())
        {
          Serial.println(F("UID:"));
          dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
          Serial.println();
          if (readRFID()) {
          // Access granted.
            digitalWrite(output_pin, HIGH);
            Serial.println("Valid");
           }
          else {
        // Access denied
            digitalWrite(output_pin, LOW);
            Serial.println("Invalid");
           }
        }   
        else digitalWrite(output_pin, LOW);    // if card serial unreadable
      }
      else digitalWrite(output_pin, LOW);     // if card not present
}

I tried your code and when i put the correct RFID tag the output chatters on and off as i hold the RFID next to the reader. The serial output also continuously reads Valid and the UID

Its normal, your code reads card continuously.

Its shouldn't be
Please edit the loop this way:

void loop()
{
 
      if (mfrc522.PICC_IsNewCardPresent())
      {
        if (mfrc522.PICC_ReadCardSerial())
        {
          Serial.println(F("UID:"));
          dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
          Serial.println();
          if (readRFID()) {
          // Access granted.
            digitalWrite(output_pin, HIGH);
            Serial.println("Valid");
           }
          else {
        // Access denied
            digitalWrite(output_pin, LOW);
            Serial.println("Invalid");
           }
        }   
        else {digitalWrite(output_pin, LOW);    // if card serial unreadable
                  Serial.println("Unable to read card serial!"); }
      }
      else  {digitalWrite(output_pin, LOW);     // if card not present
                Serial.println("Card not present"); }
}

and show what you see in the Arduino Monitor

I tried the new code and it still chatters just slower. When no card is present it repeats "Card not present" and when the correct card is present it repeats valid and the UID and chatters. Thank you for the continued help.

Could you please show the full code?