#include <p33FJ64MC802.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <uart.h>

#define FCY (80000000/2)
#define BAUDRATE 9600
#define BRGVAL ((FCY/BAUDRATE)/16) - 1
#define sortie PORTBbits.RB9

_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); 


int r=0;
char  recept[10];
	
	int i=0;


void __attribute__ ((interrupt, no_auto_psv)) _U1RXInterrupt(void) {
	char c;
	c= U1RXREG; //ECHO
	while(U1STAbits.UTXBF);// attend buffer vide
	U1TXREG =c;
	IFS0bits.U1RXIF = 0;
}


void UART_puts(char * string)
{
	unsigned int i=0;
	while (string[i]!='\0')
	{
		while(U1STAbits.UTXBF);//attend buffer vide
		U1TXREG = string[i];
		i++;
	}
}

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 InitUART1() {
U1MODEbits.UARTEN=0; // desactive l'UART1
	U1BRG=259; //9600 a 40MIPS
	U1MODEbits.PDSEL=0; //8bit sans parité
	U1MODEbits.STSEL=0; //un bit de stop;
	U1MODEbits.UEN=0;   //Juste UX et RX (pas de controles...)
	U1MODEbits.ABAUD=0;// pas de mesure de vitesse
	U1MODEbits.BRGH=0; //vitesse lente
	IPC2bits.U1RXIP = 4;	// Mid Range Interrupt Priority level, no urgent reason
	IEC0bits.U1RXIE = 1;	// Enable Recieve Interrupts
	U1MODEbits.UARTEN = 1; //Active l'uart1
	U1STAbits.UTXEN=1; //Active la transmision


}
void InitPORT_AND_PIN() {
	_U1RXR=3;	//RX sur RP3 autre ecriture RPINR0bits.INT1R=0
	_RP4R=3;   //TX sur RP4
}





int main(void)
 {
	unsigned char BUFF[50]="test";

	InitClock();	// This is the PLL settings	
	InitPORT_AND_PIN();
	InitUART1();
//	sprintf(BUFF,"Un entier: %d\nUn float: %d",10,10);
	UART_puts(BUFF);

 TRISBbits.TRISB9=0;


	while(1)
	{
//		UART_puts(BUFF);
		sortie=0;
		
/*	if(r==1)
{




}*/
		
	}
	
}
