#include <p33FJ64MC802.h>

void InitClock() {
	PLLFBD = 30;	// M = 32
	CLKDIVbits.PLLPOST = 0;	// N1 = 2
	CLKDIVbits.PLLPRE = 0;	// N2 = 2
	OSCTUN = 0;
	RCONbits.SWDTEN = 0;
// Clock switch to incorporate PLL
	__builtin_write_OSCCONH(0x03);		// Initiate Clock Switch to 
										// FRC with PLL (NOSC=0b001)
	__builtin_write_OSCCONL(0x01);		// Start clock switching
	while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur	
	while(OSCCONbits.LOCK != 1) {};
}

void InitClock2() 
{   // 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 InitPORT_AND_PIN() 
{  
	//*********SPI1=Master

	TRISCbits.TRISC0=0;   //CLK1
	AD1PCFGLbits.PCFG6=1; //AN6 en digital SCK

        TRISCbits.TRISC3=0;  //SDO1 sortie sur RC3 digital
	AD1PCFGLbits.PCFG7=1; //AN7 en digital
	
	TRISCbits.TRISC2=0;  //SSLAVE1
	AD1PCFGLbits.PCFG8=1;//AN8 en digital
        
        RPINR20bits.SDI1R=0X11; // SDI input sur RP17/AN7/RC1
	_RP19R=7; //SDO sur RP19 broche digitale/RC3
	_RP16R=8; //SCK1 OUT sur RP16/RC0
        //_RP18R=9; //// SSlave1OUT sur RP18/AN8/RC2

        //*********SPI2=Slave

	TRISCbits.TRISC4=1;	//SCK2/RC4/RP20
	TRISCbits.TRISC5=1;	//SDI2/RC5
	TRISCbits.TRISC6=1;	//SSLAVE2/RC6
        TRISCbits.TRISC7=0;	//SDO2 /RC7

        RPINR22bits.SDI2R=21;    //SDI2 sur RP21/RC5
        RPINR22bits.SCK2R=20;    //SCK2 sur RP20
        RPINR23bits.SS2R=22;      //SSLAVE2 sur RP22
	_RP23R=10 ; //SDO2 sur RC7/RP23

}