Monday, 19 October 2015

PIC16F877A I2C [TWO WIRE COMMUNICATION] IN HALF DUPLEX MODE




//**********************************MASTER*********************//
#include<pic.h>
#include<htc.h>
#define _PIC16f877A_H
#define SCL TRISCbits.TRISC3
#define SDA TRISCbits.TRISC4
__CONFIG(PWRTE_ON& FOSC_HS &LVP_OFF& WDTE_OFF);
void delay(unsigned int i)
{
while(i--);
}
void main()
{
SSPCON=0X28;       //Enables the serial port and configures the SDA and SCL pins //I2C Master mode, clock = FOSC/(4 * (SSPADD + 1))
SSPADD=0X28;        //slave device address // baud rate selection //page no 99
while(1)
{
SEN=1;             //MASTER is in ideal mode
while(!SSPIF);
SSPIF=0;
while((SSPCON2&0X1F)||(SSPSTAT&0X04));    //Initiate Acknowledge sequence on //Enables Receive mode for I2C//Initiate Stop condition//Initiate Repeated Start condition//Initiate Start condition on SDA and SCL pins
SSPBUF=0X70;                                  //data register
while(!SSPIF);                                   //flag condition
SSPIF=0;
while((SSPCON2&0X1F)||(SSPSTAT&0X04));
SSPBUF=0X81;
while(!SSPIF);
SSPIF=0;
while((SSPCON2&0X1F)||(SSPSTAT&0X04));
PEN=1;                                     //Initiate Stop condition on SDA and SCL pins. Automatically cleared by hardware.
while(!SSPIF);
while((SSPCON2&0X1F)||(SSPSTAT&0X04));
}
}
//****************************************************************//





//***********************************SLAVE***********************//
#include<pic.h>
#include<htc.h>
#define _PIC16f877A_H
#define SCL TRISCbits.TRISC3
#define SDA TRISCbits.TRISC4
__CONFIG(PWRTE_ON& FOSC_HS &LVP_OFF& WDTE_OFF);
void delay(unsigned int i)
{
while(i--);
}
void main()
{
TRISD=TRISB=0X00;    //making output port
SSPADD=0X70;      //slave address
SDA=SCL=1;          //input pin
SSPCON=0X36;        //Enables the serial port and configures the SDA and SCL pins  //Release clock  //I2C Slave mode, 7-bit address
SSPCON2=0X00;
//SSPSTAT=0xC0;
while(1)
{while(!SSPIF);
SSPIF=0;
while((SSPCON2&0X1F)||(SSPSTAT&0X04));
PORTB=SSPBUF;
while(!SSPIF);
PORTD=SSPBUF;
while((SSPCON2&0X1F)||(SSPSTAT&0X04));
SSPIF=0;
}
}
//*****************************************************************//

No comments:

Post a Comment