/* 
 * File:   main.c
 * Author: q242695
 *
 * Created on 19. Juni 2013, 11:42
 */



#include <xc.h>
#include <stdlib.h>
#include <plib/pconfig.h>
#include <plib/usart.h>
#include <plib/adc.h>

#ifndef _XTAL_FREQ
#define _XTAL_FREQ 25000000
#endif
#define USE_AND_MASKS

#pragma config OSC = HS, WDT = OFF, PWRT = OFF, DEBUG = ON, CCP2MUX = OFF, OSCS = OFF, BOR = OFF

#define LED PORTBbits.RB3

unsigned char UART1Config = 0, baud = 0;
unsigned char MsgFromPIC[] = "\r\nADC value is :";
int ADCValue = 0;
unsigned char ADCStringVal[4];

/*
 * 
 */
int main(int argc, char** argv) {
    char count;
    TRISB=0x00;
    PORTB=0x00;

    TRISAbits.RA0 = 1; //AD Channel
    TRISCbits.RC6 = 0; //TX pin set as output
    TRISCbits.RC7 = 1; //RX pin set as input

    //Configure UART
    UART1Config = USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_BRGH_HIGH ;
    baud = 26;
    OpenUSART(UART1Config,baud);

    //Configure ADC
    OpenADC(ADC_FOSC_2 & ADC_RIGHT_JUST & ADC_8ANA_0REF, ADC_CH0 & ADC_INT_ON);// & ADC_VREFPLUS_VDD & ADC_VREFMINUS_VSS, 14);//ADC_0ANA);
    ADC_INT_ENABLE(); //Easy ADC interrupt setup

    ei();       //remember the master switch for interrupt
    ConvertADC();     //Start ADC

    while(1) // Run Forever
    {
      LED=1;
      for (count=0; count<25; count++)
        __delay_ms(20);
      LED=0;
      for (count=0; count<25; count++)
        __delay_ms(20);
    }
    return (EXIT_SUCCESS);
}

void interrupt ADCInterrupt() {
    //check if the interrupt is caused by ADC
    if(PIR1bits.ADIF == 1) {
        ADCValue = ReadADC();
        putsUSART(MsgFromPIC);
        putsUSART(itoa( ADCStringVal, ADCValue,10)); //convert to string
        //Reset interrupt flag and start conversion again
        ADIF = 0;
        ConvertADC();
    }
}