/******************** (C) COPYRIGHT 2022 SONiX *******************************
* COMPANY:	SONiX
* DATE:		2022/01/03
* IC:			SN8F5762
*____________________________________________________________________________
* REVISION		Date				Author		Description
* 1.0					2022/01/03	SONiX			1. First release
*____________________________________________________________________________
*****************************************************************************/
/*_____ I N C L U D E S _________________________________*/
#include <SN8F5762.h>
#include "ADC.h"

/*_____ F U N C T I O N S _______________________________*/
void GPIO_Initialization(void);
void ADC_Initialization(void);

/*_____ D E F I N I T I O N S ___________________________*/

/*_____ D E C L A R A T I O N S _________________________*/
uint16_t	dbADC_DataBuf;

/*_____ M A C R O S _____________________________________*/
#define	IO_PORT0_OUTPUT_LOW		P0M |= 0xFF;	P0 &= 0x00;
#define	IO_PORT1_OUTPUT_LOW		P1M |= 0xFF;	P1 &= 0x00;
#define	IO_PORT2_OUTPUT_LOW		P2M |= 0xFF;	P2 &= 0x00;

#define OB_IO_OUTPUT_LOW   		P00=0;  P0M |=0x01; 
#define OB_IO_OUTPUT_HIGH 		P00=1;  P0M |=0x01;

/**
 *	@Brief		main: ADC Test Demo Function
 *	@param		None
 *	@retval		None
 */

void main(void)
{
	/*	Initialize GPIO status	*/
	GPIO_Initialization();			

	/*	Initialize ADC status	*/
	ADC_Initialization();

	
	while(1)
	{
		/*	Loop ADC status	*/
		ADM	|= mskADM_ADC_START;	
	}
}


/**
 *	@Brief		Initialize GPIO status
 *	@param		None
 *	@retval		None
 */
void GPIO_Initialization(void)
{
	/*	Set whole IOs to output low	*/
	IO_PORT0_OUTPUT_LOW
	IO_PORT1_OUTPUT_LOW
	IO_PORT2_OUTPUT_LOW
}


/**
 *	@Brief		Initialize ADC
 *	@param		None
 *	@retval		None
 */
void ADC_Initialization(void)
{
	/*	Initializes and configures the ADC function	*/
	P1CON |= 0x10 ; //AIN0 /P14
  P1M   &= 0xEF ; //P14 input mode
  P1UR  &= 0xEF ; //P14 disable pull high
	ADM = mskADM_ADC_ENALBE | mskADM_ADC_CHANNLE_AIN0;
	
	/* Start calibration after 5 clocks */
	nop_();
  nop_();
  nop_();
  nop_();
	nop_();
	
	/* ADC Calibration */
	ADCAL|= ADCCal;         //ADC start calibration
	while(ADCAL & ADCCal);  //Check ADC calibration bit
	ADCAL|= ADCCovAddCal;   //ADC conversion with calibration value	
	
	ADR |= mskADR_ADC_CLOCK_FHOSC;
	ADCAL |= mskADR_ADC;
	ADR |= mskADR_ADC_GLOBALCHS;
	VREFH = ADCInRefVDD;
	
	/*	Enable ADC interrupt and global interrupt	*/
	IEN2 = mskIEN2_INT_ADC;
	EAL = 1;
	
	/*	Start to conveter ADC	*/
	ADM	|= mskADM_ADC_START;	
	
}
/**
 *	@Brief		ISR_Adc
 *						ADC interrupt service routine
 */
void ISR_Adc(void) interrupt ISRAdc
{		
	/*	Read ADB and ADR register to get ADC value	*/
	dbADC_DataBuf = (ADB <<4) | (ADR&0x0F);			

	/*	Observe the IO toggle to represent ADC interrupt was execute	*/
	OB_IO_OUTPUT_HIGH														
	OB_IO_OUTPUT_LOW
	ADM	|= mskADM_ADC_START;
}