Skip to content

Common mistakes

Koepel edited this page Mar 24, 2018 · 22 revisions

1

Mistake 1: Waiting after calling the Wire.requestFrom()

The Wire.requestFrom() is blocking. It will wait until the I2C bus transaction has finished.
That means that no waiting is needed. If data was received, that data is in a buffer (inside the Wire library) and ready to be read with Wire.read().

The Wire.requestFrom() was either succesfull or not.

Wire.requestFrom(0x28, 2);
while(Wire.available() < 2); <--- common mistake, don't do this
x = Wire.read();
y = Wire.read();

Is it bad ? Yes.
When the sensor is not connected, the Wire.available() will return zero. That while(Wire.available code will run forever and the sketch will stop.
The Wire library can detect a few problems on the I2C bus. If such a problem is detected, the Wire.available() might also return zero, and that while(Wire.available code will stop the sketch.

2

Mistake 2: Using Wire.endTransmission() after a Wire.requestFrom()

The Wire.requestFrom() will do a complete I2C bus transaction with: START, send address, read data, STOP.

The Wire.endTransmission() has no function in this. It should only be used when writing data and only together with Wire.beginTransmission().

Wire.requestFrom(0x40, 1);
x = Wire.read();
Wire.endTransmission(); <--- common mistake, don't do this

Is it bad ? Yes, maybe.
The Wire.endTransmission() could start a I2C bus transaction and the sensor acknowledges to its address. That extra bus activity takes time. It will probably not disturb the sensor. Since there are a number of Wire compatible libraries, other libraries can do other things.

3

Mistake 3: Using Wire.beginTransmission() before a Wire.requestFrom()

The Wire.beginTransmssion() should only be used when writing data. It works together with Wire.endTransmission() but not with Wire.requestFrom().

Wire.beginTransmission(0x68); <--- common mistake, don't do this
Wire.requestFrom(0x68,2);

Is it bad ? No, probably not.
The Wire.beginTransmission() clears a few variables to get ready to write to a sensor. That is no problem.
There are however some Wire compatible libraries that already put a START condition on the I2C bus. That means that the I2C bus does no longer work according to the I2C specifications.