/* *************SOURCE FILE******************** File saved as i2c.c Compiler: XC8 v1.38 CCI compliant? Yes Software function Provides an I2C MASTER port functionality Written by Mainly Microchip C18 code adapted by Russell E. Tribe Date 26/9/16 For (PIC type) Various but developed on PIC16F1459 Other information SDA on pin 13 (RB4) SCL on pin 11 (RB6) */ /** I N C L U D E S ***********************************************/ #include //Provides PIC header file and is required for CCI compliance #include "i2c.h" //Provides header data for these functions /** FUNCTIONS *****************************************************/ void OpenI2C (unsigned char sync_mode, unsigned char slew) { SSP1STAT &= 0x3F; //Power on state SSP1CON1 = 0x00; //Power on state SSP1CON2 = 0x00; //Power on state SSP1CON1 |= sync_mode; //Select required I2C mode SSP1STAT |= slew; //Select slew rate control on/off I2C_SCL = 1; //TRIS to input I2C_SDA = 1; //TRIS to input SSP1CON1 |= SSPENB; //Enable synchronous serial port IdleI2C (); //Wait until I2C bus is in idle mode } //**************************************** void CloseI2C (void) { IdleI2C (); //Wait until I2C bus is in idle mode SSP1CON1 &= 0xDF; //Disable synchronous serial port } //**************************************** void StartI2C (void) { SSP1CON2bits.SEN = 1; //Initiate bus start condition } //**************************************** void RestartI2C (void) { SSP1CON2bits.RSEN = 1; //Initiate bus restart condition IdleI2C (); //Wait until I2C bus is in idle mode } //**************************************** void StopI2C (void) { SSP1CON2bits.PEN = 1; //Initiate bus stop condition IdleI2C (); //Wait until I2C bus is in idle mode } //**************************************** //This is my function - written as a self-contained function for MASTER mode only void masterSendI2C (unsigned char data_out) { unsigned char temp; do { do { temp = SSP1BUF; //Read and discard to clear the BF flag SSP1CON1bits.WCOL=0; //Clear the bus collision status bit (if set)) SSP1BUF = data_out; //Send the data byte } while (SSP1CON1bits.WCOL); //Repeat if a write collision occurred while(SSP1STATbits.BF); //Wait until write cycle is complete IdleI2C(); //Ensure module is idle } while (SSP1CON2bits.ACKSTAT); //Repeat until ACK received } //**************************************** //Wait here until I2C bus is in idle mode void IdleI2C (void) { while ((SSP1CON2 & 0x1F) || (SSP1STATbits.R_nW)) continue; } //****************************************