/*********************************************************************
*    Project: MG82F5B32-DEMO
*			MG82F5B32 LQFP32_V10 EV Board (TH156A)
*			CpuCLK=12MHz, SysCLK=12MHz
*    Description:
*			read UID
*
*    Note:
*
*    Creat time:
*    Modify:
*    
*********************************************************************/
#define _MAIN_C

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

#include <Stdio.h>  // for printf

#include ".\include\REG_MG82F5Bxx.H"
#include ".\include\Type.h"
#include ".\include\API_Macro_MG82F5B32.H"
#include ".\include\API_Uart_BRGRL_MG82F5B32.H"

/*************************************************
*Set SysClk (MAX.50MHz)
*Selection:
*	11059200,12000000,
*	22118400,24000000,
*	29491200,32000000,
*	44236800,48000000
*************************************************/
#define MCU_SYSCLK		12000000
/*************************************************/
/*************************************************
*Set CpuClk (MAX.32MHz)
*	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_G_0		P25
#define LED_R		P26
#define LED_G_1		P27

#define ISP_ADDRESS    0xFE00	 //ISP start address
#define IAP_ADDRESS    0xF600	 //IAP start address 

#define UID_ENCRYPT_BUF_ADDRESS	0x1000
#define DEVICE_SN_BUF_ADDRESS	0x0200


code u8 UIDEncryptBuf[16] _at_ UID_ENCRYPT_BUF_ADDRESS;

// Set serial number.Can use U1/U2 to write serial number.
// Start address set to the variable below (ex:0x0200)
// If the serial number is not in the correct address,means the programm may be stolen.
code u8 DeviceSn[16] _at_ DEVICE_SN_BUF_ADDRESS;

// U1/U2 serial number are 12bit+4bytes data
// Ckecking if the 12-bit data match
code u8 DeviceSnString[]="Megawin--MCU";

/*************************************************
*Function: 		char putchar (char c)   
*Description: 	send for printf
*Input:    		char c
*Output:     
*************************************************/
char putchar (char c)   
{      
	bit bES;
	bES=ES0;
    ES0=0;        
    S0BUF = c;        
    while(TI0==0);        
    TI0=0;        
    ES0=bES;        
    return 0;
}

/*************************************************
*Function:     	void DelayXus(u16 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 InitUart0_S1BRG()
*Description:	Initialize Uart0, The source of baud rate was S1BRG
*Input:   
*Output:   		
*************************************************************************************/
void InitUart0_S1BRG(void)
{	
	UART0_SetMode8bitUARTVar();			// UART0 Mode: 8-bit, Variable B.R.
	UART0_EnReception();				// Enable reception
	UART0_SetBRGFromS1BRG();			// B.R. source: S1BRG
	UART0_SetS1BRGBaudRateX2();			// S1BRG x2
	UART1_SetS1BRGSelSYSCLK();			// S1BRG clock source: SYSCLK

    // Sets B.R. value
	UART1_SetS1BRGValue(S1BRG_BRGRL_9600_2X_12000000_1T);
	
	UART1_EnS1BRG();					// Enable S1BRG
}

/***********************************************************************************
*Function:   	void InitPort()
*Description:	Initialize IO Port
*Input:   
*Output:   		
*************************************************************************************/
void InitPort(void)
{
	PORT_SetP2OpenDrain(BIT4|BIT5|BIT6|BIT7);			// Set P24,P25,P26,P27 as open drain
	PORT_EnP24P25P26P27PullHigh();						// Enable P24,P25,P26,P27 pull-high
}

/***********************************************************************************
*Function:   	void InitClock()
*Description:	Initialize clock
*Input:   
*Output:   		
*************************************************************************************/
void InitClock(void)
{
#if (MCU_SYSCLK==11059200)
#if (MCU_CPUCLK==MCU_SYSCLK)
	// SysClk=11.0592MHz CpuClk=11.0592MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1);
	
#else
	// SysClk=11.0592MHz CpuClk=5.5296MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1);
#endif
#endif

#if (MCU_SYSCLK==12000000)
#if (MCU_CPUCLK==MCU_SYSCLK)
	// SysClk=12MHz CpuClk=12MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1);
	
#else
	// SysClk=12MHz CpuClk=6MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1);
#endif
#endif

#if (MCU_SYSCLK==22118400)
#if (MCU_CPUCLK==MCU_SYSCLK)
	// SysClk=22.1184MHz CpuClk=22.1184MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx4, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X4|OSCIn_IHRCO);
#else
	// SysClk=22.1184MHz CpuClk=11.0592MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx4, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X4|OSCIn_IHRCO);
#endif
#endif

#if (MCU_SYSCLK==24000000)
#if (MCU_CPUCLK==MCU_SYSCLK)
	// SysClk=24MHz CpuClk=24MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx4, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X4|OSCIn_IHRCO);
#else
	// SysClk=24MHz CpuClk=12MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx4, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X4|OSCIn_IHRCO);
#endif
#endif

#if (MCU_SYSCLK==29491200)
#if (MCU_CPUCLK==MCU_SYSCLK)
	// Cpuclk high speed
	CLK_SetCpuCLK_HighSpeed();
	// SysClk=29.491200MHz CpuClk=29.491200MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx5.33, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X533|OSCIn_IHRCO);
#else
	// SysClk=29.491200MHz CpuClk=14.7456MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx5.33, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X533|OSCIn_IHRCO);
#endif
#endif

#if (MCU_SYSCLK==32000000)
#if (MCU_CPUCLK==MCU_SYSCLK)
	// Cpuclk high speed
	CLK_SetCpuCLK_HighSpeed();
	// SysClk=32MHz CpuClk=32MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx5.33, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X533|OSCIn_IHRCO);
#else
	// SysClk=32MHz CpuClk=16MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx5.33, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X533|OSCIn_IHRCO);
#endif
#endif

#if (MCU_SYSCLK==44236800)
	// SysClk=44.2368MHz CpuClk=22.1184MHz
	CLK_SetCKCON0(IHRCO_110592MHz|CPUCLK_SYSCLK_DIV_1|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx8, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X8|OSCIn_IHRCO);
#endif

#if (MCU_SYSCLK==48000000)
	// SysClk=48MHz CpuClk=24MHz
	CLK_SetCKCON0(IHRCO_12MHz|CPUCLK_SYSCLK_DIV_2|SYSCLK_MCKDO_DIV_1|ENABLE_CKM|CKM_OSCIN_DIV_2);
	DelayXus(100);
	// IHRCO, MCK=CKMIx8, OSCin=IHRCO
	CLK_SetCKCON2(ENABLE_IHRCO|MCK_CKMI_X8|OSCIn_IHRCO);
#endif

	// P60 output MCK/4
	//CLK_P60OC_MCKDiv4();
}

/***********************************************************************************
*Function:		u8 IAP_ReadPPage(u8 PsfrAddr)
*Description:	Read P page sfr
*Input:   		u8 PsfrAddr: sfr Address
*Output:        u8 : sfr data
*************************************************************************************/
u8 IAP_ReadPPage(u8 PsfrAddr)
{
	bit bEA=EA;
	EA = 0; 					//Turn off interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= PsfrAddr;			//sfr Address
	IFMT = ISP_READ_P;
	ISPCR = 0x80;				//Enable ISP/IAP
	SCMD = 0x46;
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//clear
	EA = bEA;					//restore interrupt
	return IFD;
}

/***********************************************************************************
*Function:		void IAP_WritePPage(u8 PsfrAddr,u8 PsfrData)
*Description:	write P page sfr
*Input:   
*		 		u8 PsfrAddr: sfr Address
*		 		u8 PsfrData: sfr data
*Output:     
*************************************************************************************/
void IAP_WritePPage(u8 PsfrAddr,u8 PsfrData)
{
	bit bEA=EA;
	EA = 0; 					//Turn off interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= PsfrAddr;			//sfr Address
	IFD= PsfrData;				//sfr data
	IFMT = ISP_WRITE_P;
	ISPCR = 0x80;				//Enable ISP/IAP
	SCMD = 0x46;
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//clear
	EA = bEA;					//restore interrupt
}

/***********************************************************************************
*Function:u8 	IAP_ReadByte(u16 ByteAddr)
*Description:	read one byte from IAP
*Input:   
*		 		u16 ByteAddr: IAP Address
*Output:     	u8: the data from IAP 
*************************************************************************************/
u8 IAP_ReadByte(u16 ByteAddr)
{
		bit bEA=EA;
		IFADRH = ByteAddr>>8;		//IAP Address High byte
		IFADRL= ByteAddr;			//IAP Address Low byte
		EA = 0;						//Turn off interrupt
		IFMT = ISP_READ;
		ISPCR = 0x80; 				//Enable ISP/IAP
		SCMD = 0x46;
		SCMD = 0xB9;
		IFMT=0;
		ISPCR = 0;					//clear
		EA = bEA; 					//restore interrupt
		return IFD;
}
// Can use MOVC to read IAP
#define	IAP_ReadByteByMOVC(x)	CBYTE[x]

/***********************************************************************************
*Function:   	void IAP_ErasePage(u8 ByteAddr)
*Description:	Erase one page(about 30ms) 
*Input:   		u8 ByteAddr: IAP Address High byte
*Output:   		
*************************************************************************************/
void IAP_ErasePage(u8 ByteAddr)
{
		bit bEA=EA;
		IFADRH = ByteAddr;		//IAP Address High byte
		IFADRL= 0x00;			//IAP Address Low byte
		EA = 0;					//Turn off interrupt
		IFMT = ISP_ERASE;
		ISPCR = 0x80; 			//Enable ISP/IAP
		SCMD = 0x46;
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;					//clear
		EA = bEA; 					//restore interrupt
}

/***********************************************************************************
*Function:   	void IAP_WriteByte(u16 ByteAddr,u8 ByteData)
*Description:	write one byte to IAP(about 80us).Data in the address should be 0xFF.
*				Otherwise,the address should be erease first.  
*Input:   		u16 ByteAddr: IAP Address
*				u8 ByteData: the data to be write
*Output:   		
*************************************************************************************/
void IAP_WriteByte(u16 ByteAddr,u8 ByteData)
{
		bit bEA=EA;
		IFD = ByteData;				//data to be write		
		IFADRH = ByteAddr>>8;		//IAP address high
		IFADRL= ByteAddr;			//IAP address low
		EA = 0;						//Turn off interrupt
		IFMT = ISP_WRITE;
		ISPCR = 0x80;               //Enable ISP/IAP
		SCMD = 0x46;
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;					//clear
		EA = bEA; 					//restore interrupt
}

/***********************************************************************************
*Function:   	void IAP_ReadUID(u8 *pUID)
*Description:	read UID
*Input:   		u8 *PUID: Address of the buffer  
*Output:     
*************************************************************************************/
void IAP_ReadUID(u8 *pUID)
{
	u8 i;
	ISPCR=0x80;
	IFMT=0x09;
	IFADRH=0;
	IFADRL=0xF0;
	
	for(i = 0; i < 16; i ++)
	{
		SCMD=0x46;
		SCMD=0xB9;
		pUID[i]=IFD;
		IFADRL++;
	}
	IFMT=0;
	ISPCR = 0x00;
}

/***********************************************************************************
*Function:   u8 UID_Encrypt(void)
*Description:Encrypt by UID
*Input:   
*Output:0:Pass, other:Fail   
*************************************************************************************/
u8 UID_Encrypt(void)
{
	xdata u8 UID[16]; 
	u8 i;

	IAP_ReadUID(&UID[0]);

	for(i=0;i<16;i++)
	{
		if(UIDEncryptBuf[i]!=0xFF) break;
	}
	if(i<16)
	{ // There are encrypted bytes stored, compare data
		for(i=0;i<16;i++)
		{
			if(UID[i] != UIDEncryptBuf[i]) break;
		}
		if(i<16)
		{ // comparison error
			return i+1;
		}
		else
		{
			return 0;
		}
	}
	else
	{ // All 0xFF, no save UID
		IAP_WritePPage(IAPLB_P,UID_ENCRYPT_BUF_ADDRESS/256);
		for(i=0;i<16;i++)
		{
			IAP_WriteByte(UID_ENCRYPT_BUF_ADDRESS+i, UID[i]);
		}
		IAP_WritePPage(IAPLB_P,ISP_ADDRESS/256);
		return 0;
	}

	return 0;
	
	
}

/***********************************************************************************/

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

void main()
{

	u8 i;
	bit bUIDEncryptFlag,bDeviceStringFlag;
	
    InitSystem();
	
	printf("\nHello!!");
	
	LED_G_0=0;LED_G_1=0;LED_R=0;
	DelayXms(1000);
	LED_G_0=1;LED_G_1=1;LED_R=1;

	// Check whether the UID match
	if(UID_Encrypt()!=0)
	{ // FAIL
		printf("\nUID Test Fail!!");
		bUIDEncryptFlag=FALSE;
	}
	else
	{ // PASS
		printf("\nUID Test Pass!!");
		bUIDEncryptFlag=TRUE;
		LED_G_0=0;
	}

	// Check whether the serial number match
	bDeviceStringFlag=TRUE;
	for(i=0;i<12;i++)
	{
		if(DeviceSnString[i] != DeviceSn[i])
		{ //FAIL
			bDeviceStringFlag=FALSE;
		}
	}

	if(bDeviceStringFlag)
	{
		printf("\nDeviceSN Test Pass!!");
		LED_G_1=0;
	}
	else
	{
		printf("\nDeviceSN Test Fail!!");
	}
	
    while(1)
	{	
		LED_R=!LED_R;
		DelayXms(100);
    }
	
}
