#define _XTAL_FREQ 32000000
#include <XC.h>

#pragma config FOSC = INTOSC    // Oscillator Selection (INTOSC oscillator: I/O function on CLKIN pin)
#pragma config WDTE = OFF       // Watchdog Timer Enable (WDT disabled)
#pragma config PWRTE = ON      // Power-up Timer Enable (PWRT eabled)
#pragma config MCLRE = ON       // MCLR Pin Function Select (MCLR/VPP pin function is MCLR)
#pragma config CP = ON          // Flash Program Memory Code Protection (Program memory code protection is enabled)
#pragma config CPD = ON         // Data Memory Code Protection (Data memory code protection is enabled)
#pragma config BOREN = ON       // Brown-out Reset Enable (Brown-out Reset enabled)
#pragma config CLKOUTEN = OFF   // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin)
#pragma config IESO = ON        // Internal/External Switchover (Internal/External Switchover mode is enabled)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is enabled)

// CONFIG2
#pragma config WRT = ALL        // Flash Memory Self-Write Protection (000h to 1FFFh write protected, no addresses may be modified by EECON control)
#pragma config PLLEN = ON       // PLL Enable (4x PLL enabled)
#pragma config STVREN = ON      // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset)
#pragma config BORV = LO        // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.)
#pragma config LVP = ON         // Low-Voltage Programming Enable (Low-voltage programming enabled)

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "MCP3550.h"


#define AVERAGE_SAMPLES 4

void main(void)
{
	char uart_data;
	uint8_t cnt=0, i;

	int32_t ADC_Value, ADC_Buf[AVERAGE_SAMPLES], w_offset;
	int32_t weight;

	OSCCONbits.SCS = 00;       // Clock determined by FOSC<2:0> in Configuration Word 1.
	OSCCONbits.IRCF = 0b1110;	 // 8 MHz or 32 MHz HF
	OSCCONbits.SPLLEN = 1;     // 4xPLL Enabled

	LATA = 0x00;
	TRISA = 0x00;
	ANSELA = 0x00;

	LATC = 0x02;
	TRISC = 0x00;
	ANSELC = 0x00;

	MCP3550_Init();		
	MCP3550_StartConversion();
	while(1)
	{
		if(MCP3550_DataRdy())
		{
			ADC_Buf[cnt]=MCP3550_GetValue()&0x3FFFFF;	// Mask status bits

			ADC_Buf[cnt] <<= (32 - 22);
			ADC_Buf[cnt] >>= (32 - 22);	// Extend Sign

			MCP3550_StartConversion();
			cnt++;
			cnt &= AVERAGE_SAMPLES - 1;

			ADC_Value = ADC_Buf[0];
			for(i = 1; i < AVERAGE_SAMPLES; i++)
			{
				ADC_Value += ADC_Buf[i];
			}
			ADC_Value = ADC_Value / AVERAGE_SAMPLES;
		}
	}

}

