Saturday, October 16, 2021

How the I2C and TWI (Two Wire Interface) protocol works

I2C is a two-wire serial bus communication protocol invented by Phillips in 1982. TWI stands for Two Wire Interface and, for the most part, this bus is identical to I²C. The name TWI was introduced by Atmel and other companies to avoid conflicts with trademark issues related to I²C. Because these two protocols are almost the same I will refer to them interchangeably throughout the course of this article.

This protocol is very used nowadays by all sorts of devices such as DACs, LCDs, sensors, etc. so it's worth learning about it.

As a disclaimer I need to mention that most parts of this article contains fragments from the ATmega328, 324 datasheet and MCP4706 datasheet. I liked how they explained the I2C, TWI protocol  and since not many people read the datasheets I want to share this information with anyone interested in the TWI protocol.

If you're interested in a I2C, TWI library it can be found at this link I2C, TWI library.

Features

  • 7-bit Address Space Allows up to 128 Different Slave Addresses
  • Multi-master Arbitration Support
  • General call addressing

The I2C interface specifies different communication bit rates. These are referred to as Standard, Fast or HighSpeed modes.

  • Standard mode: bit rates up to 100 kbit/s
  • Fast mode: bit rates up to 400 kbit/s
  • High-Speed mode (HS mode): bit rates up to 3.4 Mbit/s

High-Speed mode is currently unsupported by the TWI.

Table of Contents

 

Two-Wire Serial Interface Bus

The TWI protocol is able to interconnect up to 128 different devices using only two bidirectional bus lines: one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the TWI protocol.

TWI Bus Interconnection
TWI Bus Interconnection

The number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400pF and the 7-bit slave address space. The SCL and SDA pins are open-drain configurations. For this reason these pins require a pull-up resistor.

The pull-up resistor values (R1 and R2) for SCL and SDA pins depend on the operating speed (standard, fast, and high speed) and loading capacitance of the I2C bus line. A higher value of the pull-up resistor consumes less power, but increases the signal transition time (higher RC time constant) on the bus line. Therefore, it can limit the bus operating speed. The lower resistor value, on the other hand, consumes higher power, but allows higher operating speed. If the bus line has higher capacitance due to long metal traces or multiple device connections to the bus line, a smaller pull-up resistor is needed to compensate the long RC time constant. The pull-up resistor is typically chosen between 1 kΩ and 10 kΩ ranges for Standard and Fast modes, and less than 1 kΩ for High-Speed mode.

TWI Terminology

Master - The device that initiates and terminates a transmission. The Master also generates the SCL clock.

Slave - The device addressed by a Master.

Transmitter - The device placing data on the bus.

Receiver - The device reading data from the bus.

Side note: I'm note a big fan of the Master and Slave terminology but since this is the naming convention I will roll with it. Maybe they should be called Host and Client?

 

Data Transfer and Frame Format

START and STOP Conditions

The Master initiates and terminates a data transmission. The transmission is initiated when the Master issues a START condition on the bus, and it is terminated when the Master issues a STOP condition.

Between a START and a STOP condition, the bus is considered busy, and no other master should try to seize control of the bus. A special case occurs when a new START condition is issued between a START and STOP condition. This is referred to as a REPEATED START condition, and is used when the Master wishes to initiate a new transfer without relinquishing control of the bus. After a REPEATED START, the bus is considered busy until the next STOP.

I2C, TWI - START, REPEATED START, and STOP conditions
START, REPEATED START, and STOP conditions

Start Bit

The Start bit indicates the beginning of a data transfer sequence. The Start bit is defined as the SDA signal falling when the SCL signal is “High”.

I2C, TWI - Start Bit
Start Bit

Stop Bit

The Stop bit indicates the end of the I2C Data Transfer Sequence. The Stop bit is defined as the SDA signal rising when the SCL signal is “High”.

I2C, TWI - Stop Bit


Address Packet Format

All address packets transmitted on the TWI bus are nine bits long, consisting of seven address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed. When a Slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle. If the addressed Slave is busy, or for some other reason can not service the Master’s request, the SDA line should be left high in the ACK clock cycle. The Master can then transmit a STOP condition, or a REPEATED START condition to initiate a new transmission. An address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or SLA+W, respectively.

The MSB of the address byte is transmitted first. Slave addresses can freely be allocated by the designer, but the address '0000 000' is reserved for a general call.

I2C, TWI - Address Packet Format
Address Packet Format

Data Packet Format

All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the Master generates the clock and the START and STOP conditions, while the Receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signaled by the Receiver pulling the SDA line low during the ninth SCL cycle. If the Receiver leaves the SDA line high, a NACK is signaled. When the Receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the Transmitter by sending a NACK after the final byte. The MSB of the data byte is transmitted first.

Data Bit

The SDA signal may change state while the SCL signal is Low. While the SCL signal is High, the SDA signal MUST be stable.

I2C, TWI - Data bit
Data Bit

Combining Address and Data Packets into a Transmission

A transmission consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition. An empty message, consisting of a START followed by a STOP condition, is illegal.

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. The Slave extending the SCL low period is refereed to as Clock Stretching.

The following figure depicts a typical data transmission. Note that several data bytes can be transmitted between the SLA+R/W and the STOP condition, depending on the software protocol implemented by the application software.

I2C, TWI - Typical Data Transmission
Typical Data Transmission

Acknowledge (ACK) Bit

The ACK bit is typically a response from the receiving device to the transmitting device. Depending on the context of the transfer sequence, the ACK bit may indicate different things. Typically, the slave device will supply an ACK response after the Start bit and 8 “data” bits have been received. An ACK bit has the SDA signal low.

I2C, TWI - Acknowledge (ACK) Bit
Acknowledge (ACK) Bit

Not ACK (NACK) Response

The NACK bit has the SDA signal high. When this error condition occurs, then a Start bit must be issued to reset the command state machine.

Multi-master Bus Systems, Arbitration, and Synchronization

The TWI protocol allows bus systems with several masters. Special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more masters initiate a transmission at the same time. Two problems arise in multi-master systems:

  • Different masters may use different SCL frequencies. A scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. This will facilitate the arbitration process.
  • An algorithm must be implemented allowing only one of the masters to complete the transmission. All other masters should cease transmission when they discover that they have lost the selection process. This selection process is called arbitration. When a contending master discovers that it has lost the arbitration process, it should immediately switch to Slave mode to check whether it is being addressed by the winning master. The fact that multiple masters have started transmission at the same time should not be detectable to the slaves, i.e. the data being transferred on the bus must not be corrupted.

SCL Synchronization Between Multiple Masters

The wired-ANDing of the bus lines is used to solve both these problems. The serial clocks from all masters will be wired-ANDed, yielding a combined clock with a high period equal to the one from the Master with the shortest high period. The low period of the combined clock is equal to the low period of the Master with the longest low period. Note that all masters listen to the SCL line, effectively starting to count their SCL high and low time-out periods when the combined SCL line goes high or low, respectively.

I2C, TWI - SCL Synchronization Between Multiple Masters
SCL Synchronization Between Multiple Masters

In the above case scenario the Master A has a faster clock frequency than Master B so when Master A tries to pull the SCL line high the SCL Bus Line remains low because of the Master B.

Arbitration Between Two Masters

Arbitration is carried out by all masters continuously monitoring the SDA line after outputting data. If the value read from the SDA line does not match the value the Master had output, it has lost the arbitration. Note that a Master can only lose arbitration when it outputs a high SDA value while another Master outputs a low value. The losing Master should immediately go to Slave mode, checking if it is being addressed by the winning Master. The SDA line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. Arbitration will continue until only one Master remains, and this may take many bits. If several masters are trying to address the same Slave, arbitration will continue into the data packet.

I2C, TWI - Arbitration Between Two Masters
Arbitration Between Two Masters

In the above case scenario Master A loses arbitration because when it outputs a high bit on the SDA line, Master B outputs a low bit so the line cannot remain in a high state.

Note that arbitration is not allowed between:

  • A REPEATED START condition and a data bit
  • A STOP condition and a data bit
  • A REPEATED START and a STOP condition

It is the user software’s responsibility to ensure that these illegal arbitration conditions never occur. This implies that in multi-master systems, all data transfers must use the same composition of SLA+R/W and data packets. In other words; All transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined.

Transmission Modes 

The TWI can operate in one of four major modes:

  • Master Transmitter (MT)
  • Master Receiver (MR)
  • Slave Transmitter (ST)
  • Slave Receiver (SR)

 

Practical I2C example 1: Writing data to MCP4706 DAC device

In this example an AVR microcontroller is using I2C to interface with the MCP4706 DAC IC. This mode is called Master Transmitter mode.

Practical I2C example 1: Writing data to MCP4706 DAC device

The microcontroller starts the transmission by issuing a Start command and then sending the 7-bit Slave address 0b1100001 followed by R/W bit. Because this is a Write command this bit is set to 0. A 1 here would mean a Read command. The A bit is the 9-th bit and is generated by the DAC (Slave device). If this bit is 0 means ACK so the DAC received and understood the command. A 1 means a NACK response and indicates that something went wrong. The microcontroller can then issue another Start command to try again.

This first packet after the Start bit is called the Address packet or SLA+R (Slave Address + Read). After that there are two bytes. First bytes is formed by 2 Command bits + 2 Power Down bits + 4 Data bits = 8 bits total. The 9th bit is again the A bit (ACK from the DAC). The second byte is then transmitted and is represented by bits b07 to b00. This is the DAC value. After the DAC sets the ACK bit, the microcontroller sends a Stop command and the transmission ends.

Practical I2C example 2: Reading data from MCP4706 DAC device

Now the microcontroller is set to read data from the DAC. This is the Master Receiver mode.

Practical I2C example 2: Reading data from MCP4706 DAC device

The first packet after the Start bit is the same as with the Write command except the R/W bit which in a Read command must be 1 instead of 0. After the DAC sets the A bit if it is an ACK bit, then the DAC starts to send back data.

The first byte is formed by Vol Status bits a 0 bit and 5 Vol Configuration bits. The significance of the bytes is irelevant for this example. This time the A bit is set by the microcontroller instead of the DAC like before because the MCU is receiving the data so it must acknowledge the reception. After all bytes have been received the microcontroller (Master device) must send the Stop command to terminate the transmission otherwise the DAC will keep repeating the bytes.

I believe that's it folks.

1 comment: