Issue when I try to send myFile.read from the SD via I2C to another Arduino.

Good afternoon,

I have this portion of code. My attempt is to send the buffer myFile.read coming from an SD card to another Arduino via I2C protocol.

#include <Wire.h>
#include <SPI.h>
#include <SD.h>

File myFile;
String buffer;
char dati[10];


void setup() 
{
  Serial.begin(9600);
  //while (!Serial){;} // wait for serial port to connect. Needed for native USB port only
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event

  Serial.print("Initializing SD card...");
  if (!SD.begin(10))
  {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  
}
void loop() 
{
   delay(100);
}


void requestEvent() 
{ 
 myFile = SD.open("test.txt");
  if (myFile) 
  {
    Serial.println("test.txt:");
    Serial.println(myFile.size());
  
    while (myFile.available()) 
    {
     buffer = myFile.read();
     buffer.toCharArray(dati, 60);
    }
    myFile.close();
   Wire.write(dati, sizeof(dati));
  } 
  else 
  {
    Serial.println("error opening test.txt");
  }
  
}

This is the Arduino slave’s code.

I have two issues:

while (myFile.available())

This while is freezing my program.
If I delete it, the program starts to work fine.
I need this part for another purpose, so I need to leave it.
Can you help me finding the mistake?

  1. I am not sure that this is the correct way to send a buffer via I2C, because if I read the single lines from an SD I can do it without any issue but it doean’t works with the whole file (all lines packaged in the same buffer).
     buffer = myFile.read();
     buffer.toCharArray(dati, 60);
    }
    myFile.close();
   Wire.write(dati, sizeof(dati));

Many thanks.

Your line of code just calls the function: file.available() and does nothing with the return value, so just loops there.

Perhaps you want "while (myfile.available == 0); or something like that.

Paul

Paul_KD7HB:
Your line of code just calls the function: file.available() and does nothing with the return value, so just loops there.

Perhaps you want "while (myfile.available == 0); or something like that.

Paul

  1. For the point 1 I have realized that the issue could be caused by bad wiring between the SD card reader and Arduino. So it can be an hardware related problem.

For the point 2 I have noticed that if this char array exceeds 32 elements,

Wire.write(dati, sizeof(dati))

the Arduino receiver won't see any data.
I will open a new and more specific post for this question.
Many thanks.