sparkfun / SparkFun_BME280_Arduino_Library

An Arduino library to control the BME280 humidity and pressure sensor.
https://www.sparkfun.com/products/14348
Other
119 stars 113 forks source link

Usage of Wire library (not a bug, only source code aesthetics) #52

Open Koepel opened 2 years ago

Koepel commented 2 years ago

The way that the function Wire.requestFrom() is used can be improved. Others are copying this code and the comment that the slave (Target) may send less than requested is confusing, because that is not correct.

The Wire.requestFrom() is used in 4 places. One way to improve it could be this:

// request bytes from slave device
uint8_t n = (uint8_t) _hardPort->requestFrom(settings.I2CAddress, length);
if (n == length)
{
  while (_hardPort->available() > 0)
  {
    c = _hardPort->read(); // receive a byte as character
    *outputPointer = c;
    outputPointer++;
  }
}

The while can be a for (uint8_t i=0; i<n; i++), because once the received number of bytes is the same as the requested number of bytes, it is 100% sure that those bytes can be read with Wire.read().

A while is confusing if only one byte is read. It can be this:

uint8_t n = (uint8_t) _hardPort->requestFrom(settings.I2CAddress, numBytes);
if (n == numBytes)
{
  result = _hardPort->read(); // receive a byte as a proper uint8_t
}

This new code will do exactly the same thing as the old code in every situation. It is only source code aesthetics.