Im was writing some short Code for I2C with my Mega2560 when I discovered some discrepancies.
The twi.c from Arduino IDE says
SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
but the datasheet for the mega2560 says
SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR * 4^TWPS))
// code from twi.c
// initialize twi prescaler and bit rate
cbi(TWSR, TWPS0);
cbi(TWSR, TWPS1);
TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;
/* twi bit rate formula from atmega128 manual pg 204
SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
note: TWBR should be 10 or higher for master mode
It is 72 for a 16mhz Wiring board with 100kHz TWI */
The fact, that TWPS cannot be set to Zero (min. 1) would result in much slower TWI Frequencies.
Is that already a well known Problem or am I the first?
The fact, that TWPS cannot be set to Zero (min. 1) would result in much slower TWI Frequencies.
Where does it say it can't be zero? It can be zero. This clears the prescaler bits, so in fact the prescaler value is zero. Any number to the zero power equals one.
// initialize twi prescaler and bit rate
cbi(TWSR, TWPS0);
cbi(TWSR, TWPS1);
So if TWPS = 0, then (4^0) = 1.
SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR * 1)) = CPU Clock Frequency / (16 + (2 * TWBR))
When both Bits are cleared, the prescaler value equals 1. The other options for the prescaler are 4, 16 and 64.
DonVido:
When both Bits are cleared, the prescaler value equals 1. The other options for the prescaler are 4, 16 and 64.
That is correct and not correct. The TWPS (not the prescaler value) is the value of bits 0 and 1 of the TWSR. The values given in that chart you are reading have the prescaler values computed for you.
When bit 0 = 0 and bit 1 = 0, TWPS = 0. So 4^0 = 1.
When bit 0 = 1 and bit 1 = 0, TWPS = 1. So 4^1 = 4.
When bit 0 = 0 and bit 1 = 1, TWPS = 2. So 4^2 = 16.
When bit 0 = 1 and bit 1 = 1, TWPS = 3. So 4^3 = 64.
edit: My apology for the initial maths. I was in a hurry. The powers computation is now correct.
Thanks a lot. That was in fact confusing. Shame on me.
No shame in that. It is a bit confusing. I had a problem in algebra remembering x^0 = 1.