pedrokv
December 25, 2017, 11:13pm
1
Hello,
I cannot google out, if there is any easy method, how to compare two byte arrays. I program door opening on NFC tags, thus I need to compare scanned NFC id:
uint8_t uid[] = { 255, 255, 255, 255, 255, 255, 255 };
with code read from eeprom:
typedef struct {
char nick[9];
byte tokenL1; //eeprom token/uid length
byte token1[7];
byte tokenL2;
byte token2[7];
byte tokenL3;
byte token3[7];
} user;
user database[10];
I tried the simple (for first user and his first NFC token):
if (uid==database[0].token1){
but it doesn't work.
So I have to compare each position of each array, which is not user friendly..
if (
(uid[0]==database[0].token1[0] & uid[1]==database[0].token1[1] & uid[2]==database[0].token1[2] & uid[3]==database[0].token1[3] & uid[4]==database[0].token1[4] & uid[5]==database[0].token1[5] & uid[6]==database[0].token1[6])
or
(uid[0]==database[0].token2[0] & uid[1]==database[0].token2[1] & uid[2]==database[0].token2[2] & uid[3]==database[0].token2[3] & uid[4]==database[0].token2[4] & uid[5]==database[0].token2[5] & uid[6]==database[0].token2[6])
)
etc....
{
So-is there any shortcut?
Thank you.
PieterP
December 25, 2017, 11:48pm
2
memcmp or, if it's a null terminated char array, strcmp .
Pieter
pedrokv
December 26, 2017, 1:41am
3
Thanks a lot, now it works! I made a function:
boolean CheckToken (uint8_t CTuid[7]){
boolean result;
result=false;
i=0;
do{
if (
(memcmp (CTuid, database[i].token1, 7)==0)
or
(memcmp (CTuid, database[i].token2, 7)==0)
or
(memcmp (CTuid, database[i].token3, 7)==0)
){
result=true;
}
i++;
}while ((result==false) and (i<=9)); //ten users in database
if (result==true){
Serial.println(F("Token found in EEPROM"));
}
else {
Serial.println(F("Token not found in EEPROM"));
}
return result;
}
then checking it's state with:
if (CheckToken(uid)==true) {
....
A variation of your function, it returns the index found or -1 when not found.
useful to track which user/tag opened the door.
int CheckToken (uint8_t CTuid[7])
{
int index = 0;
const int tokens = 10;
while (index < tokens)
{
if (
(memcmp (CTuid, database[index].token1, 7) == 0)
or
(memcmp (CTuid, database[index].token2, 7) == 0)
or
(memcmp (CTuid, database[index].token3, 7) == 0)
)
break;
index++;
}
Serial.print(F("Token "));
if (index < tokens)
{
Serial.print(index);
}
else
{
Serial.print(F("not"));
index = -1;
}
Serial.println(F(" found in EEPROM"));
return index;
}