/*
   All the resources for this project: http://randomnerdtutorials.com/
   Modified by Rui Santos

   Created by FILIPEFLOP

   Reconfigured by E.zn
*/


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

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.


const int ledpin = 6; // ledpin and soundpin are not changed throughout the process
const int RFIDSound = 5;


void setup()
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  Serial.println();
  pinMode(ledpin, OUTPUT);
  pinMode(RFIDSound, OUTPUT);


}

void readCard() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content = ""; // for tag + Sound
  String binary = ""; // for binary + LED
  int letter;
  for (int i = 0; i < mfrc522.uid.size; i++)
  {
    Serial.print(mfrc522.uid.uidByte[i], DEC);
    content.concat(String(mfrc522.uid.uidByte[i], DEC)); // Spits out decimal value of UID tag

    // Assigns tones to each digit of a tag
    
    if (content.charAt(i) == '0') {
      tone(RFIDSound, 40, 2250);
      delay(500);
    }
    else if (content.charAt(i) == '1') {
      tone(RFIDSound, 255, 150);
      delay(500);
    }
    else if (content.charAt(i) == '2') {
      tone(RFIDSound, 260, 1500);
      delay(500);
    }
    else if (content.charAt(i) == '3') {
      tone(RFIDSound, 265, 150);
      delay(500);
    }
    else if (content.charAt(i) == '4') {
      tone(RFIDSound, 270, 1000);
      delay(500);
    }
    else if (content.charAt(i) == '5') {
      tone(RFIDSound, 275, 1590);
      delay(500);
    }
    else if (content.charAt(i) == '6') {
      tone(RFIDSound, 280, 1500);
      delay(500);
    }
    else if (content.charAt(i) == '7') {
      tone(RFIDSound, 285, 1500);
      delay(500);
    }
    else if (content.charAt(i) == '8') {
      tone(RFIDSound, 290, 1050);
      delay(500);
    }
    else if (content.charAt(i) == '9') {
      tone(RFIDSound, 100, 1000);
      delay(500);
    }
  }

  // Getting binary version of the same tag and blinking LED accordingly

  for (int b = 0; b < mfrc522.uid.size; b++)
  {
    Serial.println(mfrc522.uid.uidByte[b], BIN);
    binary.concat(String(mfrc522.uid.uidByte[b], BIN));

    if (binary.charAt(b) == '1') {
      digitalWrite(ledpin, HIGH);
      delay(500);
    }
    else if (binary.charAt(b) == '0') {
      digitalWrite(ledpin, LOW);
      delay(500);
    }
  }
  Serial.println();
  delay(1000);
}
