RFID and NRF24L01 Wireless Network Coding Issues



  • I am currently working on a project where I am interfacing an RFID-RC522 with a NRF24L01 transceiver on a single Arduino. Ultimately what I would like to have is one RFID-RC522 and NRF24L01 on one arduino, where the RFID can read the UID off of PICC cards, and the connected NRF24L01 can send the UID data to a master NRF24L01 on a different Arduino controller. Currently I am having issues with debugging and coding.

    Here is what I have achieved so far:

    For the wiring, I used @BartE Garage Door example for the hardware. Here is what he did: garage door example. The pins are set up as follows:

    The NRF24L01+ is connect as suggested on the MySensors site:

    pin 2 IRQ (I did not have this one connected as I do not believe it is needed in this project. Correct me if this is wrong).
    pin 9 CE
    pin 10 CSN/CS
    pin 11 MOSI
    pin 12 MISO
    pin 13 SCK

    The RC522 module shares pins: (these I connected together on the same row on a prototype board)

    pin 11 MOSI
    pin 12 MISO
    pin 13 SCK

    and uses

    pin 3.3 V (also shared with the NRF24L01) connected together on prototype board
    GND (for ground)
    pin 7 (iso 9) for CE
    pin 8 (iso 10) for CSN/CS.

    That is the hardware portion of it. Here is the code I have cut and figured out thus far using the garage door example and own research from the mysenors website. I started off adding line by line of code until I ran into problems. Main issue right now is the gw.begin(); not sure if using this function correctly. One main thing I noticed was I had an error with radio inti begin when I first began. I had to go into config.h and change the data rate on the RF24 to 1MPBS rather than the default 250KBPS. That is involved in this gw.begin() instance, and I put that in but it did not solve the problem.

    But there may also be other things I am missing as well. Any help would be greatly appreciated.

    The following is the code I have made thus far. Ultimately I would like to scan a UID on the RFID and have it sent to the NRF24L01 module to be read out on the serial monitor AND to send it to a NRF24L01 master module (to be set up on a different arduino.)

    #include <SPI.h> //used for SPI bus
    #include <MFRC522.h> //used for RFID reader
    #include <MySensor.h> //library that uses SPI
    
    
    #define RST_PIN     7       //  MFRC RST is used in pin 7
    #define SS_PIN      8       //  MFRC SS is used in pin 8
    
    
    MFRC522      mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    #define    RFID    1
    
    //construct instance of NRF24 
    MyTransportNRF24 transport(9, 10);
     
    MySensor gw; //create MySensor instance
    
    MyMessage msg(RFID, V_VAR1); //create MyMessage instance; this holds message data 
                                 //and has helpers for setting payload
    
    void setup() 
    { 
        Serial.begin(115200);     // Initialize serial communications with the PC
    
      // Make sure MFRC will be disabled on the SPI bus
        pinMode(RST_PIN, OUTPUT);  //set the RST pin as output   
        digitalWrite(RST_PIN, LOW); //set RST pin off
        pinMode(SS_PIN, OUTPUT); //set SS pin as output    
        digitalWrite(SS_PIN, LOW); //set SS pin off
    
      //initialize radio and start library       
      gw.begin(incomingMessage, RFID, RF24_1MBPS);
      gw.sendSketchInfo("RFID Radio", "1.0");
    
      //must present sensors before reporting data to controller
      gw.present(RFID, S_CUSTOM); 
      gw.wait(125);
    
      SPI.begin();            // Init SPI bus
      mfrc522.PCD_Init();     // Init MFRC522
      mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details*/
      
      Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
    }
     
    void loop()
    {
    //main issue area here; wasn't sure what to do
         delay(10000); // Wait 10 seconds
         gw.process();
         
    }
    
    void incomingMessage(const MyMessage &message)
    {
      // Look for new cards
     if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }
    
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
      }
    
      // Dump debug info about the card; PICC_HaltA() is automatically called
      mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
      Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
    }Here
    

    Here are the two coding programs for the RFID and NRF24L01 that I am using to base code off of and also what I tested the hardware with initially:

    For the RFID: MCRF522 class from Git Hub; Dump Info Example: (I tested this on the RFID separately before interfacing with the NRF24L01 on one arduino):

    
    #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() {
    	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
    	mfrc522.PCD_DumpVersionToSerial();	// Show details of PCD - MFRC522 Card Reader details
    	Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
    }
    
    void loop() {
    	// Look for new cards
    	if ( ! mfrc522.PICC_IsNewCardPresent()) {
    		return;
    	}
    
    	// Select one of the cards
    	if ( ! mfrc522.PICC_ReadCardSerial()) {
    		return;
    	}
    
    	// Dump debug info about the card; PICC_HaltA() is automatically called
    	mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
    }
    

    For the NRF24L01 transceiver, I originally did hardware testing there were two modules--one for receiving and one for transmitting. So two NRF24L01 modules in all. Each was connected to its own Arduino and then connected to the same laptop with two separate USB cables. I ran two separate Arduino environments on two different serial monitors. I used the GettingStarted Example from the RF24 class off of Git Hub. There is one code for one module below. For the other module, I just switched bool radioNumber = 0 to = 1. This website was helpful for this.

    /*
    * Getting Started example sketch for nRF24L01+ radios
    * This is a very basic example of how to send data from one node to another
    * Updated: Dec 2014 by TMRh20
    */
    
    #include <SPI.h>
    #include "RF24.h"
    
    /****************** User Config ***************************/
    /***      Set this radio as radio number 0 or 1         ***/
    bool radioNumber = 0;
    
    /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
    RF24 radio(7,8);
    /**********************************************************/
    
    byte addresses[][6] = {"1Node","2Node"};
    
    // Used to control whether this node is sending or receiving
    bool role = 0;
    
    void setup() {
      Serial.begin(115200);
      Serial.println(F("RF24/examples/GettingStarted"));
      Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
      
      radio.begin();
    
      // Set the PA Level low to prevent power supply related issues since this is a
     // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
      radio.setPALevel(RF24_PA_LOW);
      
      // Open a writing and reading pipe on each radio, with opposite addresses
      if(radioNumber){
        radio.openWritingPipe(addresses[1]);
        radio.openReadingPipe(1,addresses[0]);
      }else{
        radio.openWritingPipe(addresses[0]);
        radio.openReadingPipe(1,addresses[1]);
      }
      
      // Start the radio listening for data
      radio.startListening();
    }
    
    void loop() {
      
      
    /****************** Ping Out Role ***************************/  
    if (role == 1)  {
        
        radio.stopListening();                                    // First, stop listening so we can talk.
        
        
        Serial.println(F("Now sending"));
    
        unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
         if (!radio.write( &start_time, sizeof(unsigned long) )){
           Serial.println(F("failed"));
         }
            
        radio.startListening();                                    // Now, continue listening
        
        unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
        boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not
        
        while ( ! radio.available() ){                             // While nothing is received
          if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
              timeout = true;
              break;
          }      
        }
            
        if ( timeout ){                                             // Describe the results
            Serial.println(F("Failed, response timed out."));
        }else{
            unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
            radio.read( &got_time, sizeof(unsigned long) );
            unsigned long end_time = micros();
            
            // Spew it
            Serial.print(F("Sent "));
            Serial.print(start_time);
            Serial.print(F(", Got response "));
            Serial.print(got_time);
            Serial.print(F(", Round-trip delay "));
            Serial.print(end_time-start_time);
            Serial.println(F(" microseconds"));
        }
    
        // Try again 1s later
        delay(1000);
      }
    
    
    
    /****************** Pong Back Role ***************************/
    
      if ( role == 0 )
      {
        unsigned long got_time;
        
        if( radio.available()){
                                                                        // Variable for the received timestamp
          while (radio.available()) {                                   // While there is data ready
            radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
          }
         
          radio.stopListening();                                        // First, stop listening so we can talk   
          radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.      
          radio.startListening();                                       // Now, resume listening so we catch the next packets.     
          Serial.print(F("Sent response "));
          Serial.println(got_time);  
       }
     }
    
    
    
    
    /****************** Change Roles via Serial Commands ***************************/
    
      if ( Serial.available() )
      {
        char c = toupper(Serial.read());
        if ( c == 'T' && role == 0 ){      
          Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
          role = 1;                  // Become the primary transmitter (ping out)
        
       }else
        if ( c == 'R' && role == 1 ){
          Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));      
           role = 0;                // Become the primary receiver (pong back)
           radio.startListening();
           
        }
      }
    
    
    } // Loop```
    

    Any help figuring this out would be greatly appreciated!


  • Mod

    did you figure out how to make it work?



  • Sit with the same scenario. Separately both function. As soon as you share miso, mosi and sck it fails to initialize the radio. Anybody knows whether you can share this ?

    Thanks



  • Found the solution in this thread:

    https://forum.mysensors.org/topic/2439/rfid-garage-door-opener/35

    void before() {
    // Make sure MFRC is disabled from the SPI bus
    pinMode(RST_PIN, OUTPUT);
    digitalWrite(RST_PIN, LOW);
    pinMode(SS_PIN, OUTPUT);
    digitalWrite(SS_PIN, LOW);
    }



  • At least in some first test I got a second SPI device (MCP4131) on the same wires working using the before() instruction.

    int CS1 = 10; //MCP4131
    void before() {
      pinMode (CS1, OUTPUT);
    digitalWrite(CS1, HIGH);
    }
    

    Another option may be to use SoftSPI for thenRF (see Network-Gateway-sketch).


  • Mod

    @martins
    Is it working for you?



  • @gohan Yes


  • Mod

    I can't figure out what is wrong with mine



  • @gohan What is the serial output or error that you get ?


  • Mod

    just look at the garage door opener link you posted, there is log and code. If I unplug the radio and use some demo code to read the rfid tag I can read it, but I can't find where it conflicts with the radio



  • @gohan This is the code that works for me on my pro mini. Try it out.

    Here is my pins used:

    MOSI: Pin 11
    MISO: Pin 12
    SCK : Pin 13
    SS : Pin 8 (Configurable)
    RST : Pin 6 (Configurable)

    /*
      Arduino RFID Access Control
    
      Security !
    
      To keep it simple we are going to use Tag's Unique IDs
      as only method of Authenticity. It's simple and not hacker proof.
      If you need security, don't use it unless you modify the code
    
      Copyright (C) 2015 Omer Siar Baysal
    
      This program is free software; you can redistribute it and/or modify
      it under the terms of the GNU General Public License as published by
      the Free Software Foundation; either version 2 of the License, or
      (at your option) any later version.
    
      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.
    
      You should have received a copy of the GNU General Public License along
      with this program; if not, write to the Free Software Foundation, Inc.,
      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    
    */
    #define MY_DEBUG 
    
    #define MY_RADIO_NRF24
    //#define MY_RF24_PA_LEVEL RF24_PA_LOW
    
    //#define MY_RADIO_RFM69
    //#define MY_RFM69_FREQUENCY RF69_433MHZ
    //#define MY_IS_RFM69HW
    
    #if F_CPU == 8000000L
    #define MY_BAUD_RATE 38400
    #endif
    
    
    #define CHILD_ID 8
    #define MAX_CARDS       18
    
    #include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
    #include <SPI.h>        // RC522 Module uses SPI protocol
    #include <MFRC522.h>	// Library for Mifare RC522 Devices
    #include <MySensors.h>
    
    /*
    	For visualizing whats going on hardware
    	we need some leds and
    	to control door lock a relay and a wipe button
    	(or some other hardware)
    	Used common anode led,digitalWriting HIGH turns OFF led
    	Mind that if you are going to use common cathode led or
    	just seperate leds, simply comment out #define COMMON_ANODE,
    */
    
    int value=0;
    
    boolean match = false;          // initialize card match to false
    boolean programMode = false;	// initialize programming mode to false
    boolean replaceMaster = false;
    
    int successRead;		// Variable integer to keep if we have Successful Read from Reader
    
    byte storedCard[4];		// Stores an ID read from EEPROM
    byte readCard[4];		// Stores scanned ID read from RFID Module
    byte masterCard[4];		// Stores master card's ID read from EEPROM
    byte countValidCards = 0;
    /*
    	We need to define MFRC522's pins and create instance
    	Pin layout should be as follows (on Arduino Uno):
    	MOSI: Pin 11 / ICSP-4
    	MISO: Pin 12 / ICSP-1
    	SCK : Pin 13 / ICSP-3
    	SS : Pin 10 (8)(Configurable)
    	RST : Pin 9 (6)(Configurable)
    	look MFRC522 Library for
    	other Arduinos' pin configuration
    */
    
    // bool lockStatus;
    
    #define SS_PIN 8
    #define RST_PIN 6
    
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance.
    // MFRC522::Uid validCards[MAX_CARDS];
    
    //MyMessage lockMsg(CHILD_ID, V_LOCK_STATUS);
    
    MyMessage msg(CHILD_ID,V_TRIPPED);
    
    
    // MFRC522 mfrc522(SS_PIN, RST_PIN);	// Create MFRC522 instance.
    
    
    ///////////////////////////////////////// Setup ///////////////////////////////////
    void setup() {
      //Protocol Configuration
      //Serial.begin(9600);	 // Initialize serial communications with PC
      
      pinMode(RST_PIN, OUTPUT);
      digitalWrite(RST_PIN, LOW);
      pinMode(SS_PIN, OUTPUT);
      digitalWrite(SS_PIN, LOW);
      
      SPI.begin();           // MFRC522 Hardware uses SPI protocol
      mfrc522.PCD_Init();    // Initialize MFRC522 Hardware
    
      //If you set Antenna Gain to Max it will increase reading distance
      //mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
    
      Serial.println(F("Access Control v3.4"));   // For debugging purposes
      ShowReaderDetails();	// Show details of PCD - MFRC522 Card Reader details
    
      if (EEPROM.read(500) != 143) {
        Serial.println(F("No Master Card Defined"));
        Serial.println(F("Scan A PICC to Define as Master Card"));
        do {
          successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0
        }
        while (!successRead);                  // Program will not go further while you not get a successful read
    
    //    printHex(mfrc522.uid.uidByte, mfrc522.uid.size);
        
        for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
          EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
        }
          
        EEPROM.write(500, 143);                  // Write to EEPROM we defined Master Card.
        delay(500);
        
        Serial.println(F("Master Card Defined"));
    //    storeEeprom();
      }
      Serial.println(F("-------------------"));
      Serial.println(F("Master Card's UID"));
      for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
        masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
        Serial.print(masterCard[i], HEX);
      }
    
      Serial.println("");
      Serial.println(F("-------------------"));
      Serial.println(F("Everything Ready"));
      Serial.println(F("Waiting PICCs to be scanned"));
      Serial.println(EEPROM.read(500));
    }
    
    void presentation() {
      // Register binary input sensor to gw (they will be created as child devices)
      // You can use S_DOOR, S_MOTION or S_LIGHT here depending on your usage. 
      // If S_LIGHT is used, remember to update variable type you send in. See "msg" above.
      sendSketchInfo("RFID Gate", "1.0");
      present(CHILD_ID, S_DOOR);  
    }
    
    ///////////////////////////////////////// Main Loop ///////////////////////////////////
    void loop () {
      send(msg.set(value==HIGH ? 1 : 0));
      do {
        successRead = getID(); 	// sets successRead to 1 when we get read from reader otherwise 0
      }
      while (!successRead); 	//the program will not go further while you not get a successful read
    
      if (programMode) {
        if ( isMaster(readCard) ) { //If master card scanned again exit program mode
          Serial.println(F("Master Card Scanned"));
          Serial.println(F("Exiting Program Mode"));
          Serial.println(F("-----------------------------"));
          programMode = false;
          return;
        }
        else {
          if ( findID(readCard) ) { // If scanned card is known delete it
            Serial.println(F("I know this PICC, removing..."));
            deleteID(readCard);
            Serial.println("-----------------------------");
            Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
          }
          else {                    // If scanned card is not known add it
            Serial.println(F("I do not know this PICC, adding..."));
            writeID(readCard);
            Serial.println(F("-----------------------------"));
            Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
          }
        }
      }
      else {
        if ( isMaster(readCard)) {  	// If scanned card's ID matches Master Card's ID enter program mode
          programMode = true;
          Serial.println(F("Hello Master - Entered Program Mode"));
          int count = EEPROM.read(0); 	// Read the first Byte of EEPROM that
          Serial.print(F("I have "));    	// stores the number of ID's in EEPROM
          Serial.print(count);
          Serial.print(F(" record(s) on EEPROM"));
          Serial.println("");
          Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
          Serial.println(F("Scan Master Card again to Exit Program Mode"));
          Serial.println(F("-----------------------------"));
        }
        else {
          if ( findID(readCard) ) {	// If not, see if the card is in the EEPROM
            Serial.println(F("Welcome, You shall pass"));
            granted(300);        	// Open the door lock for 300 ms
          }
          else {			// If not, show that the ID was not valid
            Serial.println(F("You shall not pass"));
            denied();
          }
        }
      }
    }
    
    /////////////////////////////////////////  Access Granted    ///////////////////////////////////
    void granted (int setDelay) {
      // setLockState(!lockStatus, true);
      value = 1;
      send(msg.set(value==HIGH ? 1 : 0));
      smartSleep(5000);
      value = 0;
      send(msg.set(value==HIGH ? 1 : 0));
    }
    
    ///////////////////////////////////////// Access Denied  ///////////////////////////////////
    void denied() {
    }
    
    
    ///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
    int getID() {
      // Getting ready for Reading PICCs
        if ( ! mfrc522.PICC_IsNewCardPresent())
        return 0;
    
      // Verify if the NUID has been readed
      if ( ! mfrc522.PICC_ReadCardSerial())
        return 0;
    
      Serial.print(F("PICC type: "));
      MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
      Serial.println(mfrc522.PICC_GetTypeName(piccType));
    
      // Check is the PICC of Classic MIFARE type
      if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&  piccType != MFRC522::PICC_TYPE_MIFARE_1K && piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
        Serial.println(F("Your tag is not of type MIFARE Classic."));
        return;
      }
      Serial.println(F("Scanned PICC's UID:"));
      for (int i = 0; i < 4; i++) {  //
        readCard[i] = mfrc522.uid.uidByte[i];
        Serial.print(readCard[i], HEX);
      }
      Serial.println("");
      mfrc522.PICC_HaltA();
      return 1;
    
    /*  while (! mfrc522.PICC_IsNewCardPresent()) 
      {;}
      if ( ! mfrc522.PICC_IsNewCardPresent()) 
      { //If a new PICC placed to RFID reader continue
        Serial.println("No NCP");
        return 0;
      }
      if ( ! mfrc522.PICC_ReadCardSerial()) 
      {   //Since a PICC placed get Serial and continue
        Serial.println("RCS");
        return 0;
      }
      // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
      // I think we should assume every PICC as they have 4 byte UID
      // Until we support 7 byte PICCs
      Serial.println(F("Scanned PICC's UID:"));
      for (int i = 0; i < 4; i++) {  //
        readCard[i] = mfrc522.uid.uidByte[i];
        Serial.print(readCard[i], HEX);
      }
      Serial.println("");
      mfrc522.PICC_HaltA(); // Stop reading
      return 1;
      */
      
    }
    
    void ShowReaderDetails() {
      // Get the MFRC522 software version
      byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
      Serial.print(F("MFRC522 Software Version: 0x"));
      Serial.print(v, HEX);
      if (v == 0x91)
        Serial.print(F(" = v1.0"));
      else if (v == 0x92)
        Serial.print(F(" = v2.0"));
      else
        Serial.print(F(" (unknown),probably a chinese clone?"));
      Serial.println("");
      // When 0x00 or 0xFF is returned, communication probably failed
      if ((v == 0x00) || (v == 0xFF)) {
        Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
        Serial.println(F("SYSTEM HALTED: Check connections."));
        while (true); // do not go further
      }
    }
    
    ///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
    void cycleLeds() {
    }
    
    //////////////////////////////////////// Normal Mode Led  ///////////////////////////////////
    void normalModeOn () {
    }
    
    //////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
    void readID( int number ) {
      int start = (number * 4 ) + 2; 		// Figure out starting position
      for ( int i = 0; i < 4; i++ ) { 		// Loop 4 times to get the 4 Bytes
        storedCard[i] = EEPROM.read(start + i); 	// Assign values read from EEPROM to array
      }
    }
    
    ///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
    void writeID( byte a[] ) {
      if ( !findID( a ) ) { 		// Before we write to the EEPROM, check to see if we have seen this card before!
        int num = EEPROM.read(0); 		// Get the numer of used spaces, position 0 stores the number of ID cards
        int start = ( num * 4 ) + 6; 	// Figure out where the next slot starts
        num++; 								// Increment the counter by one
        EEPROM.write( 0, num ); 		// Write the new count to the counter
        for ( int j = 0; j < 4; j++ ) { 	// Loop 4 times
          EEPROM.write( start + j, a[j] ); 	// Write the array values to EEPROM in the right position
        }
        successWrite();
        Serial.println(F("Succesfully added ID record to EEPROM"));
      }
      else {
        failedWrite();
        Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
      }
    }
    
    ///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
    void deleteID( byte a[] ) {
      if ( !findID( a ) ) { 		// Before we delete from the EEPROM, check to see if we have this card!
        failedWrite(); 			// If not
        Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
      }
      else {
        int num = EEPROM.read(0); 	// Get the numer of used spaces, position 0 stores the number of ID cards
        int slot; 			// Figure out the slot number of the card
        int start;			// = ( num * 4 ) + 6; // Figure out where the next slot starts
        int looping; 		// The number of times the loop repeats
        int j;
        int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
        slot = findIDSLOT( a ); 	// Figure out the slot number of the card to delete
        start = (slot * 4) + 2;
        looping = ((num - slot) * 4);
        num--; 			// Decrement the counter by one
        EEPROM.write( 0, num ); 	// Write the new count to the counter
        for ( j = 0; j < looping; j++ ) { 				// Loop the card shift times
          EEPROM.write( start + j, EEPROM.read(start + 4 + j)); 	// Shift the array values to 4 places earlier in the EEPROM
        }
        for ( int k = 0; k < 4; k++ ) { 				// Shifting loop
          EEPROM.write( start + j + k, 0);
        }
        successDelete();
        Serial.println(F("Succesfully removed ID record from EEPROM"));
      }
    }
    
    ///////////////////////////////////////// Check Bytes   ///////////////////////////////////
    boolean checkTwo ( byte a[], byte b[] ) {
      if ( a[0] != NULL ) 			// Make sure there is something in the array first
        match = true; 			// Assume they match at first
      for ( int k = 0; k < 4; k++ ) { 	// Loop 4 times
        if ( a[k] != b[k] ) 		// IF a != b then set match = false, one fails, all fail
          match = false;
      }
      if ( match ) { 			// Check to see if if match is still true
        return true; 			// Return true
      }
      else  {
        return false; 			// Return false
      }
    }
    
    ///////////////////////////////////////// Find Slot   ///////////////////////////////////
    int findIDSLOT( byte find[] ) {
      int count = EEPROM.read(0); 			// Read the first Byte of EEPROM that
      for ( int i = 1; i <= count; i++ ) { 		// Loop once for each EEPROM entry
        readID(i); 								// Read an ID from EEPROM, it is stored in storedCard[4]
        if ( checkTwo( find, storedCard ) ) { 	// Check to see if the storedCard read from EEPROM
          // is the same as the find[] ID card passed
          return i; 				// The slot number of the card
          break; 					// Stop looking we found it
        }
      }
    }
    
    ///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
    boolean findID( byte find[] ) {
      int count = EEPROM.read(0);			// Read the first Byte of EEPROM that
      for ( int i = 1; i <= count; i++ ) {  	// Loop once for each EEPROM entry
        readID(i); 					// Read an ID from EEPROM, it is stored in storedCard[4]
        if ( checkTwo( find, storedCard ) ) {  	// Check to see if the storedCard read from EEPROM
          return true;
          break; 	// Stop looking we found it
        }
        else {  	// If not, return false
        }
      }
      return false;
    }
    
    ///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
    // Flashes the green LED 3 times to indicate a successful write to EEPROM
    void successWrite() {
    }
    
    ///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
    // Flashes the red LED 3 times to indicate a failed write to EEPROM
    void failedWrite() {
    }
    
    ///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
    // Flashes the blue LED 3 times to indicate a success delete to EEPROM
    void successDelete() {
    }
    
    ////////////////////// Check readCard IF is masterCard   ///////////////////////////////////
    // Check to see if the ID passed is the master programing card
    boolean isMaster( byte test[] ) {
      if ( checkTwo( test, masterCard ) )
        return true;
      else
        return false;
    }
    
    /**
     * Helper routine to dump a byte array as hex values to Serial. 
     */
    void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
      }
    }
    
    
    //void presentation()  {
    //  sendSketchInfo("RFID Lock", "1.0");
    //  present(CHILD_ID, S_LOCK);
    //}
    
    void before() {
      // Make sure MFRC is disabled from the SPI bus
      pinMode(RST_PIN, OUTPUT);
      digitalWrite(RST_PIN, LOW);
      pinMode(SS_PIN, OUTPUT);
      digitalWrite(SS_PIN, LOW);
    }
    
    

  • Mod

    Tnx, I'll try in the next days.

    Ps I edited your post with the correct tag for the code



  • Help!

    I have a RFID RC522 module I'm trying to use instead of the PN532 NFC RFID Reader/Writer Module used in the RFID Lock Sensor example (https://www.mysensors.org/build/rfid).

    I thought I could use the sketch above posted by @martins but I get the following error message. I'm a newbie so I don't really know what I'm doing wrong?

    Arduino: 1.8.1 (Windows 10), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"
    
    Build options changed, rebuilding all
    C:\Users\arons\Documents\Arduino\Vera_RFID-RC522\Vera_RFID-RC522.ino: In function 'int getID()':
    
    Vera_RFID-RC522:259: error: return-statement with no value, in function returning 'int' [-fpermissive]
    
         return;
    
         ^
    
    exit status 1
    return-statement with no value, in function returning 'int' [-fpermissive]
    


  • @Aron-Sjöberg said in RFID and NRF24L01 Wireless Network Coding Issues:

    int getID()

    Change that line in the getID() function to return 0;


Log in to reply
 

Looks like your connection to MySensors Forum was lost, please wait while we try to reconnect.