#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */

#define storedTRIM *((char*)0xFFAF )
#define ADC_CH4			ADCSC1A_ADCHA2_MASK
word ADC_result[8];  //16-bit
byte i;
void SetBus24MHz_FEI(void)
{
   MCGTRM = storedTRIM ; // fINT trimed to   31250  Hz 
   MCGC1 =0x04; //reset default; FEI mode
   MCGC2 = 0x00; //BDIV = 1. After reset typical BUS = fMCGOUT/4 = 16 MHz/4  = 4MHz
   MCGC3 = 0x01; //reset default value
   MCGC4 = 0x02; // Set FLL  = 1536 x 31.25Khz internal  = 48MHz
   while(MCGSC_CLKST !=  MCGC1_CLKS ) {} // wait till FEI is enaged
   while(! MCGSC_LOCK ){} //Ensure FLL is locked before proceed to next program
} //end of SetBus24MHz_FEI

void main(void) 
{
	SetBus24MHz_FEI();
	
	ADCCFG1 = 0x1F;          // High speed, /1 long sample, 16 bit, async clock
	ADCSC3 = 0x87;  
	
    PDBMOD = 0xffff;
    PDBIDLY = 65535 ; // Effective after writting PDBSC_DACTOE = 1, delay depends on bus speed.
    PDBSC_LDOK = 1   ;// Load value of PDBDLYn from buffers to registers
    PDBC1_TRIGSEL=7  ;// Software triggered 
    PDBSC_TOS =2 ; // needed for either Back to Back or Channel delay
    PDBSC_PDBIE = 0 ; // PDB interrupt disable
    PDBC2 = 0xFE ;    // Back to back triggers ADC conversion. SW trigger not yet started
    PDBCHEN = 0xFF;   // Eneable output to related ADC n channels
	PDBC1_CONT =1  ;  // 0= SingleShot Mode (good for polling) . 1 continuous mode (good for interrupt driven)
	PDBSC_PDBEN =1 ;  // Enable PDB module
	PDBC1_PRESCALER = 0; 
	PDBC1_MULT = 0 ;  
	   for (i=0; i<8 ; i++)
	      {
	      ADC_result[i] = 0 ; 
	      }

	ADCSC1A = ADCSC1A_AIENA_MASK | ADC_CH4;
	ADCSC1B = ADCSC1B_AIENB_MASK | ADC_CH4;
	ADCSC1C = ADCSC1C_AIENC_MASK | ADC_CH4;
	ADCSC1D = ADCSC1D_AIEND_MASK | ADC_CH4;
	ADCSC1E = ADCSC1E_AIENE_MASK | ADC_CH4;
	ADCSC1F = ADCSC1F_AIENF_MASK | ADC_CH4;
	ADCSC1G = ADCSC1G_AIENG_MASK | ADC_CH4;
	ADCSC1H = ADCSC1H_AIENH_MASK | ADC_CH4;
		
	ADCCFG2_ADACKEN = 1 ;  // Enabled as

	  ADCSC2_ADTRG = 1 ; // Hardhare trigger enabled. ADC conversion starts by either Back-back PDB or Channeln Delay PDB triggers
	  PDBC2_SWTRIG = 1;	 // Start PDB by software trigger

 
  for(;;) 
  {
  __RESET_WATCHDOG();	
  } 
}

__interrupt VectorNumber_Vadc  void adc_ISR (void)
{
 (void)ADCRA; // read ADC result and clear the corresponding ADC channel flag
 (void)ADCRB; // read ADC result and clear the corresponding ADC channel flag
 (void)ADCRC;
 (void)ADCRD;
 (void)ADCRE;
 (void)ADCRF;
 (void)ADCRG;
 (void)ADCRH ;
  
 return;
}


