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

// voir doc pwm.pdf

_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
													// Primary Oscillator Mode: XT Crystal
_FWDT(FWDTEN_OFF); 

void InitClock() {
	PLLFBD = 30;	// M = 40
	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 InitPORT_AND_PIN() 
{
	TRISBbits.TRISB14=0; //PWM1H1 EN SORTIE
	TRISBbits.TRISB12=0; //PWM1H2 EN SORTIE
}

void InitPWM()
{
	P1TCONbits.PTMOD=0b00; // free running mode
	PWM1CON1bits.PMOD1=0;	//sorties pwm complementaire page 9
	PWM1CON1bits.PMOD2=0;	//sorties pwm complementaire
	PWM1CON1bits.PEN1H=1;	//PWM1H1 activé
	PWM1CON1bits.PEN2H=1;	//PWM1H2 activé
	PWM1CON1bits.PEN1L=1;	//PWM1L1 activé 
	PWM1CON1bits.PEN2L=1;	//PWM1L2 activé	
	P1TPERbits.PTPER=4000;  // 10kHz page 7 + formule page 25 ; 4000 valeur pour un rapport cyclique de 50%
	P1TCONbits.PTEN=1; // active PWM1 page 6
}

int main(void) {

	InitClock();	// This is the PLL settings	
	InitPORT_AND_PIN();

	InitPWM();

	P1DC1 = 4000; //PWM1 à 50%
	P1DC2 = 4000; //PWM2 à 50%
	while(1)
	{

	}
	
}
