串行通讯中的字节对齐 [英] byte aligning in serial communication

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

问题描述

因此,我正在尝试为串行通信定义通信协议,我希望能够向设备发送4个字节的数字,但是我不确定如何确保设备在右侧开始拾取字节.

So I am trying to define a communication protocol for serial communication, I want to be able to send 4 byte numbers to the device, but I'm unsure how to make sure that the device starts to pick it up on the right byte.

例如,如果我想发送

0x1234abcd 0xabcd3f56 ...

我如何确保设备不会在错误的位置开始阅读并获得第一个单词:

how do I makes sure that the device doesn't start reading at the wrong spot and get the first word as:

0xabcdabcd

有一个聪明的方法吗?我曾想过要在邮件的开头使用一个标记,但是如果我要发送选择的数字作为数据怎么办?

Is there a clever way of doing this? I thought of using a marker for the start of a message, but what if I want to send the number I choose as data?

推荐答案

如果您知道数据的大小,为什么不发送start-of-message字节后跟length-of-data字节?

Why not send a start-of-message byte followed by a length-of-data byte if you know how big the data is going to be?

或者,与其他二进制协议一样,仅发送具有固定标头的固定大小的软件包.假设您只发送4个字节,那么您知道在实际数据内容之前将有一个或多个字节的标头.

Alternatively, do as other binary protocols and only send fixed sizes of packages with a fixed header. Say that you will only send 4 bytes, then you know that you'll have one or more bytes of header before the actual data content.

编辑:我认为您误会了我.我的意思是,客户端应该始终将字节视为报头或数据,而不是基于值,而是基于流中的位置.假设您要发送四个字节的数据,那么一个字节就是标头字节.

I think you're misunderstanding me. What I mean is that the client is supposed to always regard bytes as either header or data, not based on value but rather based on the position in the stream. Say you're sending four bytes of data, then one byte would be the header byte.

+-+-+-+-+-+
|H|D|D|D|D|
+-+-+-+-+-+

然后,客户端将是一个非常基本的状态机,大致如下:

The client would then be a pretty basic state machine, along the lines of:

int state = READ_HEADER;
int nDataBytesRead = 0;
while (true) {
  byte read = readInput();
  if (state == READ_HEADER) {
    // process the byte as a header byte
    state = READ_DATA;
    nDataBytesRead = 0;
  } else {
    // Process the byte as incoming data
    ++nDataBytesRead;
    if (nDataBytesRead == 4) 
    {
      state = READ_HEADER;
    }
  }
} 

关于此设置的事情是,确定字节是否为标头字节的不是字节的实际内容,而是流中的位置.如果要具有可变数量的数据字节,请在标头中添加另一个字节以指示紧随其后的数据字节数.这样,您是否发送与数据流中的标头相同的值就没有关系,因为您的客户端永远不会将其解释为数据.

The thing about this setup is that what determines if the byte is a header byte is not the actual content of a byte, but rather the position in the stream. If you want to have a variable number of data bytes, add another byte to the header to indicate the number of data bytes following it. This way, it will not matter if you are sending the same value as the header in the data stream since your client will never interpret it as anything but data.

这篇关于串行通讯中的字节对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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