Reading txt file from SD card and sending over I2C

ozil_11:
I'm facing the same problem. I logging the data of my analog sensor and wanted to send this data from the sd card to my Esp8266 module through I2C. Did you find any solution for that?

The I2C slave mode on the Arduinos send/receive one block of data.

The slave does not know how big the requested block is, so, The block size must be known before onRequest() is executed.

If you have don't have fixed length data you are going to have to write a 'protocol' that encapsulates this random length data.

Let us say that every onRequest() returns 30 bytes. And I want to be able to send 200 bytes from the Slave to the Master;

on the slave:

#define BUFFERLEN 200
volatile static byte bufPos=0; // next byte to send to master
volatile statc byte buffer[BUFFERLEN];
volatile static byte bufLen=0; // 

void request(void){
byte len = 29; // maximum number of bytes to send to Master, must leave room for count of byte
byte tempBuffer[30];

if(len > (bufLen-bufPos)) len = (bufLen-bufPos); // can't send more than exist in buffer


tempBuffer[0] = len; // send length of the valid data in this block as first byte in block
if(bufPos < BUFFERLEN)
  memmove(&tempBuffer[1],&buffer[bufPos],len); // copy up to the next 29 bytes into a transmit buffer

bufPos = bufPos + len;  // when last partial buffer is send, bufPos will equal bufLen so len ==0, (end of data)

Wire.write(tempBuffer,len+1); // data + count
} 

void receive(int len){
// assume only 1 byte is ever send, use that byte to adjust the bufPos value
bufPos = Wire.read();
bufPos = bufPos % BUFFERLEN; // make sure bufPos is 0..(BUFFERLEN-1)

}

void setup(){
Wire.begin(0x15); // set slave address a 0x15
Wire.onRequest(request);
Wire.onReceive(receive);
strcpy((char*)buffer,"This is a test of the emergency broadcasting system\n");
bufLen = strlen((char*)buffer);
}

void loop(){}
//***************
//master

void readblock(){
byte bkLen=0;
#define BUFFLEN 50
char buffer[BUFFLEN];
// set buffer address in slave to 0, start at beginning of buffer

Wire.beginTransmission(0x15);
Wire.write(0);
Wire.endTransmission();

// read from slave until slave sends a '0' length block.

do{
  buffer[0] = 0; // init to zero byte block length 
  bkLen = 0;
  Wire.requestFrom(0x15,30); // request a 30 byte block of data

  while (Wire.available()&&(bkLen<BUFFLEN)){ //data avail, and room in buffer
    buffer[bklen++] = Wire.read();
    }
  buffer[bkLen] = '\0'; // terminate the string 
  Serial.print((char*)&buffer[1]); // print the data to the serial port

  }while(buffer[0] != 0);
}

void setup(){
Serial.begin(115200);
Wire.begin();
readblock();
}

void loop(){}

Chuck.