/*******************************************************************************
* 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=CMP1CON2&0XF8;
	CMP1CON2= tmp|OFFSET;
}

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

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

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

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

	for(i=0;i<=7;i++)      //从0到7找翻转点
	{
		Cmp_Offset(i);
		__delay_us(500);
		// printf("1_1 = 0x%02x,\r\n",i);
		if(CMP1OUT != 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 = CMP1OUT;
	for(i=8;i>0;i--)       //从7到0找翻转点
	{
		Cmp_Offset(i-1);
		__delay_us(500);

		if(CMP1OUT != 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);    //填入校准值
	CMP1CON2&=0XEF;		  //关闭校准

}

void CMP1_init(void)
{
    TRISA1 = 1;PA1PD = 1;PA1PU = 1;PA1AEN = 1;	//Pch_PA1
    TRISA2 = 1;PA2PD = 1;PA2PU = 1;PA2AEN = 1;	//Nch_PA2
    TRISD6 = 0;PD6PD = 1;PD6PU = 1;PD6AEN = 0;
    CMPCLKEN = 1;
    Cmp_CAL();
    CMP1CON0 = 0x8B;    //使能CMP1,P->PA1，N->PA2
    CMP1CON1 =0x05;     //CMP1OUT -> PD6

}

void INTER_init(void)
{
    CMP1IF=0;
    CMP1IE=1;
    CMP1IP=0;	//CMP1高优先级

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