Using an Atmega168P - programmed by means of avrdude with the .hex file generated by Arduino IDE.

The following code sets the 8 MHz Atmega's TWI interface to just 15.625 kHz:

  Wire.begin(); // Initiate the Wire library
  Wire.setClock(100* 1000);

While this one doubles it to 31.25 kHz:

  Wire.begin(); // Initiate the Wire library
  TWBR = (F_CPU/(100*1000) - 16)/2;
  TWSR &= 0b11111100;

Looking to get 100 kHz clock. What am I missing ?

  • Calculations are int (16-bits) by default. Try 100*1000L. Or better define F_TWI as 100000L and use TWBR = ((F_CPU/F_TWI)-16)/2; – Mikael Patel Apr 18 '17 at 12:02
  • @MikaelPatel That was it! You may want to turn that into an answer as well, thanks. – kellogs Apr 18 '17 at 12:10
  • You get 100kHz with just Wire.begin(), because that is the default. The Wire.setClock has limits (I don't know the limits) but 50kHz to 200kHz should work: Wire.setClock(50000L) to Wire.setClock(200000L). I hope you are not trying to compile 16MHz code for a 8MHz ATmega chip. If there is no 8MHz ATmega168P in the menu, you should create an entry in boards.txt. – Jot Apr 18 '17 at 13:46

Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100*1000L. Or even better:

#define F_TWI 100000L 

and use:

TWBR = ((F_CPU/F_TWI)-16)/2;




| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.