You are on page 1of 3

I2C_Driver

/**********************************
* Header File for I2C Operations *
* P1.0 and P1.1 must be provided *
* with 10K pull-up resistors *
**********************************/

#define SDA P1.0
#define SCL P1.1

#define Acknowledge 1
#define NotAcknowledge 0

/******************************
Initialise I2C Port for Master
******************************/
void Init_I2C_Master(void){
unsigned char DelCntr;
P1 |= 0b11000000;
for (DelCntr = 0; DelCntr < 5; DelCntr++);
}

/*******************
I2C Start Procedure
*******************/
void I2C_Start(void){
unsigned char DelCntr;
SDA = 0;
for (DelCntr = 0; DelCntr < 3; DelCntr++);
SCL = 0;
for (DelCntr = 0; DelCntr < 3; DelCntr++);
}

/******************
I2C Stop Procedure
******************/
void I2C_Stop(void){
unsigned char DelCntr;
SCL = 1;
for (DelCntr = 0; DelCntr < 3; DelCntr++);
SDA = 1;
for (DelCntr = 0; DelCntr < 3; DelCntr++);
}

/********************
Generate Clock Pulse
********************/
void I2C_ClockPulse(void){
SCL = 0;
SCL = 1;
asm{NOP;}
SCL = 0;
;

/************************
I2C Data Write Procedure
************************/
bit I2C_Wr(unsigned char I2C_Data){
unsigned char BitCntr;
bit AcknowledgeFlag;
for (BitCntr = 0; BitCntr < 8; BitCntr++){
if (BitCntr){
I2C_Data = I2C_Data << 1;
}
Page 1

PortAddr |= 0x01. } /****************** Port (PCF8574) Read *******************/ unsigned char I2C_PortRead(unsigned char PortAddr){ unsigned char PortData. I2C_Driver if (I2C_Data & 0x80){ SDA = 1. } SCL = 1. if (SDA){ Buffer = (Buffer | 0x01) << 1. unsigned char PortData){ PortAddr &= 0xFE. // Start 9th clock pulse if (SDA){ AcknowledgeFlag = 0. // End of 9th clock pulse return AcknowledgeFlag. } SCL = 0. // Slave did respond } SCL = 0. // Convert addr to read address I2C_Start(). // Do not send acknowledge to the slave } SCL = 0. BitCntr++){ SCL = 1. } SCL = 1. if (I2C_Wr(PortAddr)){ I2C_Wr(PortData). // Slave did not respond } else{ AcknowledgeFlag = 1. } else{ Buffer = Buffer << 1. // Send acknowledge to the slave } else{ SDA = 1. } I2C_ClockPulse(). unsigned char Buffer = 0. BitCntr < 8. Page 2 . for (BitCntr = 0. // Convert addr to write address I2C_Start(). // End of the 9th clock pulse return Buffer. } /*********************** I2C Data Read Procedure ***********************/ unsigned char I2C_Rd(bit AckCntrl){ unsigned char BitCntr. } else{ SDA = 0. } /******************** Port (PCF8574) Write ********************/ void I2C_PortWrite(unsigned char PortAddr. // Port did respond } I2C_Stop(). // Start of the 9th clock pulse if (AckCntrl){ SDA = 0.

I2C_Driver if (I2C_Wr(PortAddr)){ PortData = I2C_Rd(NotAcknowlege). // Slave did not respond } I2C_Stop(). } Page 3 . return PortData. } else{ PortData = 0x00.