I suggest you redesign your protocol a bit. Sending a string is slow and inefficient. For one thing, you have to buffer the string up at the receiving end, you have to worry about making it null-terminated, the library routines to do a strcmp will take memory, you have to worry about the string overflowing whatever size buffer you allocate, etc.
So, instead of sending the string "requestid" you might send (for example) 0x01 which means to you, "I request your ID". Then the receiver only has to store one byte (the command). Then it might reply with a single byte (eg. 0x01 for ID 1, 0x02 for ID 2). Then if you need a different command (eg. take sensor reading) you might send 0x02.
Anyway, on to the "bug". When I was testing this:
void requestEvent ()
{
if (strcmp (buf, "requestID") == 0)
{
Wire.send ((byte *) "id1", 4);
bufpos = 0; // empty buffer out
}
} // end of requestEvent
I found that worked, but looked a bit strange. I initially had this, which looks better:
void requestEvent ()
{
if (strcmp (buf, "requestID") == 0)
{
Wire.send ("id1"); // send string
Wire.send (0); // string terminator
bufpos = 0; // empty buffer out
}
} // end of requestEvent
Sending a string does not send the null-terminator, so the other end doesn't know when it has fully been received. So I added the second Wire.send (0) to send the extra zero. But in fact, all that got sent was the zero, and not the string!
The code that handles this case in twi.c is here:
/*
* Function twi_transmit
* Desc fills slave tx buffer with data
* must be called in slave tx event callback
* Input data: pointer to byte array
* length: number of bytes in array
* Output 1 length too long for buffer
* 2 not slave transmitter
* 0 ok
*/
uint8_t twi_transmit(uint8_t* data, uint8_t length)
{
uint8_t i;
// ensure data will fit into buffer
if(TWI_BUFFER_LENGTH < length){
return 1;
}
// ensure we are currently a slave transmitter
if(TWI_STX != twi_state){
return 2;
}
// set length and copy data into tx buffer
twi_txBufferLength = length;
for(i = 0; i < length; ++i){
twi_txBuffer[i] = data[i];
}
return 0;
}
Notice how every time you call Wire.send in "slave transmitter" mode it simply replaces the existing buffer with the new data? So it would have put "id1" into the buffer, and then on the second "send" call replaced the "i" by a zero.
I'm not sure if this is by design (what design?) or simply a bug.
However a point worth nothing is that in the current library, when replying to a "requestFrom" event, you need to fully assemble your reply into a single buffer and call wire.Send
once.