//Code based on http://www.naylampmechatronics.com/blog/22_Tutorial-Lector-RFID-RC522.html

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

#define RST_PIN  9    //Pin 9 to do reset on RC522
#define SS_PIN  10   //Pin 10 (SDA) of RC522
MFRC522 mfrc522(SS_PIN, RST_PIN); //Create the object of RC522

void setup() {
  Serial.begin(9600); //Initialize Serial communication
  SPI.begin();        //Initialize SPI bus
  mfrc522.PCD_Init(); // initialize created object MFRC522
  Serial.println("Access control: ");
}

byte CurrentUID[4]; //Store the code of read tag
byte User1[4] = {0xC5, 0xF6, 0x37, 0xD5} ; //code of user 1
byte User2[4] = {0xE6, 0x88, 0x44, 0x49} ; //code of user 2
void loop() {
  //Check if exist new cards. Condition is acomplised if
  // it is true
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    //Select card
    if ( mfrc522.PICC_ReadCardSerial())
    {
      // Send UID via Serial
      Serial.print(F("Card UID:"));
      //This for loop is used to join UID terms and then print them.
      for (byte i = 0; i < mfrc522.uid.size; i++) {
        //(relational expresion) ? (expresion1) : (expresion2)
        //It is the same than a if condition
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        CurrentUID[i] = mfrc522.uid.uidByte[i];
      }
      Serial.print("     ");
      //Compare the UIDs to determine if it is the UID of a user
      if (compareArray(CurrentUID, User1) || compareArray(CurrentUID, User2))
        Serial.println("Access granted...");
      else
        Serial.println("Access denied...");

      // Finish the reading
      mfrc522.PICC_HaltA();

    }

  }

}

//Function to compare two vectors
boolean compareArray(byte array1[], byte array2[])
{
  if (array1[0] != array2[0])return (false);
  if (array1[1] != array2[1])return (false);
  if (array1[2] != array2[2])return (false);
  if (array1[3] != array2[3])return (false);
  return (true);
}