@@ -164,30 +164,29 @@ namespace sfe_KX13X
164164 return -1 ;
165165
166166 int i; // counter in loop
167- bool bFirstInter = true ; // Flag for first iteration - used to send register
167+ int failCount = 0 ; // Keep track of how many times nReturned is != nChunk
168168
169- while (numBytes > 0 )
169+ while (( numBytes > 0 ) && (failCount < 5 )) // Give up after 5 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
183- nChunk = numBytes > kChunkSize ? kChunkSize : numBytes;
177+ // The register address counts as one byte so limit nChunk to kChunkSize -1
178+ nChunk = numBytes > (kChunkSize -1 ) ? (kChunkSize -1 ) : numBytes;
184179
185- nReturned = _i2cPort->requestFrom ((int )addr, (int )nChunk, (int )true );
180+ nReturned = _i2cPort->requestFrom ((int )addr, (int )nChunk, (int )true ); // Always send a stop
186181
187182 // No data returned, no dice
188183 if (nReturned == 0 )
189184 return -1 ; // error
190185
186+ // Check we got back as much data as was requested
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,6 +196,9 @@ 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
202204 return 0 ; // Success
0 commit comments