/*
 *  for MB9BF618T on FRK-FM3
 * 
 *   Copyright (C) by Y.Ishioka.
 */
#include <basic.h>
#include <tk/tkernel.h>
#include <libstr.h>
#include <tk/syslib.h>
#include <drivers/adc.h>

#include <tk/sysdef.h>


/***********************************************************/
/*
 * ADC initialize
 */
void  adc_init( void )
{
    /* ENBL=1 */
    out_b( ADC0_ADCEN, 0x01 ) ;
    while( (in_b( ADC0_ADCEN ) & 0x02) == 0 ) ;

    /* AN16=1 */
    out_b( ADC0_SCIS2, 0x01 ) ;

    /* sampling time 1/HCLK * (31+1)*256+1 */
    out_b( ADC0_ADST0, 0xff ) ;

    out_b( ADC0_ADCR, 0x00 ) ;

    /* ADC stop */
    out_b( ADC0_ADSR, 0x80 ) ;

    /* RPT=0 SSTR=0 */
    out_b( ADC0_SCCR, 0x00 ) ;
}


/*
 *  start ADC convert
 *    return : == 0 : success
 *           : != 0 : fail
 */
int  adc_start( int port )
{
    /* RPT=0 SSTR=1 */
    out_b( ADC0_SCCR, 0x01 ) ; /* start AD convert */

    return( 0 ) ;
}


/*
 *  read ADC result data
 *    return : == 0xffffffff : fail or not completed
 *             others        : result data
 */
unsigned int  adc_read( int port )
{
    unsigned int  result ;

    result = (unsigned int)in_w( ADC0_SCFD ) ;
    if( (result & 0x00001000) != 0 ) {
        result = 0xffffffff ;
    } else {
        if( (result & 0x0000001f) == port ) {
            result >>= 20 ;
        } else {
            result = 0xffffffff ;
        }
    }

    return( result ) ;
}



