Byte Order of Serial communication to Arduino

2019-08-17 06:28发布

问题:

I am trying to write a C++ application to send a 64bit word to an Arduino.

I used termios using the method described here

The problem i am having is the byes are arriving at the arduino in least significant byte first.

ie

if a use (where serialword is a uint64_t)

write(fp,(const void*)&serialWord, 8); 

the least significant bytes arrive at the arduino first.

this is not the behavior i was wanted, is there a way to get the most significant byes to arrive first? Or is it best to brake the serialword into bytes and send byte by byte?

Thanks

回答1:

Since the endianess of the CPU's involved are different you will need to reverse the order of bytes before you send them or after your receive them. In this case I would recommend reversing them before you send them just to save CPU cycles on the Arduino. The simplest way using the C++ Standard Library is with std::reverse as shown in the following example

#include <cstdint>  // uint64_t (example only)
#include <iostream> // cout (example only)
#include <algorithm>  // std::reverse

int main()
{
    uint64_t value = 0x1122334455667788;

    std::cout << "Before: " << std::hex << value << std::endl;

    // swap the bytes
    std::reverse(
        reinterpret_cast<char*>(&value),
        reinterpret_cast<char*>(&value) + sizeof(value));

    std::cout << "After: " << std::hex << value << std::endl;
}

This outputs the following:

Before: 1122334455667788
After: 8877665544332211