
// Ce programme permet de programmer un oscillateur a 1.6MHz en utilisant un oscillateur interne + switching PLL 

#include <p33FJ64MC802.h>
#include <stdio.h>
#include <timer.h>


_FOSCSEL(FNOSC_FRC);			
_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF  & POSCMD_XT);	// Clock Switching is enabled and Fail Safe Clock Monitor is disabled
													// OSC2 Pin Function: OSC2 is Clock Output
_FWDT(FWDTEN_OFF); 



/*_FOSCSEL(FNOSC_FRCPLL);
_FOSC( POSCMD_NONE &OSCIOFNC_OFF&FCKSM_CSDCMD);		// Primary disabled Oscillator & OSC2 is clock O/P &  Both disabled (pas de switching)
_FWDT(FWDTEN_OFF); 
*/

void InitClock() {
	PLLFBD = 38;	// M = 40		
	CLKDIVbits.PLLPOST = 0;	// N1 = 2	Registre oscillator.pdf page 10
	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) {};		// Permet d'attendre que la PLL est stabilisée
}

void InitClock2() {
	PLLFBD = 6;	// M = 8
	CLKDIVbits.PLLPOST = 0;	// N1 = 2
	CLKDIVbits.PLLPRE = 0;	// N2 = 2
	OSCTUN = 0;
	RCONbits.SWDTEN = 0;

	while(OSCCONbits.LOCK != 1) {};
}

int main (void)
{
	InitClock() ;
	TRISBbits.TRISB0=0;
	AD1PCFGLbits.PCFG2=1;
	for (;;)
		PORTBbits.RB0=!PORTBbits.RB0;


}





