#include "S08_ADC12.h"
  
#pragma DATA_SEG DEFAULT
UINT16* pADC_Pointer;
#pragma DATA_SEG MY_ZEROPAGE
static UINT8 near gu8ADCindex;
static volatile near UINT8 ADC_Chan_Table[] = {ADC1_CHAN};
#pragma DATA_SEG DEFAULT


/************************************************************************************************/
/*                                      Functions Section                                       */
/************************************************************************************************/
#pragma CODE_SEG DEFAULT


void HWTrig_ADC_Init(UINT16* pADC_BufferPointer)
{
  gu8ADCindex = 0;
  SCGC1_ADC = 1;
  ADCSC1 = ADCSC1_AIEN_MASK;
  ADCSC2 = ADCSC2_ADTRG_MASK;
  ADCCFG = ADCCFG_ADIV1_MASK | ADCCFG_ADIV0_MASK | ADCCFG_MODE0_MASK | ADCCFG_ADICLK1_MASK| ADCCFG_ADICLK0_MASK;
  APCTL1 = APCTL1_REG;
  #ifdef APCTL2
    APCTL2 = APCTL2_REG;
  #endif
  
  #ifdef APCTL3
    APCTL3 = APCTL3_REG;
  #endif

  ADCSC1_ADCH = ADC_Chan_Table[gu8ADCindex];
  
  pADC_Pointer = pADC_BufferPointer;
}                           


void ADC_Init(UINT16* pADC_BufferPointer)
{
  SCGC1_ADC = 1;
  ADCSC1 = 0;
  ADCSC2 = 0;
  //ADCCFG = ADCCFG_ADLPC_MASK | ADCCFG_ADIV1_MASK | ADCCFG_ADIV0_MASK | ADCCFG_MODE0_MASK | ADCCFG_ADICLK0_MASK;
  ADCCFG = ADCCFG_ADLSMP_MASK | ADCCFG_ADIV1_MASK | ADCCFG_ADIV0_MASK | ADCCFG_MODE0_MASK | ADCCFG_ADICLK0_MASK;
  APCTL1 = APCTL1_REG; 
  #ifdef APCTL2
    APCTL2 = APCTL2_REG;
  #endif
  
  #ifdef APCTL3
    APCTL3 = APCTL3_REG;
  #endif
  
  pADC_Pointer = pADC_BufferPointer;
}                           


void ADC_Start_conversion(UINT8 chan)
{
  ADCSC2 = 0; 
  ADCSC1 = ADCSC1_AIEN_MASK | chan;
  
}
  
void ADC_Start_conversions(void)
{
	ADCSC1 = ADCSC1_ADCO_MASK;
}

UINT16 ADC_Get_Conversion(void)
{
  while(ADCSC2_ADACT)
  {
    //_Wait;
  }
  return ADCR;
}

void ADC_End(void)
{
  SCGC1_ADC = 0;
}

void interrupt VectorNumber_Vadc ADC_ISR(void)
{
  *pADC_Pointer = ADCR;
  pADC_Pointer++;
  if(gu8ADCindex==(TOTAL_ADCs-1))
  {
    gu8ADCindex = 0;
    ADCSC2_ADTRG = 1;
    ADCSC1_ADCH = ADC_Chan_Table[gu8ADCindex];
    pADC_Pointer -= TOTAL_ADCs;
  }
  else
  {
    gu8ADCindex++;
    ADCSC2_ADTRG = 0;
    ADCSC1_ADCH = ADC_Chan_Table[gu8ADCindex];
 }
}