Byte Order of Serial communication to Arduino

情到浓时终转凉″ 提交于 2019-12-11 16:45:00

问题


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



来源:https://stackoverflow.com/questions/17461623/byte-order-of-serial-communication-to-arduino

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!