Search code examples
c++serial-portarduinouart

Saving a rs232 message to a variable


If I receive a message via RS232 consisting of 2 Byte length, e.g. 0000 0001 0001 1100 (that is 100011100, lsb on the right), I wanna save it to a variable called value.

I am "decoding" the byte stream with this step:

rxByte = Serial1.read()

messageContent[0] = rxByte

messageContent[1] = rxByte

with the first rxByte having the value 0000 0001 and the second 0001 1100. Or are those values already converted internally to HEX or DEC?

Now I have seen code that saves it this way to value:

uint32_t value = messageContent[0] *256 + messageContent[0]

How does this work?


Solution

  • messageContent[0] *256 is essentially a bitshift: the code is equivelent to (and more readable as)

    uint32_t value = (messageContext[0]) << 8 + messageContent[1];
    

    So if `messageContent[0] = 0x01' and messageContext[2] = 0x1C

    value = (0x01 << 8)+0x1C
    value = (0x0100)+0x1C
    value = 0x011C
    

    Works find, but depending on the endianess of your machine, it is equivalent to:

     uint32_t value = *((uint16_t*)(messageContext));