Skip to content

Commit 36da2e4

Browse files
committed
prescaler is not calculated here https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/Wire/src/utility/twi.c#L139 which means we cannot get below 30.5mhz!
1 parent c421326 commit 36da2e4

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

Adafruit_I2CDevice.cpp

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,9 +259,37 @@ uint8_t Adafruit_I2CDevice::address(void) { return _addr; }
259259
* Not necessarily that the speed was achieved!
260260
*/
261261
bool Adafruit_I2CDevice::setSpeed(uint32_t desiredclk) {
262-
#if (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && !defined(TinyWireM_h)
262+
#if defined(__AVR__) // fix arduino core set clock
263+
// calculate TWBR correctly
264+
uint8_t prescaler = 1;
265+
uint32_t atwbr = ((F_CPU / desiredclk) - 16) / 2;
266+
if (atwbr <= 255) {
267+
prescaler = 1;
268+
TWSR = 0x0;
269+
} else if (atwbr <= 1020) {
270+
atwbr /= 4;
271+
prescaler = 4;
272+
TWSR = 0x1;
273+
} else if (atwbr <= 4080) {
274+
atwbr /= 16;
275+
prescaler = 16;
276+
TWSR = 0x2;
277+
} else if (atwbr <= 16320) {
278+
atwbr /= 64;
279+
prescaler = 64;
280+
TWSR = 0x3;
281+
}
282+
#ifdef DEBUG_SERIAL
283+
Serial.print(F("TWSR prescaler = ")); Serial.println(prescaler);
284+
Serial.print(F("TWBR = ")); Serial.println(atwbr);
285+
#endif
286+
TWBR = atwbr;
287+
return true;
288+
289+
#elif (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && !defined(TinyWireM_h)
263290
_wire->setClock(desiredclk);
264291
return true;
292+
265293
#else
266294
(void)desiredclk;
267295
return false;

0 commit comments

Comments
 (0)