#include <p33FJ64MC802.h>

void InitClockSwitch() {
	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 InitClockNoSwitch() 
{   // 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() 
{ // depend du schema de la carte
	_U1RXR=3;	                    //RX sur RP3 autre ecriture RPINR0bits.INT1R=0
	_RP4R=3;                        //TX sur RP4

	TRISBbits.TRISB3=1;     			// RX pin sur RP3/RB3 (broche 7)
	AD1PCFGLbits.PCFG5=1;			// RP3/RB3/AN5  en digital

	TRISBbits.TRISB4=0; 				// TX pin sur RP4/RB4 rq:pas de AN

	TRISBbits.TRISB0=0;				// led vie
	AD1PCFGLbits.PCFG2=1;			// RB0/AN2 en digital

}