Hi. According to the documentation, the two functions below will return the number of bytes that the master has received from the slave and which are available in the buffer.
Wire.requestFrom()
Description
Used by the master to request bytes from a slave device.
Returns
byte : the number of bytes returned from the slave device
Wire.available()
Description
Returns the number of bytes available for retrieval with read().
Returns
The number of bytes available for reading.
But if slave will respond with a less number of bytes than master requested (as is described in Master Reader/Slave Sender Example), then we have a problem because both functions (Wire.requestFrom() and Wire.available()) will return the requested number of bytes, not the number of bytes received from slave. So, the output will be hello ⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮.
master_reader.ino
#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, 32); // request 32 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.ino
#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
}
It will be great if it will be fixed.
Regards,
Florin.
Hi. According to the documentation, the two functions below will return the number of bytes that the master has received from the slave and which are available in the buffer.
But if slave will respond with a less number of bytes than master requested (as is described in Master Reader/Slave Sender Example), then we have a problem because both functions (Wire.requestFrom() and Wire.available()) will return the requested number of bytes, not the number of bytes received from slave. So, the output will be
hello ⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮.master_reader.ino
slave_sender.ino
It will be great if it will be fixed.
Regards,
Florin.