Writing to SD card disturbs serial connection with other device

Hello all

I have the following layout on my atmega2560:
MicroSD Adapter
CS -> 40
SCK -> 52
MOSI -> 51
MISO -> 50

Fingerprint reader:
RX2 and TX2

When donwloading a fingerprint image from the fingerprint reader over Serial2 everything is fine. A bunch of 128 byte sized packets are sent over the serial interface. Now as soon as I write those to a file on my SD card, after a few packets i receive weird data from the fingerprint reader.

Two examples from the code:

Without writing to the SD card (everything is fine and I see a bunch of 130 byte packets being logged:

    while (header.type() != PacketType::DATA_END) {
        header = read_response(buffer, sizeof buffer, num_read);

        if (num_read < 2) {
            Serial.println("Expected at lest the checksum");
            return false;
        }
    }

the read_response is essently just doing a Serial2.readBytes for the header and then a Serial2.readBytes for the data of the specified length.

I first extended this to the following:

auto file = SD.open("finger.img", O_WRITE | O_CREAT | O_SYNC | O_TRUNC);

while (header.type() != PacketType::DATA_END) {
  header = read_response(buffer, sizeof buffer, num_read);

  if (num_read < 2) {
    Serial.println("Expected at lest the checksum");
    return false;
  }

  if (num_read == 2) {
    continue;
  }

  file.write(buffer, num_read - 2);
}

With this code the first packet is read from the fingerprint sensor, it has the correct size, then the file.write happens and the next read_response returns a packet that has a header with random data (different every time).

If I just remove the file.write it is back to normal again.

How can these things be related to eachother? Could it be an issue with the write using too much current? Edit: I have put the SD card reader and the finger print sensor to different power sources, no difference.

BR
Yanick

The issue is a timing issue. The finger print sensor was working at a quite high baud rate (57600) and the write to the SD card took too much time, thus filling up the serial buffer, discarding some data.

I am now trying to set the finger print sensor to 9600 baud rate and increase the size of the arduinos serial buffer to make sure I can transfer the roughly 17kb of data without running into overflows.

You didn't post your entire code, but I am guessing you are using SoftwareSerial.
It does not work at 57600.

.

Its a HardwareSerial:

_finger_print = new r502_finger{Serial2};

Going to 19200 and having a 256 bytes serial buffer made it work.