Skip to content

Suggested read register region changes #21

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

Merged
merged 3 commits into from
Jan 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions src/sfe_bus.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -163,31 +163,30 @@ namespace sfe_KX13X
if (!_i2cPort)
return -1;

int i; // counter in loop
bool bFirstInter = true; // Flag for first iteration - used to send register
int i; // counter in loop
int failCount = 0; // Keep track of how many times nReturned is != nChunk

while (numBytes > 0)
while ((numBytes > 0) && (failCount < 2)) // Give up after 2 bad requests
{
_i2cPort->beginTransmission(addr);

if (bFirstInter)
{
_i2cPort->write(reg);
bFirstInter = false;
}

_i2cPort->write(reg); // Write the register address we want to read from
if (_i2cPort->endTransmission() != 0)
return -1; // error with the end transmission
return -1; // Fail immediately if the transmission isn't successful

// We're chunking in data - keeping the max chunk to kMaxI2CBufferLength
nChunk = numBytes > kChunkSize ? kChunkSize : numBytes;

nReturned = _i2cPort->requestFrom((int)addr, (int)nChunk, (int)true);
nReturned = _i2cPort->requestFrom((int)addr, (int)nChunk, (int)true); // Always send a stop

// No data returned, no dice
if (nReturned == 0)
return -1; // error

// Check we got back as much data as was requested.
// (Fringe case. This should never happen... But, you know, it _could_...)
if (nReturned != nChunk)
failCount++; // Increment the failCount

// Copy the retrieved data chunk to the current index in the data segment
for (i = 0; i < nReturned; i++)
{
Expand All @@ -197,9 +196,12 @@ namespace sfe_KX13X
// Decrement the amount of data recieved from the overall data request amount
numBytes = numBytes - nReturned;

// Increment reg by the same ammount
reg += nReturned;

} // end while

return 0; // Success
return (numBytes == 0 ? 0 : -1); // 0 = success (all bytes read), -1 = error
}

//////////////////////////////////////////////////////////////////////////////////////////////////
Expand Down