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

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

问题描述

所以我正在尝试为串行通信定义一个通信协议,我希望能够向设备发送 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 个字节,那么你知道在实际数据内容之前会有一个或多个字节的 header.

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天全站免登陆