I think there's an obvious bug in the code. After you read 16 bytes, you completely clear your serial_buffer by zeroing si_processed, and you then think "success!" after each next 10 bytes you read.
Instead you should:
- If you read too much data, don't discard the extra bytes: instead use
memmove to move them to the beginning of the buffer (assuming they're the start of the next packet), and then read the subsequent bytes into the vacant space after them.
Something like:
// after reading and processing a 10-byte packet
if (si_processed > 10) // already have the start of the next packet
{
// move start of next packet to start of buffer
memmove(serial_buffer, serial_buffer+10, si_processed - 10);
// not 0: remember how many start bytes we already have
si_processed -= 10;
}
- After you read any bytes, verify whether the start byte is your
0xA5 value, and discard the bytes if not.
Something like:
if (si_processed > 0) // have some bytes
{
int i;
for (i = 0; i < si_processed; ++i)
if (serial_buffer[i] == 0xA5) // found start of packet
break;
if (i > 0)
{
// start of packet is not start of buffer
// so discard bad bytes at the start of the buffer
memmove(serial_buffer, serial_buffer+i, si_processed - i);
si_processed -= i;
}
}