/****************************************************************************/
/* Copyright 2010 MBARI.                                                    */
/* MBARI Proprietary Information. All rights reserved.                      */
/****************************************************************************/
#include <p24fxxxx.h>
#include "analog.h"

#define ADC_DEBUGGING   1

void anaInit()
{
    /* configure ADC */
    AD1PCFGbits.PCFG10 = 0; /* Make sure AN10 is set to analog  */
    AD1PCFGbits.PCFG11 = 0; /* Make sure AN11 is set to analog  */

    AD1CON1 = 0x00E0;       /* SSRC<2:0> = 111 implies internal counter ends 
                            sampling and starts converting. */

    AD1CON2 = 0;
/*    AD1CON3 = 0x1F02;       /* Sample time = 31Tad, Tad = 3Tcy */
    AD1CON3 = 0x0F02;       /* Sample time = 15Tad, Tad = 3Tcy */

    AD1CSSL = 0;            /* Disable input scanning */
    AD1CON1bits.ADON = 1;   /* turn ADC ON */

#if ADC_DEBUGGING
/* debug bit for ADC testing */
_TRISE0 = 0;
_LATE0 = 0;
#endif

}

unsigned int anaGetSample(int channel)
{
    /* Connect the analog pin to the S/H input */    
    switch ( channel )
    {  
        case 10: AD1CHS = 0x000A; break;
        case 11: AD1CHS = 0x000B; break;
        default: return 0;
    }

    /* start sampling, after Tad go to conversion */
    AD1CON1bits.SAMP = 1;

#if ADC_DEBUGGING
_LATE0 = 1;
#endif

    /* wait for sample to complete */
    while ( AD1CON1bits.SAMP )
        ; /* sample complete? */

#if ADC_DEBUGGING
_LATE0 = 0;
Nop();
_LATE0 = 1;
#endif

    /* wait for conversion to complete */
    while ( !AD1CON1bits.DONE )
        ; /* conversion done */

#if ADC_DEBUGGING
_LATE0 = 0;
#endif
    
    /* return the current ADC value */
    return ADC1BUF0;
}

