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


void InitI2C1()
{
	unsigned int config2, config1;
	/* Baud rate is set for 100 (Khz )*/
	config2 = 59; //I2Cbr; //c'etait 	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();
}

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


unsigned char ReadByteI2C1(unsigned char Addr, unsigned char Register)
{	unsigned char data;
	StartI2C1();
	IdleI2C1();
	MasterWriteI2C1(Addr);
	MasterWriteI2C1(Register);
	RestartI2C1();
	IdleI2C1();
	MasterWriteI2C1( Addr|1);   //Addr+1: addresse en lecture
	data = MasterReadI2C1();
	IdleI2C1();
	NotAckI2C1();
	IdleI2C1();
	StopI2C1();
	IdleI2C1();
	return (data);
}


void WriteByteI2C1(unsigned char Addr, unsigned char Register,unsigned char data)
{	
	StartI2C1();
	IdleI2C1();
	MasterWriteI2C1(Addr);
	MasterWriteI2C1(Register);
	MasterWriteI2C1( data);
	StopI2C1();
	IdleI2C1();
}
