Arduino I2C long string I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.

I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?

Master makes request for string that could be about 180 bytes max - ever.

Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200 
while (Wire.available()) 
{char c = Wire.read(); 
cmdInStr.concat(c);
}


Slave sends

int len = cmdOutStr.length()+1;
char ascii_num[len];
for (int i=0; i&lt;len; ++i)
{ Wire.write(ascii_num[i]);
}
You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.

There's a number of ways around it though:


Splitting / joining.


The trick here is to split the data into packets and re-assemble it at the remote end.

For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.


two-stage transaction


In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.

If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.

You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.