@@ -116,6 +116,13 @@ class Twi
116
116
{
117
117
return (GPI & (1 << twi_scl)) != 0 ;
118
118
}
119
+ // Handle the case where a slave needs to stretch the clock with a time-limited busy wait
120
+ inline void WAIT_CLOCK_STRETCH ()
121
+ {
122
+ for (unsigned int t = 0 ; !SCL_READ () && (t < twi_clockStretchLimit); t++) {
123
+ /* noop */
124
+ }
125
+ }
119
126
120
127
public:
121
128
void setClock (unsigned int freq);
@@ -145,6 +152,7 @@ static Twi twi;
145
152
#define TWI_CLOCK_STRETCH_MULTIPLIER 6
146
153
#endif
147
154
155
+
148
156
void Twi::setClock (unsigned int freq)
149
157
{
150
158
preferred_si2c_clock = freq;
@@ -272,12 +280,11 @@ bool Twi::write_start(void)
272
280
273
281
bool Twi::write_stop (void )
274
282
{
275
- uint32_t i = 0 ;
276
283
SCL_LOW ();
277
284
SDA_LOW ();
278
285
busywait (twi_dcount);
279
286
SCL_HIGH ();
280
- while (! SCL_READ () && (i++) < twi_clockStretchLimit); // Clock stretching
287
+ WAIT_CLOCK_STRETCH ();
281
288
busywait (twi_dcount);
282
289
SDA_HIGH ();
283
290
busywait (twi_dcount);
@@ -286,7 +293,6 @@ bool Twi::write_stop(void)
286
293
287
294
bool Twi::write_bit (bool bit)
288
295
{
289
- uint32_t i = 0 ;
290
296
SCL_LOW ();
291
297
if (bit)
292
298
{
@@ -298,19 +304,18 @@ bool Twi::write_bit(bool bit)
298
304
}
299
305
busywait (twi_dcount + 1 );
300
306
SCL_HIGH ();
301
- while (! SCL_READ () && (i++) < twi_clockStretchLimit); // Clock stretching
307
+ WAIT_CLOCK_STRETCH ();
302
308
busywait (twi_dcount);
303
309
return true ;
304
310
}
305
311
306
312
bool Twi::read_bit (void )
307
313
{
308
- uint32_t i = 0 ;
309
314
SCL_LOW ();
310
315
SDA_HIGH ();
311
316
busywait (twi_dcount + 2 );
312
317
SCL_HIGH ();
313
- while (! SCL_READ () && (i++) < twi_clockStretchLimit); // Clock stretching
318
+ WAIT_CLOCK_STRETCH ();
314
319
bool bit = SDA_READ ();
315
320
busywait (twi_dcount);
316
321
return bit;
@@ -375,7 +380,7 @@ unsigned char Twi::writeTo(unsigned char address, unsigned char * buf, unsigned
375
380
SCL_LOW ();
376
381
busywait (twi_dcount);
377
382
SCL_HIGH ();
378
- unsigned int t = 0 ; while (! SCL_READ () && (t++) < twi_clockStretchLimit); // twi_clockStretchLimit
383
+ WAIT_CLOCK_STRETCH ();
379
384
busywait (twi_dcount);
380
385
}
381
386
return 0 ;
@@ -411,7 +416,7 @@ unsigned char Twi::readFrom(unsigned char address, unsigned char* buf, unsigned
411
416
SCL_LOW ();
412
417
busywait (twi_dcount);
413
418
SCL_HIGH ();
414
- unsigned int t = 0 ; while (! SCL_READ () && (t++) < twi_clockStretchLimit); // twi_clockStretchLimit
419
+ WAIT_CLOCK_STRETCH ();
415
420
busywait (twi_dcount);
416
421
}
417
422
return 0 ;
0 commit comments