Possible bug in i2c communication?

The Xiao, like some other Arduino parts in the past, like Arduino Due, have been seeing the OnRecieve callback function triggered with the argument “howmany” equal to zero. This is not suppose to happen. It was explained to me that if the sending program sent 5 bytes, then when the callback function was triggered howmany would be 5 and Wire.available() would also return 5, and after the first call to Wire.read() it would decrement and then 4 on the second call, etc. When it got to zero you were done.

I was getting some triggers where howmany was zero and Wire.available() returned 0 on the first trigger of the OnReceive callback function. I have a workaround to test for these conditions. It appears that the OnReceive callback function gets triggered for each message once with howmany = 0 and then again with the right number. I’m going to do further testing and send different number of bytes in the initial message to the slave.

So this is a bug that has been seen before. I’ll see if the Seeedunio folks can do something about it.

I’ll post the receive program below:
/*
Modified from the demo that Dronebotworkshop created.
I2C Slave Demo
i2c-slave-demo.ino
Demonstrate use of I2C bus
Slave receives character from Master and responds
DroneBot Workshop 2019
https://dronebotworkshop.com
*/

// Include Arduino Wire library for I2C
#include <Wire.h>

// Define Slave I2C Address
#define SLAVE_ADDR 9

// Define Slave answer size
#define ANSWERSIZE 5

// Define string with response to Master
String answer = “Hello”;

int num_howmany_zero = 0;
int num_request_received = 0;

void setup() {

// Initialize I2C communications as Slave
Wire.begin(SLAVE_ADDR);

// Function to run when data requested from master
Wire.onRequest(*requestEvent);

// Function to run when data received from master
Wire.onReceive(*receiveEvent);
}

void receiveEvent(int howmany) {
byte x = 0;
if (howmany == 0) {
num_howmany_zero += 1;
return;
}

// Read while data received
while (Wire.available()) {
x = Wire.read();
}

}

void requestEvent() {

// Setup byte variable in the correct size
byte response[ANSWERSIZE];

// Format answer as array
for (byte i=0;i<ANSWERSIZE;i++) {
response[i] = (byte)answer.charAt(i);
}

// Send response back to Master
Wire.write(response,sizeof(response));
num_request_received += 1;
}

void loop() {

// Time delay in loop
delay(50);
// SerialUSB.println("\n----------");
// SerialUSB.print("num_request_received = ");
// SerialUSB.println(num_request_received);
// SerialUSB.print("num_howmany_zero = ");
// SerialUSB.println(num_howmany_zero);

}