There is a lot wrong with your program - some of it might be due to a lack of programming knowledge but a good bit is due to faulty logic.
For example you can't have two start markers - it just makes no sense.
Have a look at this version. I think it might work but I have not tested it. If it does not work it won't need any major changes to fix it.
// Example XX - Receiving binary data with start marker and message length
const byte numBytes = 32;
byte receivedBytes[numBytes];
byte numReceived = 0;
boolean newData = false;
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvBytesWithStartMarkerAndCount();
showNewData();
}
void recvBytesWithStartMarkerAndCount() {
static boolean recvInProgress = false;
static byte ndx = 0;
byte startMarker= 0xAC;
static byte messageLen = 0;
byte rb;
while (Serial.available() > 0 && newData == false) {
rb = Serial.read();
if (recvInProgress == true) {
if (messageLen == 0) {
messageLen = rb;
}
else {
receivedBytes[ndx] = rb;
ndx++;
if (ndx >= messageLen) {
receivedBytes[ndx] = '\0'; // terminate the string
recvInProgress = false;
numReceived = ndx; // save the number for use when printing
ndx = 0;
messageLen = 0;
newData = true;
}
}
}
else if (rb == sizeof(startMarker)) {
recvInProgress = true;
}
}
}
void showNewData() {
if (newData == true) {
Serial.print("This just in (HEX values)... ");
for (byte n = 0; n < numReceived; n++) {
Serial.print(receivedBytes[n], HEX);
Serial.print(' ');
}
Serial.println();
newData = false;
}
}
...R