Skip to content

Commit 8c7a20a

Browse files
committed
Merge branch 'master' of github.com:adafruit/Adafruit_BusIO
2 parents 399aeea + 23ac286 commit 8c7a20a

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

Adafruit_I2CDevice.cpp

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

0 commit comments

Comments
 (0)