This question is regarding examples from the Wire library, written by Nicholas Zambetti http://www.zambetti.com.
In this example (master_reader.pde and slave_writer.pde), the master requests 6 bytes from slave 2.
Wire.requestFrom(2, 6); // request 6 bytes from slave device #2
Somewhere the number of bytes requested gets thrown out. On the slave side you see:
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
Wire.send("hello "); // respond with message of 6 bytes
// as expected by master
}
Is there any way to recover the number of bytes requested?
Thanks,
Justin
Is there any way to recover the number of bytes requested?
No, the Wire lib does not provide such info so you must use a local var for it.
int x = 6;
int y = Wire.request(2, x);
// x will hold the nr of bytes requested
// y will hold the nr of bytes actually read.
Check the library for details : - C:\Program Files (x86)\arduino-0021\libraries\Wire (my windows).
Bearing in mind that the Wire library supports a maximum of 32 bytes per transmission, I think there are two ways you can do this.
The first is, as part of the initial send, tell the receiver how many bytes you want, eg.
Wire.beginTransmission (SLAVE_ADDRESS);
Wire.send (1); // do action 1
Wire.send (6); // and I want 6 bytes back, thanks!
Wire.endTransmission ();
Wire.requestFrom(SLAVE_ADDRESS, 6); // request 6 bytes from slave device
Now the slave reads those two bytes and knows it has to perform action 1 (whatever that is) and limit its response to 5 bytes.
Alternatively, I think you could just request a response, eg.
Wire.beginTransmission (SLAVE_ADDRESS);
Wire.send (1); // do action 1
Wire.endTransmission ();
Wire.requestFrom(SLAVE_ADDRESS, 32); // request up to 32 bytes from slave device
while (Wire.available () > 0)
{
// process each byte
} // end of while
And then just use Wire.available to know how many bytes the slave sent back.
Thanks. I'll give these ideas a try.
Justin