0

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);
 delay(10);

While this one doubles it to 31.25 kHz:

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

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

asked Apr 18, 2017 at 11:44
3
  • 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; Commented Apr 18, 2017 at 12:02
  • @MikaelPatel That was it! You may want to turn that into an answer as well, thanks. Commented Apr 18, 2017 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. Commented Apr 18, 2017 at 13:46

1 Answer 1

3

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;

or:

Wire.setClock(F_TWI);

Cheers!

answered Apr 18, 2017 at 12:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.