#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
#include "MCG.h"
#include "ADC.h"
#include "DAC.h"
#include "VREF.h"
#include "OPAMP.h"
#include "Display.h"

void vfnPDB_DAC (void);

void main(void) 
{
  EnableInterrupts;
  vfnMCG_Init();
  vfnSCIInit();
  
  /** Enabled VREF to source internal peripherals */
  vfnVREF_Init (_IntUseOnly);
  
  vfnPDB_DAC();
  
  /** Enable sine wave to exit from DAC*/
  //TPM1SC = 0x49;
  vfnDACFillBuffer();
  vfnDACInit(gu8DACConfig1, gu8DACConfig2);
  vfnDACSetPointer (0,15);
  
  /** Amplify DACO with OPAMP0*/
  vfnOPAMPInit ();
  vfnOPAMPConfig (OPAMP0);
  
	PDBC1_TRIGSEL = 0b111;	//software trigger input
	PDBC2_SWTRIG = 0b1;	//fire software trigger
  
  /** Configure ADC */
  vfnADC_Init ();
  vfnADConfigChannel(2);
  ADC_CONVERT_CONTINUOUS_CHANNEL(2);
  
  
  
  for(;;) 
  {
	if (ADC_COCO)
	{
		ADC_COCO_CLEAR;
		vfnGraphicWords(&sADC.gu16LatestResult[0]);
	}
	
  __RESET_WATCHDOG();	
  } 
}

void vfnPDB_DAC (void)
{
	//set prescaler value, assuming bus clock = 24MHz
		PDBC1_PRESCALER = 0b011;	//uses bus clock/8 as PDB input
		PDBC1_MULT = 0b0;	
		PDBC1_CONT = 0b1;		//continuous mode
		
		PDBSC_PDBIE = 0b1;	//PDB interrupt enable
		PDBSC_PDBIF = 0b1;	//PDB interrupt clear

		PDBSC_TOS = 0b10;	//trigger n is OR function of all channel output
		
		PDBSC_DACTOE = 0b1;	//DAC trigger enable
		
		//set buffered register content
		PDBMOD = 400;	//Modulus is 0.33us*400 ticks = 132us
		DACINT = 50; 	//DAC trigger interval 0.33us*50 ticks = 16.5us
		PDBIDLY = 400;
		
		PDBSC_LDOK = 0b1;	//load buffered registers
		while(PDBSC_LDOK);	//wait till LDOK is cleared
		
		PDBCHEN = 0xff;	//enable all channel output
		
		PDBSC_PDBEN = 0b1;	//counter enable
		

}

