void InitI2C();
void WaitSSP();
void SendStart();
void SendStop();
void SendRestart();
char SendByte(char);
char ReceiveByte();
void SendNack();
void SendAck();
char WriteByte(int,char);
char ReadByte(int);
//initialise the MSSP module
void InitI2C(){
TRISBbits.TRISB0=1;
TRISBbits.TRISB1=1;
SSPCON1=0b00101000;
SSPCON2=0;
SSPSTAT=0b10000000;
SSPADD=50; //20000/(4*100); //Fosc/(4*baud)
PIR1bits.SSPIF=0;
PIR2bits.BCLIF=0;
}
//Wait for the module to finish it's last action.
void WaitSSP(){
while(PIR1bits.SSPIF==0);
PIR1bits.SSPIF=0;
}
//send start bit
void SendStart(){
SSPCON2bits.SEN=1;
WaitSSP();
}
//Send stop bit.
void SendStop(){
SSPCON2bits.PEN=1;
WaitSSP();
}
//Send restart bit
void SendRestart(){
SSPCON2bits.RSEN=1;
WaitSSP();
}
//Send byte and return ack bit - 1=Ack 0=NAck
char SendByte(char Byte){
SSPBUF=Byte;
WaitSSP();
return(!SSPCON2bits.ACKSTAT);
}
//Get a byte from the slave
char ReceiveByte(){
SSPCON2bits.RCEN=1;
WaitSSP();
return(SSPBUF);
}
//Send a Not Acknowledge (NAck) to the slave
void SendNack(){
SSPCON2bits.ACKDT=1;
SSPCON2bits.ACKEN=1;
WaitSSP();
}
//Send an Acknowledge (Ack) to the slave
void SendAck(){
SSPCON2bits.ACKDT=0;
SSPCON2bits.ACKEN=1;
WaitSSP();
}
//Sends the start and device address.
//If the device is busy then it resends until accepted.
void SendID(char DeviceID){
SendStart();
if(SendByte(DeviceID)==1)
return;
do{
SendRestart();
}while(SendByte(DeviceID)==0);
}
//Write a byte to 24LC256
char WriteByte(int Address, char Byte){
SendID(0b10100000);
if(SendByte(Address>>8)==0)
return(0);
if(SendByte(Address&0xff)==0)
return(0);
if(SendByte(Byte)==0)
return(0);
SendStop();
return(1);
}
//Read a byte from a 24LC256
char ReadByte(int Address){
char Byte;
SendID(0b10100000);
if(SendByte(Address>>8)==0)
return(0);
if(SendByte(Address&0xff)==0)
return(0);
SendRestart();
if(SendByte(0b10100001)==0)
return(0);
Byte=ReceiveByte();
SendNack();
SendStop();
return(Byte);
}