Electronic – ATMEGA TWI / I2C Slave – How to implement clock stretching

atmegacommunicationdriveri2ctwi

I am programming a TWI slave based on an ATMEGA644PV.

It is working in general, the master can send and read data from the slave. So far so good.
But on some read-requests, the slave requires "more time" to prepare the data. I would like to utilize clock stretching to make the master wait until the data is ready.

The ATMEGA datasheet points out:

The Slave can extend the SCL low period by pulling the SCL line low. This is useful if the clock speed set up by the Master is too fast for the Slave, or the Slave needs extra time for processing between the data transmissions.

This is exactly what I want, but I don't get how to implement this on the driver level. I see no way to indicate to the I2C slave hardware that it shouldn't immediately ACK, but instead pull the SCL for a period of my choice.

From what I get, I can only tell the slave to ACK or – well – not to ACK at all after being addressed or a data byte being transferred.

Am I missing something obvious here? This is the first time I look at I2C from the view of a slave.

Best Answer

The Atmel Atmega processors (including the Atmega644) automatically perform clock stretching whenever the I2C interface needs an action performed by the software.

This action could be when a slave has received a byte of data and the data needs to be removed from the data register before the next byte can be received or when data is needed to transmit. It happens whenever the TWINT flag is set.

The data sheet does not highlight the fact much but it is mentioned in a few places (such as in section 19.5.5 on page 207 on the 02/12 datasheet).

Related Topic