Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Koepel opened this issue Jan 14, 2022 · 0 comments
Open

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

Koepel opened this issue Jan 14, 2022 · 0 comments

Comments

@Koepel
Copy link

Koepel commented Jan 14, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant