This may be a very borderline Stack Overflow question, but I decided to post here because I'm dealing with the I2C protocol for a PIC MCU in XC8.
I'm learning how to talk with devices over I2C and it's going quite well, but I'm not sure of the best way to deal with a hung state from a not-acknowledge from a slave. The problem comes from the while() loops and the program not progressing until they're met (or not true - you know what I mean). My first method was with a watch dog reset, but I didn't like re-initializing everything any time something goes wrong.
I've consolidated all the writing of the registers to a function:
void I2Cwrite(unsigned char SLAVE, unsigned char REG, unsigned char DATA)
{
SSPCON2bits.SEN = 1; // RESET
while(SSPCON2bits.SEN == 1);
SSPBUF = SLAVE;
PIR1bits.SSPIF = 0;
while(PIR1bits.SSPIF == 0);
while(SSPCON2bits.ACKSTAT == 1);
SSPBUF = REG;
PIR1bits.SSPIF = 0;
while(PIR1bits.SSPIF == 0);
while(SSPCON2bits.ACKSTAT == 1);
SSPBUF = DATA;
PIR1bits.SSPIF = 0;
while(PIR1bits.SSPIF == 0);
while(SSPCON2bits.ACKSTAT == 1);
PIR1bits.SSPIF = 0;
SSPCON2bits.PEN = 1;
while(PIR1bits.SSPIF == 0);
}
Then all I have to do is write my data to a function like this:
I2Cwrite(DRVwrite, 0x01, 0x07);
I2Cwrite(DRVwrite, 0x1A, 0b11011110);
I2Cwrite(DRVwrite, 0x16, 0b01010110);
I2Cwrite(DRVwrite, 0x17, 0b01011110);
I2Cwrite(DRVwrite, 0x1E, 0b00110000);
I2Cwrite(DRVwrite, 0x1B, 0b10011100);
If I fall into a hung state mid write, what is a good way to jump to the start of that particular I2C write function and try again?