#include <pic.h>
#include "delay.h"
#include "lcd.h"

#define SCL RC3
#define SDA RC4

//Macros for I2C - //SDA (RC4) and SCL(RC3)
#define SDA_LOW()  (TRISC=TRISC & 0b11101111)
#define SDA_HIGH() (TRISC=TRISC | 0b00010000)
#define SCL_LOW()  (TRISC=TRISC & 0b11110111)
#define SCL_HIGH() (TRISC=TRISC | 0b00001000)
#define I2C_IDLE() (TRISC=TRISC | 0b00011000)



void InitI2C(){

    I2C_IDLE() //SDA (RC4) and SCL(RC3) high
    
    //Configure Register SSPCON
    CKP=1;      // don't hold clock down
    SSPM3=1;    //Firmware controlled Master Mode
    SSPM2=0;
    SSPM1=1;
    SSPM0=1;
    SSPEN=1; //enable SSP

}
//100 kHz -> 10us Clock cycle

/*If SDA and SCL both high -> Start Condition*/
void StartI2C(){

    I2C_IDLE();
    while(SDA == 0 || SCL ==0){   //wait till bus is free! Not needed in single master...
    }

    SDA_LOW();
    DelayUs(5); // Hold time start min 4,7us
    SCL_LOW();

}

/*SCL and SDA are low -> Stop Condition*/
void StopI2C(){
    
    DelayUs(5);
    SCL_HIGH();
    DelayUs(5);   //Stop setup time: min 4us for 100kHz
    SDA_HIGH();
    
}



void TransmitI2C(char c){
    char temp;
	int i;

    for(i=0; i<8;i++){ //set all 8 bit on the line

        temp=c & 0b10000000;
        c<<1;

        DelayUs(5);         //keep SCL at least 4.7us down
        if(temp){
            SDA_HIGH();
        }
        else{
            SDA_LOW();
        }

        DelayUs(1);     //data setup time min 250ns (nop 4Mhz = 1us)
        SCL_HIGH();
        DelayUs(5);     //SCL high min 4 us
        SCL_LOW();
    }
        SDA_HIGH();     //release bus to receive ACK

}

/*SCL and SDA are low*/
void WriteI2C(char data){

    TransmitI2C(data);
    DelayUs(5);     //SCL min 4.7us down
    SCL_HIGH();
    DelayUs(2);
	if(SDA==1){
		// Error Code if no Ack is received
	}
    DelayUs(3);     //SCL about 5us down.
    SCL_LOW();


}

void TxI2C(char control, char address, char data){
    StartI2C();
    WriteI2C(control);
    WriteI2C(address);
    WriteI2C(data);
    StopI2C();


}



void main(){
	TRISA=0x00;
	TRISB=0x00;
	TRISC=0x00;

	//initLCD();
	InitI2C();
	TxI2C(0b10100000, 0x01, 12);

	while(1){	
	}

}
