串行通讯的字节顺序Arduino的 [英] Byte Order of Serial communication to Arduino

查看:588
本文介绍了串行通讯的字节顺序Arduino的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个C ++应用程序以64位字发送到一个Arduino。

I am trying to write a C++ application to send a 64bit word to an Arduino.

我使用所描述的方法<用过的termios href=\"http://stackoverflow.com/questions/6947413/how-to-open-read-and-write-from-serial-port-in-c\">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.

这是不是我被通缉的行为,有没有办法得到最显著轮空第一个到达终点?或者是最好的制动serialword成字节,按字节发送字节?

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 ::逆转 如下面的例子

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆