Search code examples
c++cavrarduino-uno

10 char string to int on Arduino


On my current project, I have RFID badges which sends a 10 chars ID to my Arduino UNO (ex: 2700BBA0E8). The doc says "Printable ASCII", but I don't know if it's always [0-9A-F].

On Arduino, the memory is limited:

  • char is 1 byte
  • int is 2 bytes
  • long is 4 bytes

an int or a long would be shorter than a char[10] and simpler to compare (strcmp() vs ==), so I wonder how I can transform the 10 chars received one by one (on serial) to an int or a long?

Thanks for your help


Solution

  • As already mention, you want put 5 bytes inside a long which can store only 4 bytes. Also, you have to use structure:

    struct RFIDTagId
    {
        unsigned long low;
        unsigned long high; // can also be unsigned char
    };
    

    And use something like that:

    unsigned int hex2int(char c)
    {
        if (c >= 'A' && c <= 'F')
            return (c - 'A' + 0x0A);
        if (c >= '0' && c <= '9')
            return c - '0';
        return 0;
    }
    
    void char2Id(char *src, RFIDTagId *dest)
    {
        int i = 0;
    
        dest->low = 0;
        for(i = 0; i < 8; ++i)
        {
            dest->low |= hex2int(src[i]) << (i*4);
        }
    
        dest->high = 0;
        for(i = 8; i < 10; ++i)
        {
            dest->high |= hex2int(src[i]) << ((i-8)*4);
        }
    }
    

    And to compare 2 ids:

    int isRFIDTagIdIsEqual(RFIDTagId * lhs, RFIDTagId * rhs)
    {
        return lhs->low == rhs->low && lhs->high == lhs->high;
    }
    

    or if you really have c++:

    bool operator==(RFIDTagId const & lhs, RFIDTagId const & rhs)
    {
        return lhs.low == rhs.low && lhs.high == lhs.high;
    }