How to Program I2C in PIC16F877A for Data Reception

The following code demonstrate, how to write a program to write and read data over I2C bus. The slave controller receive data from master controller and data is displayed on PORTD.  Both SCL and SDA lines are open drain drivers and each line must be pull-up with 10k resistor. I2C devices can only pull the line low, they cannot drive it high. When no device is pulling on the line, it will float high through the pull-up resistor. This is the reason, why pull-up resistors are important in I2C.
For I2C bus, clock options are between the following:
  • 100 Kbps in standard mode
  • 400 Kbps in fast mode
  • Up to 3.4 Mbps in high-speed mode
Data can be visualize on I2C bus monitor and signals transition can be seen on oscilloscope. The code is written in “mikroC PRO for PIC v.5.6.1” IDE and simulation is done with Proteus 8.0 SP0. At the end of code, you can find complete project files for download.

Code in mikroC

// set direction
sbit LED_Dir at TRISB.B0;
sbit SCL_Dir at TRISC.B3;
sbit SDA_Dir at TRISC.B4;
sbit LED at PORTB.B0;
void main(void)
{
unsigned short buffer = 0x00;
// set as output
LED_Dir = 0;
SCL_Dir = 0;
SDA_Dir = 0;
TRISD = 0x00;
// init value
PORTD = 0x00;
// initializes I2C with desired clock
// clock 100 kbps
I2C1_Init(100000);
Delay_ms(10);
while(1)
{
LED = ~LED;
// determines if I2C bus is free and issues START signal
I2C1_Start();
// receive byte
buffer = I2C1_Rd(0);
// issue I2C stop signal
I2C1_Stop();
// inc counter
PORTD = buffer;
Delay_ms(500);
}
}

Download Files

For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.

Comments

Popular posts from this blog

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program Interrupts in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)