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

void Init_ADC( void );


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

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 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 int ADCValue=0;
	unsigned char BUFFER[16]={0};
	unsigned char BUFF[50]="test",BUFF2[50];


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

//	sprintf(BUFF,"UART ok");
	UART_puts(BUFF);

	TRISBbits.TRISB9=0;
	TRISBbits.TRISB0=0;
	AD1PCFGLbits.PCFG2=1;

	//sprintf(&BUFFER[0],"appuiez sur S3");



	/* wait here until switch S3 is pressed */

    /* Infinite Loop */
    while ( 1 )
	{
		AD1CON1bits.SAMP = 0; 		// Start converting
	//	Delay_Us(10); 				// Wait for sampling time (10us)
		//AD1CON1bits.SAMP = 0;		// Start the conversion (PAS BESOIN ELLE COMMENCE 
		while (!AD1CON1bits.DONE);  // Wait for the conversion to complete
{		ADCValue = ADC1BUF0; 	    // Read the conversion result
		sprintf(BUFF2," %d ", ADCValue);
		UART_puts(BUFF2);
}


	//	sprintf(&BUFFER[0],"VAL_ADC: %d",ADCValue);           //creer la chaine
		
//		Delay_Us(1000); //delay pour affichage plus clair  
	}
}


void Init_ADC( void )
{

	/* set port configuration here */ 		
 //	AD1PCFGLbits.PCFG4 = 0;         // ensure AN4/RB4 is analog (Temp Sensor)
 //	AD1PCFGLbits.PCFG5 = 0;         // ensure AN5/RB5 is analog (Analog Pot)
 	AD1PCFGLbits.PCFG0 = 0;         // ensure AN0/RA0 is analog (Analog Pot)
 	AD1PCFGLbits.PCFG1 = 0;         // ensure AN1/RA1 is analog (Analog Pot)
 

		AD1CON1bits.FORM   = 0;		// Data Output Format:  unsigned int
	    AD1CON1bits.SSRC   = 7;		// Conv Auto
		AD1CON1bits.ASAM   = 1;		// Auto SAMPLING
		AD1CON1bits.AD12B  = 0;		// 10-bit ADC operation
		AD1CON2bits.VCFG	=0;  	// VREFH=VDD et VREFL=VSS 
		AD1CON1bits.SIMSAM = 1;		// Simultane sampling of channels
	
		AD1CON2bits.CHPS  = 0;		// Converts CH0

		AD1CON3bits.ADRC = 0;		// ADC Clock is derived from Systems Clock
		//AD1CON3bits.ADCS = 63;		// ADC Conversion Clock Tad=Tcy*(ADCS+1)= (1/40M)*64 = 1.6us (625Khz)
									// ADC Conversion Time for 10-bit Tc=12*Tab = 19.2us

		AD1CON3bits.ADCS = 2;       // Tad=Tcy*(ADCS+1)= (1/40M)*3 = 75ns (la limite est de 75ns)


		AD1CON3bits.SAMC= 10; 		// SAMC * TAD = TEMPS DE SAMPLING (SAMC: COEFF ARBITRAIRE entre 0 et 31)


		AD1CON2bits.SMPI    = 0;	//ADC interrupt is generated at the completion of every sample/conversion operation

		AD1CON2bits.CSCNA = 0;		// pas de scan sur bloc entree CH0
		//AD1CSSH = 0x0000;  		// en mode scanning
		// AD1CSSLbits.CSS4=1;		// en mode scanning Enable AN4 for channel scan
		// AD1CSSLbits.CSS5=1;		// en mode scanningEnable AN5 for channel scan
		AD1CON2bits.ALTS=0;	 		// pas de mode alterne
		AD1CHS0bits.CH0SA = 1; 		//MUXA +ve input selection  AN1	Pour tester, il faut mettre une tension continue sur RA1
		AD1CHS0bits.CH0NA = 0; 		// MUXA -ve input selection (VREF-) for CH0
 
		IFS0bits.AD1IF = 0; 		// Clear the A/D interrupt flag bit
		IEC0bits.AD1IE = 0; 		// Do Not Enable A/D interrupt
        AD1CON1bits.ADON = 1;		// Turn on the A/D converter	


	
		AD1CON1bits.ADON = 1; 		// Turn on the A/D converter


}
