These are the “Master” and “Slave” sample sketches from this page for usine Wire.
// MASTER READER
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
delay(500);
}
// SLAVE SENDER
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}
void loop() {
delay(100);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
Wire.write("hello "); // respond with message of 6 bytes
// as expected by master
}
In the MASTER sketch, the line “Wire.requestFrom(8, 6);” is asking SLAVE sketch number 8 to send 6 bytes of information. But what effect does the number “6” have?
The MASTER then says “while (Wire.available())”, admitting it doesn’t know how many bytes are actrually going to be sent back. And at the same time, I don’t see any way for the SLAVE sketch to know that “6” is the number of bytes asked for.
In my case, the SLAVE sketch needs to know how many bytes are asked for, because this will determine what is replied; specificallly, the battery condition (one byte) or a set of bio-feedback values (ten bytes).
+++++++++++++++++++
A second question: Is there a way (within Wire) for the SLAVE sketch to send un-requested info to the MASTER sketch at odd times without the MASTER needing to continuously poll for it?