Is this usage of Wire.write() correct ?

hello all,

we are experimenting with Arduino for the first time using the I2C connection to another microcontroller.

from ;

we learned that;
a)

void setup()
{
  // join i2c bus (address optional for master)
  Wire.begin();
}

void loop()
{
  Wire.beginTransmission(4); // transmit to device #4
  Wire.write("x is ");       // write five bytes
  Wire.write(x);             // write one byte  
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

is okay

and
b)

void setup()
{
  Wire.begin(2);   
  Wire.onRequest(requestEvent);
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Wire.write("hello ");  
}

is also okay.

but when we try;

b)

void setup()
{
  Wire.begin(2);   
  Wire.onRequest(requestEvent);
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Wire.write("x is ");       // write five bytes
  Wire.write(x);             // write one byte  
}

it is not okay.
only the last Wire.write() is received on the master-side.

is the above syntax (two times Wire.write() in a RequestEvent) valid ?

You could always do something like:

char stuffToSend[10];
sprintf(stuffToSend, "x is %d", x);
Wire.write(stuffToSend);

in the requestEvent() function.

only the last Wire.write() is received on the master-side.

That's right. That's what happens.

Inside a requestEvent if you try to do two writes the second one overwrites the buffer that the first one used.

As PaulS said, you need to construct a single string (or buffer) and send that with a single write.

[quote author=Nick Gammon link=topic=119628.msg901045#msg901045 date=1345676108]

only the last Wire.write() is received on the master-side.

That's right. That's what happens.

###[/quote]
i see, thanks for confirming that - will have to work around that then.

ah yes, we had started thinking of concetanating the strings but encountered 'variable type' errors - will have to study how to convert using byte() and thanks PaulS for pointing out the use of sprintf.

Cheers All !