/****************************************************************************/
/* Copyright 2010 MBARI.                                                    */
/* MBARI Proprietary Information. All rights reserved.                      */
/****************************************************************************/
#include <p24fxxxx.h>
#include "analog.h"

void anaInit()
{
    /* configure ADC */
    AD1PCFGbits.PCFG5 = 0;  /* Make sure AN5 is set to analog  */
    AD1PCFGbits.PCFG4 = 0;  /* Make sure AN4 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 */
}

int anaGetSample(int channel)
{
    int sample;
    
    /* Connect the analog pin to the S/H input */    
    switch ( channel )
    {  
        case 4: AD1CHS = 0x0004; break;
        case 5: AD1CHS = 0x0005; break;
        default: AD1CHS = 0x0005; break;
    }

    /* start sampling, after 31Tad go to conversion */
    AD1CON1bits.SAMP = 1;
    
/* LATBbits.LATB12 = 0;*/
    /* wait for sample to complete */
    while ( AD1CON1bits.SAMP )
        ; /* sample complete? */
/*LATBbits.LATB12 = 1;*/
    
    /* wait one-cyle to make sure DONE bit is in valid state */
/*    Nop();*/

/*LATBbits.LATB12 = 0;*/
    /* wait for conversion to complete */
    while ( !AD1CON1bits.DONE )
        ; /* conversion done? */
/*LATBbits.LATB12 = 1;*/
    
    /* get the current ADC value */
    sample = (int)ADC1BUF0;
    
    return sample;
}

