Serial.read() only works with Serial.print()

Hi,

I'm trying to send binary data to the arduino where I use the following code to determine when a packet starts and ends:

void readSerialString () {
  char in_char;
  char bin_buf[256]; // outgoing buffer
  int bytes_out = 0; // counter for filling bin_buf
  int pre_counter = 0;
  int pst_counter = 0;

    while (Serial.available() > 0) {
        if(bytes_out < 255) {
        in_char = Serial.read();

        Serial.print("......");        // why is this even necessary?

// state machine:

      if (pre_counter < 3) {
// no valid preamble found yet
        if (in_char == 'A') { // possible part of preamble found, increase counter
          pre_counter++;
        } else {
          pre_counter = 0;
        }
      } else {
// preamble complete, start pushing chars to buffer
        if (pst_counter < 3) {
          bin_buf[bytes_out++] = in_char;
          if (in_char == 'E') { // possible part of pst found, increase counter
            pst_counter++;
          }
        } else {
          do_something(bin_buf);
          pre_counter = 0;
          pst_counter = 0;
          bytes_out = 0;
         memset(&bin_buf, 0, 256);
        }
      }
    } else {
      memset(&bin_buf, 0, 256);
      bytes_out = 0;
    }
  }
}

Here comes the weird part:

This works, but only with the Serial.print("......"); statement. If I leave that out the Arduino doesn't even seem to read the serial buffer, let alone ever get to the do_something(bin_buf); statement. It doesn't seem to matter what characters are in the Serial.print() as long as there are at least six bytes.

I'm lost. Can anybody help?

Regards,

Ali

nevermind, I got it:

When I define the variables (all of them!) outside the function, it works as expected. No idea why it would need the Serial.print() otherwise..

alibenpeng:
nevermind, I got it:

When I define the variables (all of them!) outside the function, it works as expected. No idea why it would need the Serial.print() otherwise..

In my experience unexplained problems that go away for unexplained reasons are not gone; they'll just reappear at some undetermined time. You might have a RAM problem too, but I'd look hard at those memset() calls, maybe drop the ampersand (&) from the &bin_buf in the function call argument list. That doesn't seem right to me. I'm thinking something like:

memset(bin_buf, 0, 256);