Serial.readBytes() out of order

Hello everyone,

I'm currently attempting to read two bytes that are constantly sent from another device. However, when I call readBytes(buffer, 2) and output them, the bytes are often out of order. Is there any way to correct this. Is it necessary to use delays to read?

My code for the writing device MSP430G2553 with energia is simply

Serial.write(output, 2);

and the read device which a Meg2560 I have

if(Serial2.available())
{
   byte buffer[2];
   memset(buffer,0,sizeof(buffer));
   Serial2.read(buffer,2);
   Serial.print(buffer[0]);
   Serial.print(buffer[1]);
}

Perhapsyou'venoticedthatpeopleusedelimiterssoweknowwhereapacketpfdatastartsandends.

You have to use something to keep the data in sync. That is far harder when sending binary data.

Even when I used delimiters when sending packets they come out of order. Like if I pad them with ab[data]cd or send them as string with the \0 ending it. I still get packet errors and out of order data. Is there any way to fix this?

Is there any way to fix this?

Send the data as ASCII data, with start and end markers and delimiters. If you don't get what you expect, send the number of characters that should be in the packet as part of the packet. Discard any packets that are not the right size on receipt.

Is there any chance it lags due to the Serial.print I have to output the data. It reads the correct values for a little bit at the start then it catches something and reads the wrong values.

My send data looks as follows with the padding. I'm trying to grab the middle two bytes.

    writeFormat[0] = (uint8_t)255;
    writeFormat[1] = (uint8_t)255;
    writeFormat[2] = (uint8_t)128;
    writeFormat[3] = (uint8_t)128;
    writeFormat[4] = (uint8_t)255;
    writeFormat[5] = (uint8_t)255;

Serial.write(writeFormat,6);

The input code from the other device is

if(Serial2.available()>6)
{
  Serial2.readBytes(output,6);
  Serial.println(output[2], DEC);
}

The outputs from println is bouncing between the 255 and 128.

There are no delays because I want to transmit as fast as possible.

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R

if(Serial2.available()>6)

Makes it go out of sync. You sent 6 values and you wait until you receive 7 values...

I must say, I'm not a fan of sending ASCII for the values. But you can try to use a start command and maybe CRC. Check out the Pololu motor drivers. You send serial values to it and works great.