Strings look alike but comparison fails

Hello everyone \o/,

I'm trying to compare the UID of a RFID device and run some action if the UID match the registered UID.
Even if my two strings look alike, the comparison return nothing.

  • I have tried the trim() function => Does nothing to my string (visually, at least)
  • I have tried the remove to remove what looks like a "\n" at the beginning and/or tried to add it in the string to compare.
  • I have tried the strncmp() function, but I cannot make it work as it's expecting a const char*.

Is there a simple way to compare string without caring all the strange possible space character or \n ?
Or may be my issue is somewhere else....

This is the last state of the code :

  //Show UID on serial monitor
  Serial.print("UID tag :");
    String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++) 
  {
     //Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     //Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  content.toUpperCase();
  content.remove(0,1);
  Serial.println(content);
  Serial.print("supposed to compare :");
  Serial.print("\n04 36 70 D2 13 12 90");

  if (content=="\n04 36 70 D2 13 12 90" && content=="\n04 6B 1F 02 CD 12 90"){
    Serial.print("Hello world");
    delay(3000);
  }

Picture in the serial monitor :

UID of the RFID is an array of bytes. What's the point of converting UIDs to strings to compare, why not compare it as is, byte by byte?

Good question ! The UID tag reading is a copy/paste code.
Ok, I will have a look how to do it, I'm not familiar with byte manipulation.
Thanks !

// Tag to compaqre
 uit8_t tag[] = {0x04, 0x36, 0x70, 0xD2 ,0x13, 0x12, 0x90 };

 bool tag_matched = true;
 
 for (byte i = 0; i < mfrc522.uid.size; i++) 
  {
     if (mfrc522.uid.uidByte[i] != tag[i]) {
        tag_matched = false;
        break;
      }
  }


  if (tag_matched) {
    Serial.print("The tag is match!");
    delay(3000);
  }

the "content" can't be 04 36 ... AND 04 6B ... at the same time.
This if will never get true.

by the way, get rid off the leading \n
even better, just compare the array

mfrc522.uid.uidByte

with a simple memcmp

https://en.cppreference.com/w/cpp/string/byte/memcmp

1 Like

Thanks, it works !
For my curiosity, why use the hexadecimal ? Could we use directly decimal to define this byte array ?

Oh.... I'm ashamed....
It works better with the correct logic operator ^^"
Thanks !

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.