Serial.Read() problem

So I got this weird error when reading from the serial port since a while.
IPlatform: Arduino Mega 2560
I am using a XBEE and when I read from the serial port I should receive the following bytes:
7E-0-A-81-0-1-24-0-55-22-20-22-55-4B.
I get this about 50% of the time. The other half I receive this:
0-55-22-20-22-55-4B-7E-0-A-81-0-1-24.
As you can see its look like 7 bytes are in the place of the other 7 bytes.
Rarelly I got this: 81-0-1-24-0-55-22-20-22-55-4B-7E-0-A

It look to me that the function Serial.Read start to read at a random time and I don't always have my start delimiter (7E) at the beginning.

This is my code, for debugging I add some serial.println so I could get what is in RxBuffer().

Is there something I should do before calling Serial1.Read or do you know why I got such a thing??

Thanks

robot_1_1_2.ino (4.8 KB)

It look to me that the function Serial.Read start to read at a random time and I don't always have my start delimiter (7E) at the beginning.

No. It always returns the next byte in the buffer. If you don't read often enough, then the buffer can overflow, resulting in lost data.

This is my code, for debugging I add some serial.println so I could get what is in RxBuffer().

I don't do rubbish bin. Use the Additional Options link and post you code as an attachment here.

Thanks for the input.

Is just saw that for the first 4 or 5 transmisson, everything works fine..

Here is what happen.

The Serial buffer is 64 bytes long. If I only read 14 of them (number of bytes in my transmisson) the function Serial1.available return me those number after each time I send a packet:
63-49-35-21. The difference between those numbers are 14. I think the buffer is then overflowing.
**If I read the whole thing (64 bytes) everything it works fine, except in got my last 4.5 transmisson.
If I only wants to read 14 bytes each time, what should I do?
I tried Serial1.Flush();....nothing changed.

Where's the code?

Please use code tags.

Read this before posting a programming question

It's attached with my post (.ino) and there is also the pastebin link.

void serialEvent1() {

  if(Serial1.available()>=rx_lenght) {
    for(int n=0; n <= (rx_lenght-1); n++){
      RxBuffer[n] = Serial1.read();
    }
    mess_received = 1;
  } 
}

You are much better off reading each byte into your buffer as it arrives, and then when you get an "end of packet" indicator (whatever that is) process the entire lot.

Read and digest: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

johnyboy:
It's attached with my post (.ino) and there is also the pastebin link.

If the code is of reasonable size, use the # to put it in a code box for easy viewing so downloading is not required.