0

I'm currently doing a project using RFID. I'm wondering how this lines of the code work. I know that this has something to do with getting the UID of a scanned/tapped card, but can someone please explain or elaborate to me each line, how it executes? Thank you very much.

  String ID = "";
  for (byte i = 0; i < 4; i ++) {
    ID += (rfid.uid.uidByte[i] < 0x10 ? "0" : "")
          + String(rfid.uid.uidByte[i], HEX)
          + (i != 3 ? ":" : "" );
  }
  • 1
    which part of the code do you understand? .... which part of the code do you not understand? – jsotola Aug 21 '18 at 3:27
  • I'm finding a hard time to understand the 4th and 6th lines of this specific part, so those are operators. Thank you so much for elaborating. – A. Raymundo Aug 21 '18 at 4:51
  • those are ternary operators .... the print() function would receive one of the two strings depending on a logic test result print( 1<2 ? "this is true" : "this is not true") .... print( 1>2 ? "this is true" : "this is not true") ..... first one would print "this is true" .... the second one would print "this is not true" – jsotola Aug 21 '18 at 5:13
3

The code formats UUID as a string of 4 hex bytes (each bytes a pair of hex digits) separated by colons.

String ID = ""

Blank the string

for (byte i = 0; i < 4; i ++){

Iterate over the four bytes of the UUID

  ID +=

Add the following to the string "ID"

(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +

If the hex number to be displayed is less than 0x10, add a leading '0' to the string 'ID'. This ensures the UUIDs are all aligned and all bytes within the UUID are displayed as two hex digits (even if only one is needed). It uses the ternary condition operator, which is a compact if/then/else that can only return one of two values (rather than executing chunks of code). See https://en.wikipedia.org/wiki/%3F: for more on the ternary condition operator.

 String(rfid.uid.uidByte[i], HEX) +

Add the UUID to the string 'ID' as HEX.

   (i != 3 ? ":" : "" );

Another instance of the ternary condition operator. This one adds a colon to the string 'ID' after the hex byte unless the index is 3 (ie the last one).

 }

End of for loop. This means that the result is nn:nn:nn:nn instead of nn:nn:n:nn: (leave off trailing colon and differing numbers of hex digits).

  • Thank you guys for elaborating it for me. I super highly appreciate it. :) – A. Raymundo Aug 21 '18 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.