#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
#define PROG_UID 2
#define VALID_UID 8
#define INVALID_UID 4
byte valid_uids[5][10] = {};
int count_saved_uid=0;
MFRC522 mfrc522(SS_PIN, RST_PIN);
void setup() {
Serial.begin(9600);
SPI.begin();
mfrc522.PCD_Init();
mfrc522.PCD_DumpVersionToSerial();
}
void loop() {
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
if ( !mfrc522.PICC_ReadCardSerial())
return;
if(digitalRead(PROG_UID)){
save_uid(mfrc522.uid.uidByte, mfrc522.uid.size);
}
if(check_uid(mfrc522.uid.uidByte, mfrc522.uid.size)){
Serial.print("UID: ");
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println(" is valid!");
digitalWrite(VALID_UID,HIGH);
digitalWrite(INVALID_UID,LOW);
}
else{
Serial.print("UID: ");
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println(" is invalid!");
digitalWrite(VALID_UID,LOW);
digitalWrite(INVALID_UID,HIGH);
}
delay(1000);
}
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
void save_uid(byte *buffer, byte bufferSize){
Serial.print("saving UID: ");
dump_byte_array(buffer, bufferSize);
Serial.print("\n");
for (byte i = 0; i < bufferSize; i++) {
valid_uids[count_saved_uid][i] = buffer[i];
}
count_saved_uid++;
Serial.print("saved ");
Serial.print(count_saved_uid);
Serial.println(" UIDs");
}
bool check_uid(byte *buffer, byte bufferSize){
byte c_err=0;
for(byte k = 0; k<count_saved_uid;k++){
for (byte i = 0; i < bufferSize; i++) {
if(valid_uids[k][i] != buffer[i]) c_err++;
}
if (c_err==0)
return true;
else
c_err=0;
}
return false;
}