Wire requestFrom(): How many bytes were requested from the master?

Hi there,

I’m currently working on a Arduino-I2C slave device with multiple registers/values the master (also an Arduino for now) needs to read out. I want to be able to read multiple bytes at once by using the Wire.requestFrom(SLAVE, numOfBytes)-Method. But therefore the slave needs to know the number of bytes requested from the master. How can I get this number?

My master program looks like this:

#include <Wire.h>

#define SLAVE 0x86
#define REGISTER 0x6B

void setup() 
{
  Wire.begin();
  Serial.begin(9600);  
}

void loop()
{
  Wire.beginTransmission(SLAVE);
  Wire.write(REGISTER);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE, 4);
  
  if(Wire.available())
  {
    char c = Wire.read();
    Serial.println(c);
  }

  delay(500);
}

Slave:

#include <Wire.h>

#define ADDRESS 0x86

#define REGISTER 0x6B

byte data[4];
byte currentRegister;

void setup() 
{
  Wire.begin(ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

//Called, when the master calls Wire.write()
void receiveEvent()
{
  if(Wire.available())
  {
    //Set the currently selected register.
    currentRegister = Wire.read();
  }
}

//Called, when the master calls Wire.requestFrom()
void requestEvent()
{
  //Get the number of requested bytes.
  //How can I get this number???
  int requestedBytesCount = ?             //HELP!

  //Return different data, depending on the currently selected register.
  
  if(currentRegister == REGISTER_1)
  {
    for(int i = 0; i < requestedBytesCount; i++)
    {
      //Send the data a the i-th position of the data-Array
      Wire.write(data[i]);
    }
  }
  //Code for the other registers
}

void loop()
{
}

How can I get this number?

With the current Wire library implementation you cannot. The only way to implement it is to fill the buffer with the maximum number of bytes the master may request. If the client recognize a stop condition it will empty the buffer as soon as the next request arrive.

You may read this: Doubts on Wire library implementation - Programming Questions - Arduino Forum.

The buffer size for normal AVR Arduino boards is 32 bytes. I have Slave Arduino boards with array/register/values that is more than 32 bytes in the Slave.
The 'currentRegister' (or register address) is set by the Master and after that some bytes are requested. Because the Slave does not know how many bytes will be requested, I just fill all the 32 bytes with a single Wire.write(), starting from the offset of 'currentRegister' (or register address).