How to Program I2C in PIC16F877A for Data Transmission
The I2C stands for Inter-Integrated Circuit, It is a serial interface that requires only two bus lines for bi-directional data transfer. The two bus lines details are the following.
SDA line: Any data sent from one device to another goes through the SDA line.
SCL line: It provides the necessary synchronization clock for the data transfer.
SCL line: It provides the necessary synchronization clock for the data transfer.
Data is sent in either direction on SDA line by the master or slave. Only a master can start a data transfer and slaves respond to the master. It is possible to have multiple masters on a common bus, but only one could be active at a time. The SCL clock line is always driven by the master.
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 between the following:
- 100 Kbps in standard mode
- 400 Kbps in fast mode
- Up to 3.4 Mbps in high-speed mode
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;
// 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();
// send byte
I2C1_Wr(buffer);
// issue I2C stop signal
I2C1_Stop();
// inc counter
buffer++;
Delay_ms(500);
}
}
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;
// 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();
// send byte
I2C1_Wr(buffer);
// issue I2C stop signal
I2C1_Stop();
// inc counter
buffer++;
Delay_ms(500);
}
}
Download Files
For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.
Comments
Post a Comment