Search code examples
arduinoserial-portnumber-formattingrfid

How can I get the serial number printed on RFID tag with RFID reader?


How can I get the serial number printed on an RFID tag through an RFID reader?

I have:

  • Arduino uno,
  • RMD 6300 reader, and
  • RFID tag (125Khz).

I use the following code:

#include <SoftwareSerial.h>
SoftwareSerial RFID(2, 3); // RX and TX

int i;

void setup()
{
  RFID.begin(9600);    // start serial to RFID reader
  Serial.begin(9600);  // start serial to PC 
}

void loop()
{
  if (RFID.available() > 0) 
  {
     i = RFID.read();
     Serial.print(i, DEC);
     Serial.print(" ");
  }
}

I get this value:

2 48 57 48 48 50 69 52 69 65 50 67 66 3 

But the following value is printed on the RFID tag:

0003034786

I would want to have this number, but I don't know how to convert it.


Solution

  • The value that you currently get is the serial number encoded as US-ASCII string. The value in decimal (as you currently print it) is

    2 48 57 48 48 50 69 52 69 65 50 67 66 3
    

    Converting these bytes into hexadecimal form (for better readability) leads to:

    02 30 39 30 30 32 45 34 45 41 32 43 42 03
    

    Encoding these bytes in US-ASCII leads to this string:

    <STX>09002E4EA2CB<ETX>
    

    Note that you could also receive this form directly on your console by using

    Serial.write(i);
    

    instead of Serial.print(i, DEC);

    Thus, your reader starts outputting the serial number by sending a start-of-transmission (STX) character (0x02) and ends sending the serial number with an end-of-transmission (ETX) character. Everything in between is the serial number (represented as hexadecimal characters):

    09002E4EA2CB
    

    The serial number printed on your key (0003034786) is only a fraction of the complete serial number. This value is the decimal representation. If you convert

    0003034786
    

    to its hexadecimal representation, you get

    002E4EA2
    

    This value is contained in the serial number that you received from the reader:

    09002E4EA2CB
    

    Therefore, you could do something like this to print the value (use sprintf(), if you need the leading zeros):

    void loop() {
        int serialNumber = 0;
        int charIndex = 0;
        int currentChar;
    
        if (RFID.available() > 0) {
            currentChar = RFID.read();
            ++charIndex;
            if (currentChar == 0x002) {
                charIndex = 0;
                serialNumber = 0;
            } else if (currentChar == 0x003) {
                Serial.print(serialNumber, DEC);
                Serial.print(" ");
            } else {
                if ((charIndex >= 1) && (charIndex < 5)) {
                    serialNumber <<= 8;
                    serialNumber += currentChar;
                }
            }
        }
    }