File tree Expand file tree Collapse file tree 1 file changed +19
-9
lines changed Expand file tree Collapse file tree 1 file changed +19
-9
lines changed Original file line number Diff line number Diff line change @@ -264,33 +264,43 @@ bool Adafruit_I2CDevice::setSpeed(uint32_t desiredclk) {
264
264
#if defined(__AVR_ATmega328__) || \
265
265
defined (__AVR_ATmega328P__) // fix arduino core set clock
266
266
// calculate TWBR correctly
267
- uint8_t prescaler = 1 ;
267
+
268
+ if ((F_CPU / 18 ) < desiredclk) {
269
+ #ifdef DEBUG_SERIAL
270
+ Serial.println (F (" I2C.setSpeed too high." ));
271
+ #endif
272
+ return false ;
273
+ }
268
274
uint32_t atwbr = ((F_CPU / desiredclk) - 16 ) / 2 ;
275
+ if (atwbr > 16320 ) {
276
+ #ifdef DEBUG_SERIAL
277
+ Serial.println (F (" I2C.setSpeed too low." ));
278
+ #endif
279
+ return false ;
280
+ }
281
+
269
282
if (atwbr <= 255 ) {
270
- prescaler = 1 ;
283
+ atwbr / = 1 ;
271
284
TWSR = 0x0 ;
272
285
} else if (atwbr <= 1020 ) {
273
286
atwbr /= 4 ;
274
- prescaler = 4 ;
275
287
TWSR = 0x1 ;
276
288
} else if (atwbr <= 4080 ) {
277
289
atwbr /= 16 ;
278
- prescaler = 16 ;
279
290
TWSR = 0x2 ;
280
- } else if (atwbr <= 16320 ) {
291
+ } else { // if (atwbr <= 16320)
281
292
atwbr /= 64 ;
282
- prescaler = 64 ;
283
293
TWSR = 0x3 ;
284
294
}
295
+ TWBR = atwbr;
296
+
285
297
#ifdef DEBUG_SERIAL
286
298
Serial.print (F (" TWSR prescaler = " ));
287
- Serial.println (prescaler );
299
+ Serial.println (pow ( 4 , TWSR) );
288
300
Serial.print (F (" TWBR = " ));
289
301
Serial.println (atwbr);
290
302
#endif
291
- TWBR = atwbr;
292
303
return true ;
293
-
294
304
#elif (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && \
295
305
!defined (TinyWireM_h)
296
306
_wire->setClock (desiredclk);
You can’t perform that action at this time.
0 commit comments