// quick and dirty
//----Fonctionne 6.12.11------
// test du whoiam du gyro

#include <p33FJ64MC802.h>
#include <stdio.h>
#define _MI2CIF 
#include <i2c.h>

#include <libpic30.h> //pour les DELAY
 #define FOSC  80000000LL  // clock-frequecy in Hz with suffix LL (64-bit-long), eg. 32000000LL for 32MHz
 #define FCY       (FOSC/2)  // MCU is running at FCY MIPS
 #define delay_us(x) __delay32(((x*FCY)/1000000L)) // delays x us
 #define delay_ms(x) __delay32(((x*FCY)/1000L))  // delays x ms
 #define __DELAY_H 1

// COMMANDES Du gyro
#define GYRO_ADDRESS 			0xD0 // adresse par défaut du GYRO
#define REG_HELLO    		0x00   // registre de commande




_FOSCSEL(FNOSC_PRIPLL);								// Choix du oscillateur + PLL
_FOSC(FCKSM_CSDCMD & OSCIOFNC_OFF  & POSCMD_XT);	// Pas de basculement d'horloge
													// pas de OSC2
													// type d'oscillateur XT
_FWDT(FWDTEN_OFF); // watchdog off;






void InitClock() {
  // CHOIX DES COEF DE LA PLL : voir notice OSCILLATOT
	// FOSC = FIN •(M/(N1*N2))  et Fcy=Fosc/2 = fréquence de fct des périphriques
	// ex: quartz 8Mhz et Fosc=80Mhz => Fosc=8M*(40/4)
	PLLFBD = 38;				// M = 40       
	CLKDIVbits.PLLPOST = 0;		// N1 = 2
	CLKDIVbits.PLLPRE = 0;		// N2 = 2
	OSCTUN = 0;
	RCONbits.SWDTEN = 0;

	while(OSCCONbits.LOCK != 1) {}; // attente verrouillage PLL
}



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

// retourne le premier echo en cm
unsigned int read_hello(void) {
   unsigned char dl ,  dh ;
   int d ;

   		StartI2C1();   

	   IdleI2C1();
	   MasterWriteI2C1(GYRO_ADDRESS);
	//   IdleI2C1();           
	   MasterWriteI2C1(REG_HELLO);
	  // IdleI2C1();
       RestartI2C1();  
 
	   IdleI2C1();
	   MasterWriteI2C1(GYRO_ADDRESS|1);
	  // IdleI2C1(); 
	   //dh = MasterReadI2C1(); //lit le poid fort
	   //IdleI2C1();  
	  // AckI2C1(); 
	   //IdleI2C1();           
	   dl = MasterReadI2C1(); //lit le poid faible
	   IdleI2C1();
	   NotAckI2C1();
	   IdleI2C1();
   StopI2C1();
   IdleI2C1(); 

     return dl ;
}



int main(void) {
int d;
int a=0;


	InitClock();	// This is the PLL settings	
	InitI2C();
	d=read_hello();
	
	
for(;;)
{
a++;
}

	
}
