SolderedElectronics / SHT21-Arduino-Library

Arduino library for SHT21 - temperature and humidity sensor. With checksum!
7 stars 11 forks source link

No waiting and no delay needed after Wire.requestFrom() #2

Closed Koepel closed 4 years ago

Koepel commented 7 years ago

In the file "SHT21.cpp" a while-loop is used after the Wire.requestFrom() in two places and a timeout with delayMicroseconds. Those while-loops and that timeout can be removed. There is nothing to wait for.

When the Wire.requestFrom() function returns, the I2C transaction has completely finished and the received data is waiting in a buffer in the Wire library.

davidzovko commented 7 years ago

Hey Koepel,

thank you for your feedback. Feel free to fork it or I would when I find some time for it.

David

davidzovko commented 4 years ago

Fixed!

Koepel commented 4 years ago

The while(Wire.available() < 8) {} after a Wire.requestFrom() does not do something, it makes things worse. You can remove that line. You can remove the other while(Wire.available() < 6) {} as well.

This waiting is also not needed:

Wire.requestFrom(I2C_ADD,3);

while(Wire.available() < 3) {
    delay(10);
    n++;
    if(n>10) return 0;
}

There is nothing to wait for, and the delay(10) is useless. To test if the Wire.requestFrom() was successful, you can do this:

Wire.requestFrom(I2C_ADD,3);
if( Wire.available() != 3) {
  return 0;
}

or this:

int n = Wire.requestFrom(I2C_ADD,3);
if( n != 3) {
  return 0;
}

Explanation: Common-mistakes#1

There is nothing to wait for. There is no I2C bus activity when the Wire.requestFrom() returns. That function is blocking, and the data is stored in a buffer (inside the Wire library). What you do is similar to this:

int i = 3;   // declare integer and make it 3
while( i < 3) {}  // wait until it is really 3