/*********************************************************************
*Project:MG82F6B08_001_104-DEMO
*			MG82F6B08_001_104 SOP16_V11 EV Board (TH221A)
*			CpuCLK=8MHz, SysCLK=8MHz
*Description:
*			GPL Bit Order Reversed
*			GPL CRC calculate(CCIT16 CRC16 0x1021)		
*			GPL Flash automatic CRC
*Note:
*
*Creat time:
*Modify:
*    
*********************************************************************/
#define _MAIN_C

#include <Intrins.h>
#include <Absacc.h>

#include <Stdio.h>  // for printf

#include ".\include\REG_MG82F6B08_001_104.H"
#include ".\include\Type.h"
#include ".\include\API_Macro_MG82F6B08_001_104.H"
#include ".\include\API_Uart_BRGRL_MG82F6B08_001_104.H"


/*************************************************
*Set SysClk (MAX.24MHz)
*Selection: 
*	8000000,16000000
*	11059200,22118400
*************************************************/
#define MCU_SYSCLK		8000000
/*************************************************/
/*************************************************
*Set CpuClk (MAX.16MHz)
*	1) CpuCLK=SysCLK
*	2) CpuClk=SysClk/2
*************************************************/
#define MCU_CPUCLK		(MCU_SYSCLK)
//#define MCU_CPUCLK		(MCU_SYSCLK/2)

#define TIMER_1T_1ms_TH	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(1000000)))) /256) 			
#define TIMER_1T_1ms_TL	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(1000000)))) %256)

#define TIMER_12T_1ms_TH	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(12000000)))) /256) 			
#define TIMER_12T_1ms_TL	((65536-(u16)(float)(1000*((float)(MCU_SYSCLK)/(float)(12000000)))) %256)

#define LED_R		P32
#define LED_G_0		P33
#define LED_G_1		P46

code u8 TestBuf[16]={0xAA,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};


/*************************************************
*Function:     void DelayXus(u8 xUs)
*Description:  delay,unit:us
*Input:     u8 Us -> *1us  (1~255)
*Output:     
*************************************************/
void DelayXus(u8 xUs)
{
	while(xUs!=0)
	{
#if (MCU_CPUCLK>=11059200)
		_nop_();
#endif
#if (MCU_CPUCLK>=14745600)
		_nop_();
		_nop_();
		_nop_();
		_nop_();
#endif
#if (MCU_CPUCLK>=16000000)
		_nop_();
#endif

#if (MCU_CPUCLK>=22118400)
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
#endif
#if (MCU_CPUCLK>=24000000)
		_nop_();
		_nop_();
#endif		
#if (MCU_CPUCLK>=29491200)
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
#endif
#if (MCU_CPUCLK>=32000000)
		_nop_();
		_nop_();
#endif

		xUs--;
	}
}

/*************************************************
*Function:     void DelayXms(u16 xMs)
*Description:delay,unit:ms
*Input:     u16 xMs -> *1ms  (1~65535)
*Output:     
*************************************************/
void DelayXms(u16 xMs)
{
	while(xMs!=0)
	{
		CLRWDT();
		DelayXus(200);
		DelayXus(200);
		DelayXus(200);
		DelayXus(200);
		DelayXus(200);
		xMs--;
		
	}
}

/***********************************************************************************
*Function:void SendByte(u8 tByte)
*Description:Uart send byte
*Input: u8 tByte: the data to be send
*Output:     
*************************************************************************************/
void SendByte(u8 tByte)
{
	bit bES0;
	bES0=ES0;
	ES0=0;
	S0BUF=tByte;
	while(TI0==0);
	TI0=0;
	ES0=bES0;
}



/***********************************************************************************
*Function:void SendStr(u8* PStr)
*Description:Uart send string
*Input: u8* PStr:the string to be send
*Output:     
*************************************************************************************/
void SendStr(u8* PStr)
{
	while(*PStr != 0)
	{
		SendByte(*PStr);
		PStr ++;
	}
}

/***********************************************************************************
*Function:   void SendHex(u8 ToSend)
*Description:Uart send data for HEX
*Input: u8 ToSend: the data to be send 
*Output:     
*************************************************************************************/
void SendHex(u8 ToSend)
{
	u8 x;
//	SendByte(' ');
//	SendByte('0');
//	SendByte('x');
	x = ToSend >> 4;
	if(x < 10)
	{
		SendByte('0'+x);
	}
	else
	{
		SendByte('A'-10+x);
	}
	x= ToSend&0x0F;
	if(x < 10)
	{
		SendByte('0'+x);
	}
	else
	{
		SendByte('A'-10+x);
	}
}

/***********************************************************************************
*Function:   void SendDW2DEC(u8 ToSend)
*Description:Uart send data for DEC
*Input: u32 ToSend: the data to be send 
*Output:     
*************************************************************************************/
void SendDW2DEC(u32 ToSend)
{
	bit bFlag;
	u8 x;
	bFlag=0;
	x=ToSend/1000000000L;
	ToSend=ToSend%1000000000L;
	if(x!=0)
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/100000000L;
	ToSend=ToSend%100000000L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/10000000L;
	ToSend=ToSend%10000000L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/1000000L;
	ToSend=ToSend%1000000L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/100000L;
	ToSend=ToSend%100000L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/10000L;
	ToSend=ToSend%10000L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/1000L;
	ToSend=ToSend%1000L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/100L;
	ToSend=ToSend%100L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend/10L;
	if((x!=0)||(bFlag==TRUE))
	{	bFlag=TRUE;
		SendByte('0'+x);
	}
	
	x=ToSend%10L;
	SendByte('0'+x);
		
}

/***********************************************************************************
*Function:   void ResetCounter()
*Description:Reset counter
*Input:  
*Output:     
*************************************************************************************/
void ResetCounter()
{
	// Close T0,T1
	TM_GlobalSTOP(TIMER0_GLOBAL_BIT|TIMER1_GLOBAL_BIT);
	TM_SetT0HighByte(0);
	TM_SetT0LowByte(0);
	TM_SetT1HighByte(0);
	TM_SetT1LowByte(0);
	// Start T0,T1
	TM_GlobalStart(TIMER0_GLOBAL_BIT|TIMER1_GLOBAL_BIT);
}
/***********************************************************************************
*Function:   void GetCounter()
*Description:Get counter
*Input:  
*Output:     
*************************************************************************************/
u32 GetCounter()
{
	DWordTypeDef dwTime;
	TM_GlobalSTOP(TIMER0_GLOBAL_BIT|TIMER1_GLOBAL_BIT);
	dwTime.B.BHigh=TH0;
	dwTime.B.BMHigh=TL0;
	dwTime.B.BMLow=TH1;
	dwTime.B.BLow=TL1;
	return dwTime.DW;
}

/***********************************************************************************
*Function:   void InitTimer0(void)
*Description:Initialize Timer0
*Input:   
*Output:     
*************************************************************************************/
void InitTimer0(void)
{
	TM_SetT0Mode_1_16BIT_TIMER();			// TIMER0 Mode: 16-bit
	TM_SetT0Clock_T1OF();					// T0 Clock: T1OF
	TM_SetT0Gate_Disable();
	TM_SetT0LowByte(0);						// Set TL0 value
	TM_SetT0HighByte(0);					// Set TH0 value
	//TM_EnableT0();						// Enable T0
}

/***********************************************************************************
*Function:   void InitTimer1(void)
*Description:Initialize Timer1
*Input:   
*Output:     
*************************************************************************************/
void InitTimer1(void)
{
	TM_SetT1Mode_1_16BIT_TIMER();			// T1 Mode: 16-bit
	TM_SetT1Clock_SYSCLKDiv12();			// T1 Clock: SYSCLK/12
	TM_SetT1Gate_Disable();
	TM_SetT1LowByte(0);						// Set TL1 value
	TM_SetT1HighByte(0);					// Set TH1 value
	//TM_EnableT1();						// Enable T1
}

/***********************************************************************************
*Function:   void InitUart0_S0BRG(void)
*Description:   Initialize Uart0, The source of baud rate was S0BRG
*Input:   
*Output:     
*************************************************************************************/
void InitUart0_S0BRG(void)
{
	
	UART0_SetAccess_S0CR1();			// Set SFR 0xB9 address to access S0CR1
	UART0_SetMode8bitUARTVar();			// 8-bit, Variable B.R.
	UART0_EnReception();				// Enable reception
	UART0_SetBRGFromS0BRG();			// B.R. source: S0BRG
	UART0_SetS0BRGBaudRateX2();			// S0BRG x2
	UART0_SetS0BRGSelSYSCLK();			// S0BRG clock source:SYSCLK

	// Set S0BRG Value
	UART0_SetS0BRGValue(S0BRG_BRGRL_9600_2X_8000000_1T);
	
	UART0_EnS0BRG();					// Enable S0BRG
}

/***********************************************************************************
*Function:   void InitPort(void)
*Description:   Initialize IO Port
*Input:   
*Output:     
*************************************************************************************/
void InitPort(void)
{
	PORT_SetP3QuasiBi(BIT0|BIT1|BIT2|BIT3);		// Set P30,P31,P32,P33 as Quasi-Bidirectional,for RXD/TXD,LED
	PORT_SetP4OpenDrainPu(BIT6);				// Set P46 as Open-Drain with pull-up resistor,for LED
}

/***********************************************************************************
*Function:   void InitClock(void)
*Description:   Initialize clock	
*Input:   
*Output:     
*************************************************************************************/
void InitClock(void)
{
#if (MCU_SYSCLK==8000000)
	// Default: IHRCO=16MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK/2
#endif

#if (MCU_SYSCLK==11059200)
	// IHRCO=22.12MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK/2
	CLK_SelIHRCO_22118400Hz();
#endif
	
#if (MCU_SYSCLK==16000000)
	// IHRCO=16MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK
	CLK_SetCKCON3(WDTCS_ILRCO|FWKP_NORMAL_120uS|MCKDO_MCK_DIV_1);
#endif

#if (MCU_SYSCLK==22118400)
	// IHRCO=22.12MHz, OSCin=IHRCO,MCK=OSCin,MCKDO=MCK
	CLK_SelIHRCO_22118400Hz();
	CLK_SetCKCON3(WDTCS_ILRCO|FWKP_NORMAL_120uS|MCKDO_MCK_DIV_1);
#endif
	

#if (MCU_CPUCLK==MCU_SYSCLK)
	CLK_SetCpuclk_Sysclk();
#else
	CLK_SetCpuclk_SysclkDiv2();
#endif

	// P45 ouput MCK/4
	//CLK_P45OC_MCKDiv4();
}



/***********************************************************************************
*Function:   void InitSystem(void)
*Description:   Initialize MCU
*Input:   
*Output:     
*************************************************************************************/
void InitSystem(void)
{
	InitPort();
	InitClock();
	InitUart0_S0BRG();
	InitTimer0();
	InitTimer1();
}

/***********************************************************************************
*Function:   u16 CRC16_CCIT(u8 *ptr,u16 len)
*Description:calculation CRC16 by software
*Input:   
*		 u8 *pBuf: the Buffer to be CRC
*		 u16 len: the length of Buffer
*Output:u16: CRC16 value     
*************************************************************************************/
u16 CRC16_CCIT(u8 *ptr,u16 len)
{
	u16 wCRCin = 0x0000;
	u16 wCPoly = 0x1021;
	u16 wChar=0;
	u16 i;
	u8 x;
	for(i=0;i<len;i++)
	{
		wChar=(ptr[i])&0x00FF;
		wCRCin=wCRCin^(wChar<<8);
		for(x=0;x<8;x++)
		{
			if((wCRCin&0x8000)!=0)
			{
				wCRCin=wCRCin<<1;
				wCRCin=wCRCin^wCPoly;
			}
			else
			{
				wCRCin=wCRCin<<1;
			}
		}
	}
    return wCRCin;
}

/***********************************************************************************
*Function:   u16 GPL_CRC(u8 *pBuf,u8 len)
*Description:calculation CRC16 by HW
*Input:   
*		 u8 *pBuf: the Buffer to be CRC
*		 u8 len: the length of Buffer 
*Output:u16: CRC16 Value     
*************************************************************************************/
u16 GPL_CRC(u8 *pBuf,u8 len)
{
	WordTypeDef CRCValue;
	u8 i;
	// Set CRC Seed
	GPL_CRC_WriteCRCSeedH(0x00);
	GPL_CRC_WriteCRCSeedL(0x00);
	
	for(i=0;i<len;i++)
	{
		GPL_CRC_WriteCRCData(pBuf[i]);
	}
	GPL_CRC_ReadCRCResultH(CRCValue.B.BHigh);
	GPL_CRC_ReadCRCResultL(CRCValue.B.BLow);
	return CRCValue.W;
}

/***********************************************************************************
*Function:   u16 GPL_AutoFlashCRC(u16 StartAddr,u16 EndAddr)
*Description:Read P page sfr
*Input:   
*		 u16 StartAddr: Flash start address
*		 u16 EndAddr: Flash end address(The last byte of the flash page. 
*							Ex: ....0x03FF,0x05FF,0x07FF,0x09FF,0x0BFF,0x0DFF,0x0FFF)
*Output:u16: CRC16 Value     
*************************************************************************************/
u16 GPL_AutoFlashCRC(u16 StartAddr,u16 EndAddr)
{
	WordTypeDef CRCValue;
	bit bEA=EA;
	// Set CRC Seed
	GPL_CRC_WriteCRCSeedH(0x00);
	GPL_CRC_WriteCRCSeedL(0x00);

	GPL_CRC_CRC0DA_DataIn();
	
	// Set End address, Defined by IAPLB
	EA = 0; 					//Disable interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= IAPLB_P;			//set sfr address;
	IFD= (EndAddr>>8)&0xFE;		//Set sfr data
	IFMT = ISP_WRITE_P;
	ISPCR = 0x80;				//Enable ISP/IAP
	SCMD = 0x46;
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//Clear ISPCR
	// Set Start address
	IFADRH = StartAddr/256; 	//Address high byte
	IFADRL= StartAddr%256;		//Address low byte
	IFMT = ISP_AUTO_FLASH_CRC;
	ISPCR = 0x80;				//Enable ISP/IAP
	SCMD = 0x46;
	SCMD = 0xB9;
	nop();
	GPL_CRC_ReadCRCResultH(CRCValue.B.BHigh);
	GPL_CRC_ReadCRCResultL(CRCValue.B.BLow);
	IFMT=0;
	ISPCR = 0;					//Clear ISPCR
	EA = bEA;					//restore interrupt
	return CRCValue.W;
}

void main()
{
	WordTypeDef CRCValue;
	u8 TestBorev;
	DWordTypeDef dwTime;
	unsigned char volatile code *pCode;

	InitSystem();

	SendStr("\nStart GPL Test!");

	LED_G_1=0;LED_R=0;
	DelayXms(1000);
	LED_G_1=1;LED_R=1;	

	// Bit Order Reversed
	TestBorev=0x46;
	SendStr("\nBorev old:0x");
	SendHex(TestBorev);
	GPL_BOREV(TestBorev);
	SendStr("\nBorev new:0x");
	SendHex(TestBorev);

	
	// Calculate CRC16 of the FLASH 0x0000~0x3FFF
	ResetCounter();
	CRCValue.W=GPL_AutoFlashCRC(0x0000, (1024-1));
	dwTime.DW=GetCounter();
	SendStr("\nHW 1KFlash CRC16 Value:0x");
	SendHex(CRCValue.B.BHigh);
	SendHex(CRCValue.B.BLow);
	SendStr("; Time:");
	SendDW2DEC(dwTime.DW);

	// Software Calculate CRC16 of the FLASH 0x0000~0x3FFF
	pCode=0x0000;
	ResetCounter();
	CRCValue.W=CRC16_CCIT(pCode, 1024);
	dwTime.DW=GetCounter();
	SendStr("\nSW 1KFlash CRC16 Value:0x");
	SendHex(CRCValue.B.BHigh);
	SendHex(CRCValue.B.BLow);
	SendStr("; Time:");
	SendDW2DEC(dwTime.DW);
	
	// Calculate CRC16 of TestBuf[16]
	ResetCounter();
	CRCValue.W=GPL_CRC(TestBuf,16);
	dwTime.DW=GetCounter();
	SendStr("\nHW TestBuf[16] CRC16 Value:0x");
	SendHex(CRCValue.B.BHigh);
	SendHex(CRCValue.B.BLow);
	SendStr("; Time:");
	SendDW2DEC(dwTime.DW);
	
	// Software Calculate CRC16 of TestBuf[16]
	ResetCounter();
	CRCValue.W=CRC16_CCIT(TestBuf,16);
	dwTime.DW=GetCounter();
	SendStr("\nSoft TestBuf[16] CRC16 Value:0x");
	SendHex(CRCValue.B.BHigh);
	SendHex(CRCValue.B.BLow);
	SendStr("; Time:");
	SendDW2DEC(dwTime.DW);
	while(1)
	{
		DelayXms(100);
		LED_G_0 = !LED_G_0;
	}

}


