Skip to content

Tricks that are (almost) allowed

Koepel edited this page Mar 28, 2018 · 12 revisions

Reading the data in the loop() in a Slave with empty onReceive handler.

When an Arduino is set as I2C Slave, the interrupt function for receiving data is set with Wire.onReceive(). That interrupt function (the handler function) can be empty and the checking for received data can be done in the loop(). Thus assuming that the data is still available in the buffer after the interrupt function (the handler function) has finished.

This might work, although when new data is received it will replace the old data and in the loop() a mix of old and new data is processed.

The official Arduino Wire libraries clear the buffer when receiving data. That means the old data stays in the buffer and can indeed be used outside the interrupt function.

The main concern is the compatibility with other Wire libraries.

This is allowed at this moment with the official Arduino Wire libraries. However, it is not explicitly mentioned in the documentation that this is supposed to be normal use of the Wire library.

Writing 32 bytes in the Slave onRequest handler, regardless how many the Master will ask.

When the Arduino is set as a Slave, it does not know how many bytes the Master wants when the Master does a Wire.requestFrom(). In the onRequest handler in the Slave it is allowed to fill the buffer up to 32 bytes. The Master could request just 1 or 2 bytes and might stop the I2C bus transaction after that.
This is allowed and will do no harm.

Using the size of the data in the onReceive handler to identify which data it is.

When the Arduino is set as a Slave, the parameter of the onReceive handler tells how many bytes are received. When different kind of data sets are written to the Slave and the data packets have different sizes, then a identifier is not needed and the Slave can use the size to distinguish between the data packets.

Don't try a Multi-Master I2C bus

In 2018 the Wire library for the Arduino Uno can detect a bus collision. That error is processed by the Wire.endTransmission() and Wire.requestFrom(). The experienced Arduino users stay away from a Multi-Master I2C bus, because it has many consequences. It is hard to predict when it still works reliable and when there are too many Masters on the bus. Don't be the first one to attempt to make a Multi-Master I2C bus.

Clone this wiki locally