/* OK teste le 14/06/2011 sur 64MC802 */
// example PWM en mode simple (free running)
// example de configuration en mode complémentaire ou indépendant

#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 = 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 InitPORT_AND_PIN() 
{
	TRISBbits.TRISB14=0; //PWM1H1 EN SORTIE pin 25
	TRISBbits.TRISB15=0; //PWM1L1 EN SORTIE pin 26
	TRISBbits.TRISB12=0; //PWM1H2 EN SORTIE  pin 23
	TRISBbits.TRISB13=0; //PWM1L2 sera configure en sortie voir InitPWM  pin 23
}

void InitPWM()
{
	P1TCONbits.PTMOD=0b00; // free running mode p22
	P1TCONbits.PTOPS=0; 	//PWM Time Base Output Postscale
	
	P1TCONbits.PTCKPS=0;  //choix PrescalerDiv de Fcy (diviseur de frquence en entree PWM time base input clock period is TCY (1:1 prescale)
	
	PWM1CON1bits.PMOD1=0;	//sorties PWM1x1 complementaire page 9
	PWM1CON1bits.PEN1H=1;	//PWM1H1 activé
	PWM1CON1bits.PEN1L=1;	//PWM1L1 activé

	PWM1CON1bits.PMOD2=1;	//sorties PWM1x2  independante
	PWM1CON1bits.PEN2H=1;	//PWM1H2 activé
	PWM1CON1bits.PEN2L=0 ;	//PWM1L2 désactivé

//	PWM1CON2bits.IUE=1;
 	// PTPER=Fcy/(Fpwmvoulue x PrescalerDiv)
	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();
	// attention: Dedicated time base that supports TCY/2 PWM edge resolution
	// rapport de 2 entre PTPER et PxDCy
	P1DC1 = 4000; //PWM1L2 à 50% 
	P1DC2 = 6000; //PWM1L1 à 75% 

	while(1)
	{
	PORTBbits.RB13=!PORTBbits.RB13; // RB13=PWM1L2 mode indépendant
	}
	
}
