Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte aligning in serial communication

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.

For instance if I want to send

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?

like image 640
vanjoe Avatar asked Feb 27 '12 16:02

vanjoe


1 Answers

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?

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.

Edit: 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.

like image 118
Dervall Avatar answered Oct 20 '22 00:10

Dervall