@@ -163,31 +163,30 @@ namespace sfe_KX13X
163
163
if (!_i2cPort)
164
164
return -1 ;
165
165
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
168
168
169
- while (numBytes > 0 )
169
+ while (( numBytes > 0 ) && (failCount < 2 )) // Give up after 2 bad requests
170
170
{
171
171
_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
179
173
if (_i2cPort->endTransmission () != 0 )
180
- return -1 ; // error with the end transmission
174
+ return -1 ; // Fail immediately if the transmission isn't successful
181
175
182
176
// We're chunking in data - keeping the max chunk to kMaxI2CBufferLength
183
177
nChunk = numBytes > kChunkSize ? kChunkSize : numBytes;
184
178
185
- nReturned = _i2cPort->requestFrom ((int )addr, (int )nChunk, (int )true );
179
+ nReturned = _i2cPort->requestFrom ((int )addr, (int )nChunk, (int )true ); // Always send a stop
186
180
187
181
// No data returned, no dice
188
182
if (nReturned == 0 )
189
183
return -1 ; // error
190
184
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
+
191
190
// Copy the retrieved data chunk to the current index in the data segment
192
191
for (i = 0 ; i < nReturned; i++)
193
192
{
@@ -197,9 +196,12 @@ namespace sfe_KX13X
197
196
// Decrement the amount of data recieved from the overall data request amount
198
197
numBytes = numBytes - nReturned;
199
198
199
+ // Increment reg by the same ammount
200
+ reg += nReturned;
201
+
200
202
} // end while
201
203
202
- return 0 ; // Success
204
+ return (numBytes == 0 ? 0 : - 1 ) ; // 0 = success (all bytes read), -1 = error
203
205
}
204
206
205
207
// ////////////////////////////////////////////////////////////////////////////////////////////////
0 commit comments