与 Arduino 串行通信的字节顺序 [英] Byte Order of Serial communication to Arduino
问题描述
我正在尝试编写一个 C++ 应用程序来向 Arduino 发送 64 位字.
I am trying to write a C++ application to send a 64bit word to an Arduino.
我使用 termios 使用描述的方法 这里
I used termios using the method described here
我遇到的问题是轮空首先以最低有效字节到达 arduino.
The problem i am having is the byes are arriving at the arduino in least significant byte first.
即
如果使用(其中 serialword 是 uint64_t)
if a use (where serialword is a uint64_t)
write(fp,(const void*)&serialWord, 8);
最低有效字节首先到达 arduino.
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?
谢谢
推荐答案
由于所涉及的 CPU 的字节序不同,您需要在发送之前或接收之后颠倒字节顺序.在这种情况下,我建议您在发送它们之前反转它们,以节省 Arduino 上的 CPU 周期.使用 C++ 标准库的最简单方法是使用 std::reverse
如下例所示
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;
}
输出如下:
之前:1122334455667788
后:8877665544332211
Before: 1122334455667788
After: 8877665544332211
这篇关于与 Arduino 串行通信的字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!