Navigation

    • Register
    • Login
    • OpenHardware.io
    • Categories
    • Recent
    • Tags
    • Popular
    1. Home
    2. Ispandy
    3. Posts
    • Profile
    • Following
    • Followers
    • Topics
    • Posts
    • Best
    • Groups

    Posts made by Ispandy

    • RE: RFID and NRF24L01 Wireless Network Coding Issues

      @evb thank you for the response, and sorry for late reply.
      As I mentioned above, that node 3 is running as it should, and I've copied it to node 50 and it's also running normally. The problem is on sketch node 50 when i click the switch in openhab the relay doesn't respond but when i scan the card on rfid, the relay responds. Unlike node 3, the relay responds to both card scans and openhab.
      Regards,

      posted in Troubleshooting
      Ispandy
      Ispandy
    • RE: RFID and NRF24L01 Wireless Network Coding Issues

      @evb yes i have 2 nodes (node 3 and node 50) all with MRFC522 right now, the node 3 is working perfectly but i dont like add and remove card system, I just want to change the part of the RFID sketch on node 3 using the sketch above, so i make one node for test (node 50) and put the code

      send(lockMsg.set(false));
      

      and

      send(lockMsg.set(true));
      

      to this

      void granted ( uint16_t setDelay) {
        digitalWrite(blueLed, LED_OFF);   // Turn off blue LED
        digitalWrite(redLed, LED_OFF);  // Turn off red LED
        digitalWrite(greenLed, LED_ON);   // Turn on green LED
        digitalWrite(relay, LOW);     // Unlock door!
        send(lockMsg.set(false));
        delay(setDelay);          // Hold door lock open for given seconds
        digitalWrite(relay, HIGH);    // Relock door
        send(lockMsg.set(true));
        delay(1000);            // Hold green LED on for a second
      }
      

      and i add this to node 50

      if (message.type == V_LOCK_STATUS) {
          // Change relay state
          if (!message.getBool()) {
            granted(300);
          }
      
          // Write some debug info
          Serial.print(F("Lock status: "));
          Serial.println(message.getBool());
        }
          else
          {
            // Write some debug info
            Serial.print(F("Incoming msg type: "));
            Serial.print(message.type);
            Serial.print(F(" id: "));
            Serial.print(message.sensor);
            Serial.print(F(" content: "));
            Serial.println(message.getInt());
          }
      

      nothing happen...

      sketch Node 3

      /
      // Enable debug prints
      #define MY_DEBUG
      #define MY_NODE_ID 3
      // Enable and select radio type attached
      #define MY_RADIO_RF24
      //#define MY_RF24_CHANNEL  10 
      #include <MySensors.h>
      #include <SPI.h>
      #include <MFRC522.h> 
      #include <Bounce2.h>
      
      #define RF_INIT_DELAY   125
      #define ONE_SEC         1000
      #define MAX_CARDS       18
      #define PROG_WAIT       10
      #define HEARTBEAT       10
      #define BAUD            115200
      
      /*Pin definitions*/
      #define LED_PIN         4
      #define GARAGEPIN       2
      #define SWITCH_PIN      3
      #define RST_PIN   7   //  MFRC 
      #define SS_PIN    8   //  MFRC 
      
      MFRC522      mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
      MFRC522::Uid olduid;
      MFRC522::Uid masterkey = { 4,{ 0xEF,0xDB,0x8E,0x79 },0 };
      
      byte       countValidCards = 0;
      MFRC522::Uid validCards[MAX_CARDS];
      
      void       ShowCardData(MFRC522::Uid* uid);
      bool       sameUid(MFRC522::Uid* old, MFRC522::Uid* check);
      void       copyUid(MFRC522::Uid* src, MFRC522::Uid* dest);
      bool       isValidCard(MFRC522::Uid* uid);
      int        releasecnt = 0;
      
      //#define    CHILD_ID_ALARM    2
      #define    CHILD_ID_LOCK     1
      Bounce     debouncer = Bounce();
      
      int        oldSwitchValue = -1;
      int        switchValue = 0;
      long       timer = -1;
      bool       programmode = false;
      bool       ledon;
      int        programTimer = 0;
      bool       armed = true;
      unsigned long lastTime = 0;
      
      MyMessage  lockMsg(CHILD_ID_LOCK, V_LOCK_STATUS);
      //MyMessage  lockArmMsg(CHILD_ID_ALARM, V_ARMED);
      //MyMessage  wrongMsg(CHILD_ID_ALARM, V_TRIPPED);
      
      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);
      }
      
      void presentation() {
        sendSketchInfo("RFID Garage", "1.1"); delay(RF_INIT_DELAY);
        // Register all sensors to gw (they will be created as child devices)
      
        present(CHILD_ID_LOCK, S_LOCK);      delay(RF_INIT_DELAY);
        //present(CHILD_ID_ALARM, S_MOTION);   delay(RF_INIT_DELAY);
      }
      
      void setup() {
        Serial.begin(BAUD);   // Initialize serial communications with the PC
        pinMode(GARAGEPIN, OUTPUT);     // Initialise in/output ports
      
                        // Make sure MFRC will be disabled on the SPI bus
        /*pinMode(RST_PIN, OUTPUT);
        digitalWrite(RST_PIN, LOW);
        pinMode(SS_PIN, OUTPUT);
        digitalWrite(SS_PIN, LOW);*/
      
        pinMode(LED_PIN, OUTPUT);
        digitalWrite(LED_PIN, LOW);
        // Setup the button
        pinMode(SWITCH_PIN, INPUT);
        // Activate internal pull-up
        digitalWrite(SWITCH_PIN, HIGH);
      
        // After setting up the button, setup debouncer
        debouncer.attach(SWITCH_PIN);
        debouncer.interval(5);
      
        // Init mysensors library
        
        /*sendSketchInfo("RFID Garage", "1.1"); delay(RF_INIT_DELAY);
      
        // Register all sensors to gw (they will be created as child devices)
        present(CHILD_ID_LOCK, S_LOCK);      delay(RF_INIT_DELAY);
        present(CHILD_ID_ALARM, S_MOTION);   delay(RF_INIT_DELAY);*/
      
        recallEeprom();
      
        // Init MFRC RFID sensor
        SPI.begin();      // Init SPI bus
        mfrc522.PCD_Init();   // Init MFRC522
        ShowReaderDetails();          // Show details of PCD - MFRC522 Card Reader details
      
        //send(lockArmMsg.set(armed));
        Serial.println(F("Init done..."));
      }
      
      void loop() {
        timer++;
        delay(HEARTBEAT);
        debouncer.update();
      
        // Get the update value
        int switchValue = debouncer.read();
        if (switchValue != oldSwitchValue) {
          // Send in the new value
          Serial.print(F("Switch "));
          Serial.println(switchValue);
      
          if (switchValue && programmode) {
            lastTime = millis() / 1000;
          }
      
          if (!switchValue && programmode && lastTime > 0) {
            if ((millis() / 1000) - lastTime > 3) {
              Serial.println(F("Reset all cards"));
              countValidCards = 0;
              blinkFast(50);
            }
            else {
              Serial.println(F("Program off"));
              digitalWrite(LED_PIN, LOW);
              programmode = false;
      
              storeEeprom();
            }
          }
      
          if (!switchValue) {
            programTimer = 0;
          }
          oldSwitchValue = switchValue;
        }
      
        if (programmode && ((timer % (ONE_SEC / HEARTBEAT)) == 0)) {
          ledon = !ledon;
          digitalWrite(LED_PIN, ledon);
          programTimer++;
      
          // Stop program mode after 20 sec inactivity
          if (programTimer > PROG_WAIT) {
            programmode = false;
            digitalWrite(LED_PIN, false);
            Serial.println(F("Program expired"));
          }
        }
      
        if ((timer % (200 / HEARTBEAT)) == 0) {
          // Look for new cards
          if (!mfrc522.PICC_IsNewCardPresent()) {
            if (releasecnt > 0) {
              releasecnt--;
              if (!releasecnt) {
                olduid.size = 0;
                Serial.println(F("release"));
              }
            }
            return;
          }
          releasecnt = 5;
      
          // 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));
          if (!olduid.size || !sameUid(&(mfrc522.uid), &olduid)) {
            ShowCardData(&(mfrc522.uid));
            copyUid(&(mfrc522.uid), &olduid);
            if (isValidCard(&olduid)) {
              OpenDoor(false);
            }
            else {
      
              if (sameUid(&(mfrc522.uid), &masterkey)) {
                // Only switch in program mode when mastercard is found AND the program button is pressed
                if (switchValue) {
                  Serial.println(F("Program mode"));
                  programmode = true;
                  programTimer = 0;
                  lastTime = 0;
                }
              }
              else {
                if (programmode) {
                  Serial.println(F("new card"));
                  programTimer = 0;
      
                  if (countValidCards < MAX_CARDS)
                  {
                    // Add card to list...
                    copyUid(&(mfrc522.uid), &validCards[countValidCards]);
                    countValidCards++;
                    blinkFast(15);
                  }
                }
                else {
                  Serial.println(F("Invalid card"));
                  //if (armed) {
                   // send(wrongMsg.set(1));
                   // delay(2000);
                    //send(wrongMsg.set(0));
                  //}
                }
              }
            }
          }
        }
      }
      
      void ShowCardData(MFRC522::Uid* uid) {
        Serial.print(F("Card UID:"));
        for (byte i = 0; i < uid->size; i++) {
          if (uid->uidByte[i] < 0x10) {
            Serial.print(F(" 0"));
          }
          else {
            Serial.print(F(" "));
          }
          Serial.print(uid->uidByte[i], HEX);
        }
        Serial.println();
      }
      
      void copyUid(MFRC522::Uid* src, MFRC522::Uid* dest)
      {
        dest->size = src->size;
        dest->sak = src->sak;
      
        for (byte i = 0; i < src->size; i++) {
          dest->uidByte[i] = src->uidByte[i];
        }
      }
      
      bool sameUid(MFRC522::Uid* old, MFRC522::Uid* check)
      {
        if (old->size != check->size) {
          return false;
        }
        for (byte i = 0; i < old->size; i++) {
          if (old->uidByte[i] != check->uidByte[i]) {
            return false;
          }
        }
        return true;
      }
      
      bool isValidCard(MFRC522::Uid* uid)
      {
        for (byte i = 0; i < countValidCards; i++) {
          if (validCards[i].size != uid->size) {
            break;
          }
          for (int j = 0; j < uid->size; j++) {
            if (validCards[i].uidByte[j] != uid->uidByte[j]) {
              break;
            }
            if (j == (uid->size - 1)) {
              return true;
            }
          }
        }
        return false;
      }
      
      
      void storeEeprom()
      {
        byte address = 0;
        saveState(address++, countValidCards);
      
        for (byte i = 0; i < countValidCards; i++) {
          saveState(address++, validCards[i].size);
          for (byte j = 0; j < 10; j++) {
            saveState(address++, validCards[i].uidByte[j]);
          }
        }
      }
      
      void recallEeprom()
      {
        byte address = 0;
      
        countValidCards = loadState(address++);
        if (countValidCards > MAX_CARDS) {
          Serial.println(F("Not a valid EEPROM reading set to default"));
          countValidCards = 0;
          storeEeprom();
          return;
        }
      
        for (byte i = 0; i < countValidCards; i++) {
          validCards[i].size = loadState(address++);
          for (byte j = 0; j < 10; j++) {
            validCards[i].uidByte[j] = loadState(address++);
          }
        }
      
      }
      
      void blinkFast(int times)
      {
        for (int i = 0; i < times; i++) {
          ledon = !ledon;
          digitalWrite(LED_PIN, ledon);
          delay(100);
        }
      }
      
      void OpenDoor(bool fakeOpen)
      {
        Serial.println(F("Open door!"));
        send(lockMsg.set(false));
      
        if (!fakeOpen) {
          digitalWrite(LED_PIN, HIGH);
          digitalWrite(GARAGEPIN, HIGH);
        }
        
        delay(1000);
      
        if (!fakeOpen) {
          digitalWrite(GARAGEPIN, LOW);
          digitalWrite(LED_PIN, LOW);
        }
      
        send(lockMsg.set(true));
      }
      
      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)"));
        }
        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?"));
        }
      }
      
      
      void receive(const MyMessage &message)
      {
        if (message.type == V_LOCK_STATUS) {
          // Change relay state
          if (!message.getBool()) {
            OpenDoor(false);
          }
      
          // Write some debug info
          Serial.print(F("Lock status: "));
          Serial.println(message.getBool());
        }
        /*else
        {
          if (message.type == V_ARMED) {
            // Change relay state
            armed = message.getBool();
      
            // Write some debug info
            Serial.print(F("Arm status: "));
            Serial.println(message.getBool());
          }*/
          else
          {
            // Write some debug info
            Serial.print(F("Incoming msg type: "));
            Serial.print(message.type);
            Serial.print(F(" id: "));
            Serial.print(message.sensor);
            Serial.print(F(" content: "));
            Serial.println(message.getInt());
          }
        }
      //}
      

      I'm not good at programming that's why I'm asking for help😑 😑

      posted in Troubleshooting
      Ispandy
      Ispandy
    • RE: RFID and NRF24L01 Wireless Network Coding Issues

      @evb, thank you for the reply
      In that sketch above the node doesn't receive message from openhab, but the other node using same message type "message.type == V_LOCK_STATUS" it does receive message from openhab.

      posted in Troubleshooting
      Ispandy
      Ispandy
    • RE: RFID and NRF24L01 Wireless Network Coding Issues

      Hi everyone,
      I have problem on RFID sketch, when i scan the card its unlock the door but when i switch from openhab its not unlock.

      the sketch is

      
      /*
         --------------------------------------------------------------------------------------------------------------------
         Example sketch/program showing An Arduino Door Access Control featuring RFID, EEPROM, Relay
         --------------------------------------------------------------------------------------------------------------------
         This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
         This example showing a complete Door Access Control System
        Simple Work Flow (not limited to) :
                                           +---------+
        +----------------------------------->READ TAGS+^------------------------------------------+
        |                              +--------------------+                                     |
        |                              |                    |                                     |
        |                              |                    |                                     |
        |                         +----v-----+        +-----v----+                                |
        |                         |MASTER TAG|        |OTHER TAGS|                                |
        |                         +--+-------+        ++-------------+                            |
        |                            |                 |             |                            |
        |                            |                 |             |                            |
        |                      +-----v---+        +----v----+   +----v------+                     |
        |         +------------+READ TAGS+---+    |KNOWN TAG|   |UNKNOWN TAG|                     |
        |         |            +-+-------+   |    +-----------+ +------------------+              |
        |         |              |           |                |                    |              |
        |    +----v-----+   +----v----+   +--v--------+     +-v----------+  +------v----+         |
        |    |MASTER TAG|   |KNOWN TAG|   |UNKNOWN TAG|     |GRANT ACCESS|  |DENY ACCESS|         |
        |    +----------+   +---+-----+   +-----+-----+     +-----+------+  +-----+-----+         |
        |                       |               |                 |               |               |
        |       +----+     +----v------+     +--v---+             |               +--------------->
        +-------+EXIT|     |DELETE FROM|     |ADD TO|             |                               |
                +----+     |  EEPROM   |     |EEPROM|             |                               |
                           +-----------+     +------+             +-------------------------------+
         Use a Master Card which is act as Programmer then you can able to choose card holders who will granted access or not
       * **Easy User Interface**
         Just one RFID tag needed whether Delete or Add Tags. You can choose to use Leds for output or Serial LCD module to inform users.
       * **Stores Information on EEPROM**
         Information stored on non volatile Arduino's EEPROM memory to preserve Users' tag and Master Card. No Information lost
         if power lost. EEPROM has unlimited Read cycle but roughly 100,000 limited Write cycle.
       * **Security**
         To keep it simple we are going to use Tag's Unique IDs. It's simple and not hacker proof.
         @license Released into the public domain.
         Typical pin layout used:
         -----------------------------------------------------------------------------------------
                     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
      */
      #define MY_DEBUG
      #define MY_RADIO_RF24
      #define MY_NODE_ID 50
      
      #include <SPI.h>        // RC522 Module uses SPI protocol
      #include <MFRC522.h>  // Library for Mifare RC522 Devices
      #include <MySensors.h>
      
      /*
        Instead of a Relay you may want to use a servo. Servos can lock and unlock door locks too
        Relay will be used by default
      */
      #define RFID 1
      
      // #include <Servo.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,
      */
      
      //#define COMMON_ANODE
      
      #ifdef COMMON_ANODE
      #define LED_ON LOW
      #define LED_OFF HIGH
      #else
      #define LED_ON HIGH
      #define LED_OFF LOW
      #endif
      
      #define redLed 4    // Set Led Pins
      #define greenLed 5
      #define blueLed 6
      
      #define relay 2       // Set Relay Pin
      #define wipeB 3     // Button pin for WipeMode
      
      bool programMode = false;  // initialize programming mode to false
      
      uint8_t 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 dumpedCard[4];
      
      static const uint8_t MAGIC = 168;
      
      // Create MFRC522 instance.
      #define SS_PIN 8
      #define RST_PIN 7
      MFRC522 mfrc522(SS_PIN, RST_PIN);
      
      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);
      }
      
      ///////////////////////////////////////// Setup ///////////////////////////////////
      void setup() {
         //Arduino Pin Configuration
        pinMode(redLed, OUTPUT);
        pinMode(greenLed, OUTPUT);
        pinMode(blueLed, OUTPUT);
        pinMode(wipeB, INPUT_PULLUP);   // Enable pin's pull up resistor
        pinMode(relay, OUTPUT);
        //Be careful how relay circuit behave on while resetting or power-cycling your Arduino
        digitalWrite(relay, HIGH);    // Make sure door is locked
        digitalWrite(redLed, LED_OFF);  // Make sure led is off
        digitalWrite(greenLed, LED_OFF);  // Make sure led is off
        digitalWrite(blueLed, LED_OFF); // Make sure led is off
      
        //Protocol Configuration
        Serial.begin(115200);  // Initialize serial communications with PC
        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 v2.0"));   // For debugging purposes
        ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details
        checkWipe();
      
        // Check if master card defined, if not let user choose a master card
        // This also useful to just redefine the Master Card
        // You can keep other EEPROM records just write other than MAGIC to EEPROM address 1
        // EEPROM address 1 should hold magical number which is 'MAGIC'
        if (loadState(1) != MAGIC) {
          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
            digitalWrite(blueLed, LED_ON);    // Visualize Master Card need to be defined
            delay(200);
            digitalWrite(blueLed, LED_OFF);
            delay(200);
          }
          while (!successRead);                  // Program will not go further while you not get a successful read
          for ( uint8_t j = 0; j < 4; j++ ) {        // Loop 4 times
            saveState( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
          }
          saveState(1, MAGIC);                  // Write to EEPROM we defined Master Card.
          Serial.println(F("Master Card Defined"));
        }
         Serial.println(F("-------------------"));
        Serial.println(F("Master Card's UID"));
        for ( uint8_t i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
          masterCard[i] = loadState(2 + i);    // Write it to masterCard
          Serial.print(masterCard[i], HEX);
        }
        Serial.println("");
        Serial.println(F("-------------------"));
        Serial.println(F("Everything is ready"));
        Serial.println(F("Waiting PICCs to be scanned"));
        cycleLeds();    // Everything ready lets give user some feedback by cycling leds
      } 
      
      //////////////////////////////////////// MySensors Presentation ///////////////////////////////
      
      MyMessage lockMsg(RFID, V_LOCK_STATUS);
      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 PintuBesi", "1.0");
        present(RFID, S_LOCK);
      }
      
      ///////////////////////////////////////// Main Loop ///////////////////////////////////
      void loop () {
        do {
          successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
          checkWipe();
          if (programMode) {
            cycleLeds();              // Program Mode cycles through Red Green Blue waiting to read a new card
          }
          else {
            normalModeOn();     // Normal mode, blue Power LED is on, all others are off
          }
        }
        while (!successRead);   //the program will not go further while you are not getting a successful read
        if (programMode) {
          if ( isMaster(readCard) ) { //When in program mode check First If master card scanned again to 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"));
            uint8_t count = loadState(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 ( uint16_t setDelay) {
        digitalWrite(blueLed, LED_OFF);   // Turn off blue LED
        digitalWrite(redLed, LED_OFF);  // Turn off red LED
        digitalWrite(greenLed, LED_ON);   // Turn on green LED
        digitalWrite(relay, LOW);     // Unlock door!
        send(lockMsg.set(false));
        delay(setDelay);          // Hold door lock open for given seconds
        digitalWrite(relay, HIGH);    // Relock door
        send(lockMsg.set(true));
        delay(1000);            // Hold green LED on for a second
      }
      
      ///////////////////////////////////////// Access Denied  ///////////////////////////////////
      void denied() {
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        digitalWrite(redLed, LED_ON);   // Turn on red LED
        delay(1000);
      }
      
      
      ///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
      uint8_t getID() {
        // Getting ready for Reading PICCs
        if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
          return 0;
        }
        if ( ! mfrc522.PICC_ReadCardSerial()) {   //Since a PICC placed get Serial and continue
          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 ( uint8_t 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."));
          // Visualize system is halted
          digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
          digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
          digitalWrite(redLed, LED_ON);   // Turn on red LED
          while (true); // do not go further
        }
      }
      
      ///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
      void cycleLeds() {
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        delay(200);
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
        delay(200);
        digitalWrite(redLed, LED_ON);   // Make sure red LED is on
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        delay(200);
      }
      
      //////////////////////////////////////// Normal Mode Led  ///////////////////////////////////
      void normalModeOn () {
        digitalWrite(blueLed, LED_ON);  // Blue LED ON and ready to read card
        digitalWrite(redLed, LED_OFF);  // Make sure Red LED is off
        digitalWrite(greenLed, LED_OFF);  // Make sure Green LED is off
        digitalWrite(relay, HIGH);    // Make sure Door is Locked
      }
      
      //////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
      void readID( uint8_t number ) {
        uint8_t start = (number * 4 ) + 2;    // Figure out starting position
        loadCard(start, storedCard);
      }
      
      ///////////////////////////////////////// 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!
          uint8_t num = loadState(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
          uint8_t start = ( num * 4 ) + 6;  // Figure out where the next slot starts
          num++;                // Increment the counter by one
          saveState( 0, num );     // Write the new count to the counter
          //for ( uint8_t j = 0; j < 4; j++ ) {   // Loop 4 times
          //  saveState( start + j, a[j] );  // Write the array values to EEPROM in the right position
          //}
          saveCard(start, a);
          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 {
          uint8_t num = loadState(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
          uint8_t slot;       // Figure out the slot number of the card
          uint8_t start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
          uint8_t looping;    // The number of times the loop repeats
          uint8_t j;
          uint8_t count = loadState(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
          saveState( 0, num );   // Write the new count to the counter
          for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
            saveState( start + j, loadState(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
          }
          for ( uint8_t k = 0; k < 4; k++ ) {         // Shifting loop
            saveState( start + j + k, 0);
          }
          successDelete();
          Serial.println(F("Succesfully removed ID record from EEPROM"));
        }
      }
      
      ///////////////////////////////////////// Check Bytes   ///////////////////////////////////
      bool checkTwo ( byte a[], byte b[] ) {   
        for ( uint8_t k = 0; k < 4; k++ ) {   // Loop 4 times
          if ( a[k] != b[k] ) {     // IF a != b then false, because: one fails, all fail
             return false;
          }
        }
        return true;  
      }
      
      ///////////////////////////////////////// Find Slot   ///////////////////////////////////
      uint8_t findIDSLOT( byte find[] ) {
        uint8_t count = loadState(0);       // Read the first Byte of EEPROM that
        for ( uint8_t 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
          }
        }
      }
      
      ///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
      bool findID( byte find[] ) {
        uint8_t count = loadState(0);     // Read the first Byte of EEPROM that
        for ( uint8_t 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;
            }
        return false;
      }
      
      ///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
      // Flashes the green LED 3 times to indicate a successful write to EEPROM
      void successWrite() {
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is on
        delay(200);
        digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
        delay(200);
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        delay(200);
        digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
        delay(200);
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        delay(200);
        digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
        delay(200);
      }
      
      ///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
      // Flashes the red LED 3 times to indicate a failed write to EEPROM
      void failedWrite() {
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        delay(200);
        digitalWrite(redLed, LED_ON);   // Make sure red LED is on
        delay(200);
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        delay(200);
        digitalWrite(redLed, LED_ON);   // Make sure red LED is on
        delay(200);
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        delay(200);
        digitalWrite(redLed, LED_ON);   // Make sure red LED is on
        delay(200);
      }
      
      ///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
      // Flashes the blue LED 3 times to indicate a success delete to EEPROM
      void successDelete() {
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
        digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
        delay(200);
        digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
        delay(200);
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        delay(200);
        digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
        delay(200);
        digitalWrite(blueLed, LED_OFF);   // Make sure blue LED is off
        delay(200);
        digitalWrite(blueLed, LED_ON);  // Make sure blue LED is on
        delay(200);
      }
      
      ////////////////////// Check readCard IF is masterCard   ///////////////////////////////////
      // Check to see if the ID passed is the master programing card
      bool isMaster( byte test[] ) {
        return checkTwo(test, masterCard);
      }
      
      bool monitorWipeButton(uint32_t interval) {
        uint32_t now = (uint32_t)millis();
        while ((uint32_t)millis() - now < interval)  {
          // check on every half a second
          if (((uint32_t)millis() % 500) == 0) {
            if (digitalRead(wipeB) != LOW)
              return false;
          }
        }
        return true;
      }
      
      void saveCard(uint8_t startPos, byte *card) {
        for ( uint8_t j = 0; j < 4; j++ ) {        // Loop 4 times
          saveState( startPos + j, card[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
        }
      }
      
      void loadCard(uint8_t startPos, byte *card) {
        for ( uint8_t i = 0; i < 4; i++ )    // Read Card's UID from EEPROM
          card[i] = loadState(startPos + i);    // Write it to the card
      }
      
      void checkWipe() {
        //Wipe Code - If the Button (wipeB) Pressed while setup run (powered on) it wipes EEPROM
        if (digitalRead(wipeB) == LOW) {  // when button pressed pin should get low, button connected to ground
          digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
          Serial.println(F("Wipe Button Pressed"));
          Serial.println(F("You have 10 seconds to Cancel"));
          Serial.println(F("This will be remove all records and cannot be undone"));
          bool buttonState = monitorWipeButton(10000); // Give user enough time to cancel operation
          if (buttonState == true && digitalRead(wipeB) == LOW) {    // If button still be pressed, wipe EEPROM
            Serial.println(F("Starting Wiping EEPROM"));
             Serial.println(F("Starting Wiping"));
            saveState(0, 0 );     // light wipe. only erase number
            saveState(1, 0);      // light wipe. only erase magic number
            Serial.println(F("EEPROM Successfully Wiped"));
            digitalWrite(redLed, LED_OFF);  // visualize a successful wipe
            delay(200);
            digitalWrite(redLed, LED_ON);
            delay(200);
            digitalWrite(redLed, LED_OFF);
            delay(200);
            digitalWrite(redLed, LED_ON);
            delay(200);
            digitalWrite(redLed, LED_OFF);
          }
          else {
            Serial.println(F("Wiping Cancelled")); // Show some feedback that the wipe button did not pressed for 15 seconds
            digitalWrite(redLed, LED_OFF);
          }
        }
      }
      
      
      void receive(const MyMessage &message)
      {
        if (message.type == V_LOCK_STATUS) {
          // Change relay state
            if (!message.getBool()) {
            granted(300);
          }
          }
      }
      

      need advise, thanks
      regards

      posted in Troubleshooting
      Ispandy
      Ispandy
    • RE: Example RFID MFRC522 + mysensors with "some" security

      Hello Oniric,
      I want use this sketch but with relay controlled, what do I have to do?.
      I'm not good at programming.😬
      regards

      posted in My Project
      Ispandy
      Ispandy
    • RE: Heatpump controller

      I want to make heatpumpIR, but after trying to send the signal using simple.ino sketch to my Sharp A/C nothing happened. Confused where to start ....

      posted in Development
      Ispandy
      Ispandy