The code had several issues leading to a constant flow of wrong data (with correct data in the middle) between the master that won the bus arbitration. This made it keep the bus too long and eventually give it away to the second master at a random time, with missed transfers from the second master in between. The second master was then behaving the same and so on.
receiveEvent
, on the slave side, contained a millis
if
condition timer that made it time out. I moved the timer to the master side before calling Wire.requestFrom
. Avoid slow code in receiveEvent
!
receiveEvent
, on the slave side, was also confusing real data with incoming requestEvent
. I added an if
statement to compare the receiveEvent
data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the Wire
library)
These fixes solved the busy bus problem. I figured these out after asking question #35092
The bus speed also had to be reduced because 800 kHz was too fast for the Mega 2560 (but worked between 3 Nano).
The slave has to send the data destined to both masters to each of them because requestEvent
can't tell which master is asking for data. The data is then filtered on each master to only keep the relevant information.
The data is now being transferred both ways between the 2 Nano masters and the Mega slave at the correct interval, without corrupt data.
fixed Slave code
fixed Master 1 code
fixed Master 2 code in the same repo (I'm limited to 2 links post)