Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

c++ - Byte Order of Serial communication to Arduino

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...