platisd / AndroidCar

Arduino library to control an Android Autonomous Vehicle by Team Pegasus
GNU General Public License v3.0
45 stars 15 forks source link

No need to wait after Wire.requestFrom(). #1

Closed Koepel closed 6 years ago

Koepel commented 6 years ago

In the file "AndroidCar/SRF08.cpp", the while (Wire.available() < 2); after a Wire.requestFrom() can be removed.

In the file "AndroidCar/Gyroscope.cpp", the

while(!Wire.available()) {
        //waiting
}

can be removed. Explanation: Common-mistakes#1

platisd commented 6 years ago

I see... So apparently the correct way to do this is:

if (Wire.requestFrom (SLAVE_ADDRESS, responseSize) == 0)
  {
  // handle error - no response
  }
else
  {
  // data received, now use Wire.read to obtain it.
  }

Will fix this later today, thanks!

Koepel commented 6 years ago

At this moment the Wire.available() returns zero when a problem could be detected. However, according to the Arduino documentation, the Wire.available() might return less than the number of requested bytes (when there was I2C bus problem). That is why I prefer to test the number of received bytes.
If 2 dollars are transferred, then the transfer is successful if 2 dollars are received.

if (Wire.requestFrom (SLAVE_ADDRESS, responseSize) == responseSize)
{
  // success
}

Since there is no testing for the return value of Wire.endTransmission(), testing if the Wire.requestFrom() was successful is not very useful. In my opinion a Wire.requestFrom() without any checking would be just as good in the file SRF08.cpp.

platisd commented 6 years ago

the Wire.available() might return less than the number of requested bytes (when there was I2C bus problem)

I guess you mean Wire.requestFrom might return less than the number of requested bytes, therefore comparing with 0 does not completely safeguard against I2C problems. Thanks for the fair point!

I will apply these changes to the smartcar_shield project as well, since this one is practically inactive.

Koepel commented 6 years ago

Yes, I ment the Wire.requestFrom or the first Wire.available (before any Wire.read).

By the way, Nick Gammon compares the Wire.requestFrom with 0: www.gammon.com.au/forum/?id=10896&reply=4#reply4.