#include "OB6710.h"
#include "ADC.h"

bit g_AdcInterrupt = 0;

void ADC_Interrupt(void) interrupt d_ADC_Vector  // ADC Interrupt Vector Address 0053h => interrupt 10
{  
    g_AdcInterrupt = 1;
}

void ADC_start(unsigned char nLength)
{  
		ADCINTFlag = 0x00	;
		ADCSL = nLength;  
		ADCC2 = ADCC2 | 0x80;      //ADC start conversion
    while(1)
		{
		  if(( ADCINTFlag & d_ADC_INT_SEQUENCE) == d_ADC_INT_SEQUENCE) 
			  break;
		}
}

void ADC_Init(void)
{
	ADCCD = 0x00;
	ADCC2 = 0x02;
	while(1)
	{
		if(ADCCAL == 0x02)
			break;
	}
}

void ADC_SetInputSource(unsigned char nInputSel, unsigned char nChannelNO, unsigned char nMode)
{
  if(nMode == d_ADC_MODE_continue)   
		nChannelNO = nChannelNO & 0xEF;
  else
		nChannelNO = nChannelNO | 0x10;
		
	switch(nInputSel)
    {
        case d_ADC_INPUT_1ST:
				  	ADCSC1 = nChannelNO;
            break;

        case d_ADC_INPUT_2ND:
				  	ADCSC2 = nChannelNO;
				break;

        case d_ADC_INPUT_3RD:
				  	ADCSC3 = nChannelNO;
				break;

        case d_ADC_INPUT_4TH:
				  	ADCSC4 = nChannelNO;
				break;

        default:
            break;
    }
}

void ADC_GetSampleResult(unsigned int *pResult, unsigned char nLength)
{
	unsigned int Buff;
  unsigned char Loop, Shift;
	unsigned char ADC_INT_Buff;
	ADC_INT_Buff = ADCINTEN;
	ADCINTEN = 1;
	ADC_UPDATE_DISABLE = 1;	
	if (nLength > 4)
		nLength = 4;
	
	if((ADCCD & 0x80) == 0x00)
		Shift = 0x04;
	else
		Shift = 0x08;
		
	Loop = 0x00;
  while(1)
	{		
		//-------------------------------------------------	
		if(Loop == 0x00)
		{
				Buff = ADCRS0H;
				Buff = (Buff << Shift) | ADCRS0L;
		}
		//-------------------------------------------------	
		if(Loop == 0x01)
		{
				Buff = ADCRS1H;
				Buff = (Buff << Shift) | ADCRS1L;
		}
		//-------------------------------------------------			
		if(Loop == 0x02)
		{
				Buff = ADCRS2H;
				Buff = (Buff << Shift) | ADCRS2L;
		}
		//-------------------------------------------------		
		if(Loop == 0x03)
		{
				Buff = ADCRS3H;
				Buff = (Buff << Shift) | ADCRS3L;
		}
		//-------------------------------------------------	
		(*(pResult + Loop)) = Buff;
		Loop++;
		if(Loop >=nLength)
			break;			
	}
		ADC_UPDATE_DISABLE = 0;	
	  ADCINTEN = ADC_INT_Buff;
}

void ADC_TimerTrigger(unsigned char nData)
{
	ADCTrigSource2 = nData | 0x80;
	TR1 = 1;				// Timer1 Run; 
}

void ADC_TimerTriggerCounter(unsigned int Counter)
{
	Timer1TrigADCL = (unsigned char)(Counter >> 0x00);
	Timer1TrigADCH = (unsigned char)(Counter >> 0x08);
}

void ADC_EnableIE(unsigned int Mode)
{
	EA = 1;
	IEADC = 1;  
	ADCINTEN = Mode;
}
