Skip to content

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

Open
@Koepel

Description

@Koepel

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions