[英]Byte Order of Serial communication to Arduino
我正在嘗試編寫一個C ++應用程序以將64位字發送到Arduino。
我使用此處描述的方法使用termios
我遇到的問題是,再見首先到達最低有效字節的arduino。
即
如果使用(其中serialword是uint64_t)
write(fp,(const void*)&serialWord, 8);
最低有效字節首先到達arduino。
這不是我想要的行為,有沒有辦法讓最重要的人先到達? 還是最好將串行字分解為字節並逐字節發送?
謝謝
由於所涉及的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.