Inter-Integrated Circuit (two wire interface TWI)
I²C (also referred as IIC or TWI ) pronounced as I square C is widely used communication protocal . If we wish to use multiple device with serially communicating device then I2C is the best way to communication between a microcprocessor and multiple device like motors , LCD , LED , EEPROM , etc . In this method we can control ( communicate ) up to 128 device which is almost impossible with conventional USART method . I2C bus consists of two lines called Serial Data Line (SDA) and Serial Clock Line (SCL) ,Communication between devices is master and slave based. Master generates clock signal, initiates and terminates data transfer. In many case microcontroller is master and it generate clock and address for multiple slave devices . From electrical point of view I2C devices use open drain (open collector) pins. In order to operate correctly SDA and SCL lines require pull up resistors. Typically 4.7kΩ resistors are used as shown in figure below .And The devices that we are using TWI must support TWI protocal .
I2C devices can work in four different modes:
- master transmit — master node is sending data to a slave
- master receive — master node is receiving data from a slave
- slave transmit — slave node is sending data to the master
- slave receive — slave node is receiving data from the master
There are different types of signals , some carry data some carry adress of each It is boring to explain a lot of things on internet without any funny demonstration so lets learn by example project related to I²C .
The code is somehow already explained by commenting the line how ever this code is not too hard to understand . There are four functions inside the code for initialization, start , write and read each function have their own defination you better read data sheet of ATmega32 or atmega16 (download link) page number 182. there is a lot of explanation of each registers and bits you need to set up for i2c programming PCF8574 IC this IC is used to expand input output pins if there is shortage of PINS in microcontroller you can download this from above link . In above example only write operation is done to you need to change circuit diagram as shown in figure below.
and the code for read from PCF8574 IO expander is below