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

MFRC522 mfrc522(10, 9);

Servo servo;

String last_uid = "";
const int SIZE = 3;

const int TIME = 3;
int tick = 0;
bool start_timer = false;

String user[SIZE][2] =
{
  {"Oleg", "FA C4 B4 1A"},
  {"Petro", "1A 0D 6C 19"}
};


void setup()
{
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();

  Serial.println("\nREADY!");
  servo.attach(3);
}

void loop()
{
  delay(100);
  if (start_timer)
  {
    tick++;
  }

  if (tick >= 10 * TIME)
  {
    tick = 0;

    start_timer = false;
    servo.write(0);
  }

  if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial())
    return;

  String curr_uid = get_uid();

  bool work = false;

  if (last_uid == curr_uid)
  {
    return;
  }

  tick = 0;
  for (int i = 0; i < SIZE; i++)
  {
    if (user[i][1] == curr_uid)
    {
      servo.write(90);
      work = true;
      start_timer = true;
      break;
    }
  }
  if (!work)
  {
    start_timer = false;
    servo.write(0);
    Serial.print("\nAccess denied");
  }
  last_uid = curr_uid;
}


String get_uid()
{
  String content = "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  content.toUpperCase();
  return content.substring(1);
}