/*******************************************************************************
* Device      : AD18F06A
* Author      : XAD Application Team
* Version     : V0.0.1
* Date        : 20201201
* Description : 系统外设驱动函数
********************************************************************************/

/********************************INCLUDES*************************************/
#include "Periph.h"


void GPIO_Init()
{
	PAOD = 0X00;
	PBOD = 0X00;
	PCOD = 0X00;
	PDOD = 0X00;

	PAPU = 0XFF;	//
	PBPU = 0XFF;	//
	PCPU = 0XFF;	//
	PDPU = 0XFF;	//

	PAPD = 0XFF;
	PBPD = 0XFF;
	PCPD = 0XFF;
	PDPD = 0XFF;

	TRISA=0X00;	 	//
	TRISB=0X00;	 	//PB0_
	TRISC=0X00;		//PC0
	TRISD=0X00;		//PC0

	PORTA=0X00;
	PORTB=0X00;	//PB1_RX，PB0_TX
	PORTC=0X00;
	PORTD=0X00;

	PDSINKCUR=0X00;	//PORTD_SINK,0-20mA,1-60mA
	CURCON=0XFF;	//PORTA/B/C_Isource选择：<1:0>PACUR,<3:2>PBCUR,<5:4>PCCUR:	1-6mA,2/0-3mA,3-12mA

}

void Cmp_Offset(unsigned char OFFSET)
{
	unsigned char tmp=0;
	tmp=CMP0CON2&0XF8;
	CMP0CON2= tmp|OFFSET;
}

//每次校准只需选择同相端
void Cmp_CAL()
{
	unsigned char VOOS1 = 0,start = 0;
	unsigned char i = 0;

	CMP0CON2|=0x10;	//使能校准

	Cmp_Offset(0);
	__delay_us(500);
	start =CMP0OUT;

	if(start == 1)
	{
		CMP0CON2 &= 0XF7;	//校准负值
	}
	else
	{
		CMP0CON2 |= 0X08;	    //校准正值
	}

	for(i=0;i<=7;i++)      //从0到7找翻转点
	{
		Cmp_Offset(i);
		__delay_us(500);
		// printf("1_1 = 0x%02x,\r\n",i);
		if(CMP0OUT != start)
		{
			// printf("V1_1 \r\n");
			VOOS1 = i;
			break;
		}
	}
	// printf("VOOS1_1 = 0x%02x,\r\n",VOOS1);
	Cmp_Offset(7);         ////切换状态值并记录OP0OUT初始状态值
	__delay_us(500);
	start = CMP0OUT;
	for(i=8;i>0;i--)       //从7到0找翻转点
	{
		Cmp_Offset(i-1);
		__delay_us(500);
		// printf("1_2 = 0x%02x,\r\n",i-1);
		if(CMP0OUT != start)
		{
			// printf("V1_2 \r\n");
			VOOS1 =(VOOS1+ i-1)/2;
			break;
		}
	}
	// printf("VOOS1_2 = 0x%02x,\r\n",i-1);
	// printf("VOOS1 = 0x%02x,\r\n",VOOS1);

	Cmp_Offset(VOOS1);    //填入校准值
	CMP0CON2&=0XEF;		  //关闭校准

}
void CMP0_init(void)
{
    TRISA1=1; PA1PD=1; PA1PU=1;PA1AEN=1;	//Pch_PA1
    TRISA3=1; PA3PD=1; PA3PU=1;PA3AEN=1;	//Nch_PA3
    TRISD2=0; PD2PD=1; PD2PU=1;PD2AEN=0;    //Output_PD2

    CMPCLKEN=1;
    Cmp_CAL();
    CMP0CON1 =  0x05;       //使能PD2为cmpout输出 IO
    CMP0CON0 =  0x93;       //使能CMP0,P ->PA1，N->PA3
}
void INTER_init(void)
{
    CMP0IF=0;
    CMP0IE=1;
    CMP0IP=0;	//CMP0高优先级

    IPEN=1;		//使能优先级分级
    GIEH=1;		//使能高优先级
    GIEL=1;
}
