Search code examples
ci2c8051

How does I2C Protocol work


I have visited on some links and looked for some example programs for I2C programming. I want to write my own code for I2C protocol. Suppose DS1307 RTC and LCD connected to 8051. I am using Keil software to write a C program. It's very difficult to write whole program of I2C for me, so I tried to break program in small parts:

  • Module 1: define and set pins for LCD and DS1307 RTC
  • Module 2: write C code for DS1307 (make functions for DS1307 such as read, write)
  • Module 3: write C code for LCD (data, command initialize, etc)
  • Module 4: main function

I understand module 1 but I am looking help to understand module 2. So again I want break module 2 in small parts.

How to break module 2 in small parts for easy understanding? How many functions should be in module2?


Solution

  • The Module 2 is essentially I2C driver using bit banging of 8051 port. I2C protocol follows a sequence. It is started by start sequence and stopped by stop sequence. You can have different functions. The communication is started by the master and each slave has an address. So in module2, you will write all below functions.

    For example, the I2 read sequence will be following

    I2C_Start();  // set I2C start sequence
    I2C_Send(slave_address|1); Send I2C slave address in read mode
    I2C_read_ACK(); //master will know slave got data 
    while(number_of bytes){
    I2C_Read();
    I2C_send_ACK();
    number_of bytes--;
    }
    I2C_NAK();    //slave need to know so it will not prepare next data.
    I2C_Stop();   //stop communication
    

    Again the write on slave will have below steps

    I2C_Start();  // set I2C start sequence
    I2C_Send(slave_address); Send I2C slave address in write mode
    I2C_read_ACK(); //master will know slave got data 
    while(number_of bytes){
    I2C_Write();
    I2C_read_ACK(); //master will know slave got data 
    number_of bytes--;
    }
    I2C_Stop(); //stop communication
    

    I also see driver at https://circuitdigest.com/microcontroller-projects/digital-clock-using-8051-microcontroller

    Official I2C protocol is here

    https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwici4Ocn6jVAhUIwlQKHV_zAJ8QFggoMAA&url=https%3A%2F%2Fwww.nxp.com%2Fdocuments%2Fuser_manual%2FUM10204.pdf&usg=AFQjCNHgNi6wOD4MjIDsnT0DXTYLS_-gPQ