sparkfun / MPL3115A2_Breakout

Example code and board files for MPL3115A2 Breakout board.
https://www.sparkfun.com/products/11084
29 stars 50 forks source link

No need to wait for data after Wire.requestFrom() #15

Open Koepel opened 7 years ago

Koepel commented 7 years ago

In three places in MPL3115A2.ino there is a while-loop with a delay. That while-loop is not needed and that delay is not needed.

When the Wire.requestFrom() function returns, the I2C transaction has completely finished and the received data is in the receive buffer in the Wire library. The Wire.read() only reads from that buffer.

nseidle commented 7 years ago

I was working on a similar routine for the HTU21D library. There is a case (at least for that sensor and may be this one as well) where the sensor stops responding while it does its internal calcs.

You are correct, a Wire.requestFrom() will return a value without blocking the rest of the code. However, if the sensor is internally calculating, requestFrom will return zeros. These while-loop with delay tricks may be necessary for some sensors while we wait for the sensor to complete its calcs. (I haven't yet dug into the MPL3115A2 to figure out if it is or is not one).

Koepel commented 7 years ago

A delay or timeout after the Wire.requestFrom() has no use. The I2C transmission has already finished and the data is in a buffer inside the Wire library. This sensor does indeed not acknowledge to the I2C bus when it is busy. The Wire.requestFrom() must be part of a timeout and the Wire.requestFrom() should be called a number of times, until it returns data from the sensor. Sorry that I didn't mention this before.

Or a fixed delay between the endTransmission() and requestFrom(). According to the datasheet the 14-bit conversion takes 50ms for the HTU21D.

In some libraries there is a fixed delay() after the Wire.requestFrom() to make it work. However, that delay does not influence the current I2C transmission, but it is a delay for the next I2C transmission.

nseidle commented 7 years ago

I think we're agreeing and saying the same thing. Please ping the HTU21D Library https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library if you are seeing something that I'm not.

Koepel commented 7 years ago

The datasheet of the MPL3115A2 seems to tell that the sensor is always available on the I2C bus (as long as it is not powered down), but the status bit will tell if the data is ready. That is polled at a higher level, and there is no need to do multiple requestFrom() or wait before or after the requestFrom() itself. If the requestFrom returns zero or other wrong value, then there is something wrong with the I2C bus.