Accessing Serial while SD card open seems to kill the SD card connection

Hi All,

I have a project that I am having a little trouble with. I have a connection open to a file on a SD card (File dataFile) and when I call a readBytes function that I have to get some input on the Serial line it seems to kill the dataFile object.

Here is the readBytes function

void readBytes() {
  bufferLength = 0;
  while (Serial.available() > 0) {
    buffer[bufferLength] = Serial.read();
    bufferLength++;
  }
}

Both bufferLength and buffer are defined globally as int buffer[16] and int bufferLength.

If I access data from the SD card with dataFile.available() and dataFile.read() before running that bit of code there no problems. But if I run it afterwards then the SD reading goes into an infinite loop returning -1

I am using one of the original Ethernet shields for SD card access fo CS is pin 6 and I have rewired the pins to get the SD card to work.

Could it be a RAM issue running out of space?

Cheers, Dean

That loop doesn't do bounds checking - you will be overwriting memory outside the buffer I reckon. You always have to check for array bounds if code is to be robust.

Ah k, so it would be getting to index 17 and overwriting whatever is there (in this case could be the SD card library) and killing the dataFile pointer?

By checking array bounds do you mean

void readBytes() {
  bufferLength = 0;
  while (Serial.available() > 0) {
    if(bufferLength <= 16) {
      buffer[bufferLength] = Serial.read();
    }
    bufferLength++;
  }
}

that will check bounds.
Add an else to the if and do something with the buffer to allow more reads, otherwise all the remaining data is ignored in the loop until next time the code passes through.
This will never happen as the Serial.available() will stay above 0 until no data is left causing an infinite loop.

That worked a charm, just need to do some checking to see if the buffer is full, it shouldn't have been more than 16 bytes but something must have been playing up and messing the SD library up. I just expanded it out to 32 and then had it die if it was more than that (as anything larger than that is wrong).

Thanks for all your help!