#define FOSC 8000000UL
#define FCY (FOSC / 2)
#include <xc.h>

void TimerInit(void)
{
	PR1 = 0x186A;	  //%6250
	T1CONbits.TCKPS = 0x1; //1:8 prescaler
	IPC0bits.T1IP = 5;	 //set interrupt priority
	IFS0bits.T1IF = 0;	 //reset interrupt flag
	IEC0bits.T1IE = 1;	 //turn on the timer1 interrupt
	T1CONbits.TON = 1;	//Turn on timer
}

void PWM_Init(void)
{
	OC1CON1 = 0; //Clear, advised in FRM
	OC1CON2 = 0; //Clear, advised in FRM
	OC1CON1bits.OCTSEL = 7; // FCy as source

	OC1R = 0x0; //initial period = 0%
	OC1RS = 0x0FFF; //period = 4095

	OC1CON1bits.OCM = 6; //left aligned PWM
	OC1CON2bits.SYNCSEL = 0x1F; //Determine period by OC1RS
}

void SPI_Init(void)
{
	SPI1CON1bits.CKE = 1; //Clock event occurs in the middle of Data window
	SPI1CON1bits.MSTEN = 1; //Master Mode enable
	SPI1CON1bits.SPRE = 7;
	SPI1CON1bits.PPRE = 3;
	SPI1STATbits.SPIROV = 0; //Clear SPI
	SPI1STATbits.SPIEN = 1; //Enable SPI
}

void UART_Init(void)
{
    U1MODEbits.UARTEN = 0;        // Bit15 TX, RX DISABLED, ENABLE at end of func
    U1MODEbits.UEN = 0;          // Bits8,9 TX,RX enabled, CTS,RTS not
    U1MODEbits.BRGH = 0;          // Bit3 16 clocks per bit period
    U1MODEbits.PDSEL = 0;        // Bits1,2 8bit, No Parity 
    U1MODEbits.STSEL = 0;         // Bit0 One Stop Bit

    U1BRG = 25;         // BAUDRATE 9600

    U1STAbits.UTXISEL1 = 0;       //Interrupt when Char is transferred
	U1STAbits.UTXISEL0 = 0;
    U1STAbits.URXISEL1 = 0;       //Bits6,7 Int. on character recieved
	U1STAbits.URXISEL0 = 0;

    U1MODEbits.UARTEN = 1;        // And turn the peripheral on
	U1STAbits.UTXEN = 1;
    
    IPC2bits.U1RXIP = 4;  //set interrupt priority
	IFS0bits.U1RXIF = 0;	 //reset interrupt flag
	IEC0bits.U1RXIE = 1;	 //turn on the U1RX interrupt
}

void SendUARTChar(char c)
{
    while(U1STAbits.UTXBF != 0);
    U1TXREG = c;
}

void SendUARTString(char *s) 
{
while (*s)
	{
	SendUARTChar(*s);
	s++;
	}
}

void ADC_Init(void)
{
AD1PCFGbits.PCFG8 = 0;
AD1CON1 = 0x00E0;
AD1CHS = 0x08;	//channel AN8
AD1CSSL=0;
AD1CON3 = 0x1F05;
AD1CON2 = 0x0000;
AD1CON1bits.ADON = 1;
}

unsigned int get_adc()
{
unsigned int temp;
AD1CON1bits.SAMP = 1;
while (AD1CON1bits.DONE == 0);
temp = ADC1BUF0;
return temp;
}

