Slave I2C and Serial receive on Mega 2560

There seems to be an issue using the wire library as a slave I2C at the same time as the (or any) serial port on a Mega 2560.

I have code which receives I2C data, but whilst I2C data is received, it seems also to populate the serial receive buffer. This the (minimised) receive code for I2C

void receiveEvent(int howMany)
	while(Wire.available()) // loop through



but then the (minimised) receive event for Serial is also fired:

void serialEvent() {
	while (Serial.available()) {;
                Serial.print(recbyte);    //echo

So the effect is that data received on the I2C bus is sent twice.

Somewhat wierdly, this does not occur with an Uno. Just a Mega.

Any ideas?

It happens on the Uno and the Mega.
You can not use any Serial function in the receiveEvent(). Also no delays, no while-loops and a lot more.
Somtimes it might seem to work a little. But just don't use Serial in receiveEvent().

By the way, the "howMany" variable is the same as Wire.available() in that function. You could use the "howMany" and read that many bytes into a buffer.

The serialEvent() is at the same level as the loop() function. You can use Serial functions in a normal way in serialEvent().

Thanks for your observations.

So far, I don't see the problem on Uno, having pumped upwards of around 10,000 messages through it. But I've taken your suggestion of removing the wire.available with a for loop based on the number of characters.

In fact, my original code in its complete version was buffer based. The receiving functions (at the same level of "loop" or otherwise) simply set a flag if they had data, and then the data was despatched from a buffer when the flash was detected during a "loop" execution. But this exhibited the same problem, so I reduced it to the minimum set of code which displays the issue, to help diagnostics.

When I get a moment, I'll re-create the buffer based example.

I don't care if it worked or not :smiley: , don't use the Serial library in a receiveEvent function. Not even for debugging.