#include <p33FJ64MC802.h>
#include "drvI2C.h"


void InitI2C1()
{
	unsigned int config2, config1;
	/* Baud rate is set for 100 (Khz )*/
	config2 = 59 ; //I2Cbr=59 I2Cfreq= 400 ///  I2Cbr=359 I2Cfreq= 100 	calcul:	 I2Cfreq= 400; I2Cbr=(fcy/I2Cfreq-fcy/1000)/1000-1 
	/* Configure I2C for 7 bit address mode */
	config1 = (I2C_ON & I2C_IDLE_CON & I2C_CLK_HLD &
	           I2C_IPMI_DIS & I2C_7BIT_ADD &
	           I2C_SLW_DIS & I2C_SM_DIS &
	           I2C_GCALL_DIS & I2C_STR_DIS &
	           I2C_NACK & I2C_ACK_DIS & I2C_RCV_DIS &
	           I2C_STOP_DIS & I2C_RESTART_DIS &
	           I2C_START_DIS);
	OpenI2C1(config1,config2); 
	IdleI2C1();
}

char ReadMultipleI2C1(unsigned char Addr, unsigned char Register, int Nb, unsigned char * Data)
{		int i;
		char result;
		StartI2C1();
		IdleI2C1();
		result=MasterWriteI2C1(Addr);
		if (result<0) {goto exit;}
		result=MasterWriteI2C1(Register);
		if (result<0) {goto exit;}
		RestartI2C1();
		IdleI2C1();
		result=MasterWriteI2C1(Addr|1);   //Addr+1: addresse en lecture
		if (result<0) {goto exit;}
		for(i=0; i<Nb; i++) 
			{
			*Data = MasterReadI2C1();
			IdleI2C1();
			if(i<(Nb-1))
				{ AckI2C1();
				  IdleI2C1();
				  Data++;
				}
			}
		NotAckI2C1();
		IdleI2C1();
		result=0;

exit:	StopI2C1();
		IdleI2C1();
	return(result);
}


unsigned char ReadByteI2C1(unsigned char Addr, unsigned char Register)
	{	unsigned char data;
		char result;
		StartI2C1();
		IdleI2C1();
		result=MasterWriteI2C1(Addr);
		if (result<0) {goto exit;}
		result=MasterWriteI2C1(Register);
		if (result<0) {goto exit;}
		RestartI2C1();
		IdleI2C1();
		result=MasterWriteI2C1( Addr|1);   //Addr+1: addresse en lecture
		if (result<0) {goto exit;}
		data = MasterReadI2C1();
		IdleI2C1();
		NotAckI2C1();
		IdleI2C1();
		result=0;

exit:	StopI2C1();
		IdleI2C1();
	return (data);
}


char WriteByteI2C1(unsigned char Addr, unsigned char Register,unsigned char data)
	{	char result;
		StartI2C1();
		IdleI2C1();
		result=MasterWriteI2C1(Addr);
			if (result<0) {goto exit;}
		result=MasterWriteI2C1(Register);
			if (result<0) {goto exit;}
		result=MasterWriteI2C1( data);

exit:	StopI2C1();
		IdleI2C1();
		return(result);
}
