0

我正在尝试编写一个 C++ 应用程序来向 Arduino 发送一个 64 位字。

我使用此处描述的方法使用了 termios

我遇到的问题是再见首先以最低有效字节到达arduino。

IE

如果使用(其中 serialword 是 uint64_t)

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

最低有效字节首先到达arduino。

这不是我想要的行为,有没有办法让最重要的轮空首先到达?还是最好将串行字制动成字节并逐字节发送?

谢谢

4

1 回答 1

3

由于所涉及的 CPU 的字节序不同,您需要在发送它们之前或接收它们之后反转字节顺序。在这种情况下,我建议在发送它们之前将它们反转,以节省 Arduino 上的 CPU 周期。使用 C++ 标准库的最简单方法是std::reverse如下例所示

#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;
}

这将输出以下内容:

之前:
1122334455667788 之后:8877665544332211

于 2013-07-04T04:32:55.170 回答