Skip to content

Commit ad8eaee

Browse files
authored
Merge pull request #21 from sparkfun/Suggested_readRegisterRegion_changes
Suggested read register region changes
2 parents d638ab0 + d0166fc commit ad8eaee

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/sfe_bus.cpp

+15-13
Original file line numberDiff line numberDiff line change
@@ -163,31 +163,30 @@ namespace sfe_KX13X
163163
if (!_i2cPort)
164164
return -1;
165165

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

169-
while (numBytes > 0)
169+
while ((numBytes > 0) && (failCount < 2)) // Give up after 2 bad requests
170170
{
171171
_i2cPort->beginTransmission(addr);
172-
173-
if (bFirstInter)
174-
{
175-
_i2cPort->write(reg);
176-
bFirstInter = false;
177-
}
178-
172+
_i2cPort->write(reg); // Write the register address we want to read from
179173
if (_i2cPort->endTransmission() != 0)
180-
return -1; // error with the end transmission
174+
return -1; // Fail immediately if the transmission isn't successful
181175

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

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

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

185+
// Check we got back as much data as was requested.
186+
// (Fringe case. This should never happen... But, you know, it _could_...)
187+
if (nReturned != nChunk)
188+
failCount++; // Increment the failCount
189+
191190
// Copy the retrieved data chunk to the current index in the data segment
192191
for (i = 0; i < nReturned; i++)
193192
{
@@ -197,9 +196,12 @@ namespace sfe_KX13X
197196
// Decrement the amount of data recieved from the overall data request amount
198197
numBytes = numBytes - nReturned;
199198

199+
// Increment reg by the same ammount
200+
reg += nReturned;
201+
200202
} // end while
201203

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

205207
//////////////////////////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)