My I2C Master (PIC24F) to request a byte from a PIC slave ... Now you will see immediately c my 'C' is that of a 4 year old... but it seems to work..
void I2C_req_from_PB()
{
I2C_start_W(LCD_BP_addr); // start with W bit
I2C_sendB(0xF7); // command
I2C_sendB(0x99); // command this sets up a response condition slave waits for read request
// more commands here
I2C_endtx(); // send stop
I2C_start_R(LCD_BP_addr); send start R
I2C1CONbits.RCEN = 1; // turn on RX
while (!I2C1STATbits.RBF); wait for RBF
inkey = I2C1RCV; // save RX
I2CNak(); // send Nak
I2C_endtx(); // end
I2C1CONbits.RCEN = 0; // probably not needed
}
void I2C_start_W(char device_addr)
{
I2C1CONbits.SEN = 1; // Set start bit
Nop();
while(I2C1CONbits.SEN){} //
Nop();
I2C1TRN = (device_addr << 1) & 0xFE; // send (slave + write bit )
Nop();
while (I2C1STATbits.TRSTAT) {} //
I2Cackstat();
}
void I2C_start_R(char device_addr)
{
I2C1CONbits.SEN = 1; // Set start bit
Nop();
while(I2C1CONbits.SEN){} //
Nop();
I2C1TRN = ((device_addr << 1 ) & 0xFE) | 0x01; // send (slave + read bit )
Nop();
while (I2C1STATbits.TRSTAT) {} //
I2Cackstat();
}
void I2C_restart_R(char device_addr)
{
I2C1CONbits.RSEN = 1; // Set start bit
Nop();
while(I2C1CONbits.RSEN) {}
Nop();
I2C1TRN = ((device_addr << 1 ) & 0xFE) | 0x01; // send (slave + READ bit )
Nop();
while (I2C1STATbits.TRSTAT) {} //
I2Cackstat();
}
void I2C_sendB(char data)
{
I2C1TRN = data; // send control
while (I2C1STATbits.TRSTAT) {} //
I2Cackstat();
}
void I2C_sendS(char sdata[], char count)
{
int x = 0;
for ( x = 0; x < count; x++)
{
I2C1TRN = sdata
Nop();
while (I2C1STATbits.TRSTAT) {} //
I2Cackstat();
//DLY10u();
}
}
void I2C_endtx()
{
I2C1CONbits.PEN = 1; // Set stop bit
Nop();
while(I2C1CONbits.PEN){}
DLY10u();
}
void I2Cackstat()
{
if( I2C1STATbits.ACKSTAT )
{
I2C1CONbits.PEN = 1; // Set stop bit
LATAbits.LATA0 = 1; // ERR led on
}
DLY10u();
}
void I2CInit() // for a PIC24FV16KM302 ?
{
I2C1MSK = 0; // set this controller's device address
I2C1CONbits.I2CEN = 1; // enable I2C module
I2C1CONbits.A10M = 0; // I2C1ADD is a 7-bit slave address
I2C1CONbits.DISSLW = 1; // Disable slew - 0 for 400 kHz up enable slew rate
I2C1CONbits.SMEN = 0; // No signal conditioning
I2C1CONbits.GCEN = 0; // general call for slave mode only
I2C1BRG = (8000 / (2 * 100)) - 1 ; //
}