/*********************************************************************
*Project:MG82F6B08_001_104-DEMO
*			MG82F6B08_001_104 SOP16_V11 EV Board (TH221A)
*			CpuCLK=8MHz, SysCLK=8MHz
*Description:
*			IAP Test
*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

#define IO_KEY_SAVE_0			P10
#define IO_KEY_SAVE_1			P30


#define ERR_CNT_MAX		4		// Error, Try again times


#define ISP_ADDRESS    0x1A00	 //ISP Start address 
#define IAP_ADDRESS    0x1600	 //IAP Start address  
idata u8 TrapFlag[3];

#define TEST_WRITE_BUF_IAP_ADDRESS_0    0x1600	 // Test writing Buf to IAP starting address
#define TEST_WRITE_BUF_IAP_ADDRESS_1    0x1610	 // Test writing Buf to IAP starting address
xdata u8 TestBuf[16];

/*************************************************
*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(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 CheckTrapFlag(void)
*Description:   	Check the IAP operation whether is Right
*			If TrapFlag != 'Win',then the IAP operation is wrong,MCU reset
*Input:   	
*Output:     
*************************************************************************************/
void CheckTrapFlag(void)
{ 
	if ((TrapFlag[0]!='W')||(TrapFlag[1]!='i')||(TrapFlag[2]!='n'))
	{
		//MCU Reset
	//	POW_ResetToAP();
	}
}

/***********************************************************************************
*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; 					//Disable interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= PsfrAddr;			//set sfr address;
	IFMT = ISP_READ_P;
	ISPCR = 0x80;				//Enable ISP/IAP
//	CheckTrapFlag();
	SCMD = 0x46;
//	CheckTrapFlag();
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//Clear ISPCR
	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; 					//Disable interrupt
	IFADRH = 0; 				//IFADRH must be 0
	IFADRL= PsfrAddr;			//set sfr address;
	IFD= PsfrData;				//Set sfr data
	IFMT = ISP_WRITE_P;
	ISPCR = 0x80;				//Enable ISP/IAP
//	CheckTrapFlag();
	SCMD = 0x46;
//	CheckTrapFlag();
	SCMD = 0xB9;
	nop();
	IFMT=0;
	ISPCR = 0;					//Clear ISPCR
	EA = bEA;					//restore interrupt
}

/***********************************************************************************
*Function:u8 IAP_ReadByte(u16 ByteAddr)
*Description:read one byte from IAP
*Input:u16 ByteAddr: IAP Address   
*Output:     
*************************************************************************************/
u8 IAP_ReadByte(u16 ByteAddr)
{
		bit bEA=EA;
		IFADRH = ByteAddr>>8;		//Set address high byte
		IFADRL= (u8)(ByteAddr);			//Set address low byte;
		EA = 0;						//Disable interrupt
		IFMT = ISP_READ;
		ISPCR = 0x80; 				//Enable ISP/IAP
//		CheckTrapFlag();
		SCMD = 0x46;
//		CheckTrapFlag();
		SCMD = 0xB9;
		IFMT=0;
		ISPCR = 0;					//Clear ISPCR
		EA = bEA; 					//restore interrupt
		return IFD;
}
// Can use MOVC to read IAP
#define	IAP_ReadByteByMOVC(x)	CBYTE[x]

/***********************************************************************************
*Function:void IAP_ErasePage(u16 ByteAddr)
*Description:Erase one page
*Input:u8 ByteAddr: IAP Address   
*************************************************************************************/
void IAP_ErasePage(u16 ByteAddr)
{
		bit bEA=EA;
		IFADRH = (u8)(ByteAddr>>8);				//Set address high byte
		IFADRL= (u8)(ByteAddr)&B11000000;		//Set address low byte;
		EA = 0;									//Disable interrupt
		IFMT = ISP_ERASE;
		ISPCR = 0x80; 							//Enable ISP/IAP
//		CheckTrapFlag();
		SCMD = 0x46;
//		CheckTrapFlag();
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;								//Clear ISPCR
		EA = bEA; 								//restore interrupt
}

/***********************************************************************************
*Function:		u8 IAP_WriteBuf_With_Verify_Protect(u16 ByteAddr,u8 *pBuf,u8 Cnt)
*Description:	Write data to IAP
*		 	    use 64 bytes XDATA to save orgin IAP data.
*Input:  u16 ByteAddr: IAP Address, u8 *pBuf: The data buf to be write,u8 Cnt: Length to be write(<64) 
*Output:u8  0->succeed, other->failure     
*************************************************************************************/
u8 IAP_WriteBuf_With_Verify_Protect(u16 ByteAddr,u8 *pBuf,u8 Cnt)
{
		xdata u8 TempBuf[64];
		u16 i;
		u8 ErrCnt;
		WordTypeDef SectorAddr;
		bit bEA=EA;

		// read orgin data to XDATA
		ErrCnt=0;
		
		SectorAddr.W=ByteAddr&0xFFC0;
		for(i=0;i<64;i++)
		{
			TempBuf[i]=IAP_ReadByte(SectorAddr.W);
			SectorAddr.W++;
		}
		// modify data which to be write
		i=ByteAddr&0x003F;
		while(Cnt!=0)
		{
			TempBuf[i]=*pBuf;
			pBuf++;
			i++;
			Cnt--;
		}
	P_Err_Loop:
		// Erase page
		SectorAddr.W=ByteAddr&0xFE00;
		IAP_ErasePage(SectorAddr.W);
		
		// write data to IAP		
		EA = 0;								//Disable interrupt
		
		ISPCR = 0x80;               		//Enable ISP/IAP
		IFMT = ISP_BYTE_WRITE;				//Byte write mode
		
		for(i=0;i<64;i++)
		{
			IFADRH= SectorAddr.B.BHigh;		//Set address high byte
			IFADRL= SectorAddr.B.BLow; 		//Set address low byte;
			IFD = TempBuf[i]; 				//Set data to be wite 
			//		CheckTrapFlag();
			SCMD = 0x46;
			//		CheckTrapFlag();
			SCMD = 0xB9;
			nop();
			SectorAddr.W++;
		}
		IFMT = ISP_PAGE_WRITE;				//Page write mode
		//CheckTrapFlag();
		SCMD = 0x46;
		//CheckTrapFlag();
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;							//Clear ISPCR

		EA = bEA; 							//restore interrupt

		// Verify
		SectorAddr.W=ByteAddr&0xFFC0;
		for(i=0;i<64;i++)
		{
			if(TempBuf[i]!=IAP_ReadByte(SectorAddr.W))
			{
				ErrCnt++;
				if(ErrCnt<ERR_CNT_MAX)
				{
					goto P_Err_Loop;
				}
				else
				{
					goto P_Err_Return;
				}
			}
			SectorAddr.W++;
		}
		ErrCnt=0;
	P_Err_Return:
		return ErrCnt;		
}

/***********************************************************************************
*Function:		u8 IAP_WriteBuf_With_Verify(u16 ByteAddr,u8 *pBuf,u8 Cnt)
*Description:	Write data to IAP
*		 	 	not protect the orgin data
*Input:u16 ByteAddr: IAP Address, u8 *pBuf: The data buf to be write,u8 Cnt: Length to be write(<64) 
*Output:u8  0->succeed, other->failure     
*************************************************************************************/
u8 IAP_WriteBuf_With_Verify(u16 ByteAddr,u8 *pBuf,u8 Cnt)
{
		u16 i;
		u8 ErrCnt;
		WordTypeDef SectorAddr;

		bit bEA=EA;

		ErrCnt=0;
		
	Err_Loop:
		// Erase page
		SectorAddr.W=ByteAddr;
		IAP_ErasePage(SectorAddr.W);

		// 	
		EA = 0;								//Disable interrupt
		
		ISPCR = 0x80;               		//Enable ISP/IAP
		IFMT = ISP_BYTE_WRITE;				//Byte write mode
		
		// write data to IAP		
		for(i=0;i<Cnt;i++)
		{
			IFADRH= SectorAddr.B.BHigh;		//Set address high byte
			IFADRL= SectorAddr.B.BLow; 		//Set address low byte;
			IFD = pBuf[i]; 					//Set data to be wite 
			//		CheckTrapFlag();
			SCMD = 0x46;
			//		CheckTrapFlag();
			SCMD = 0xB9;
			nop();
			SectorAddr.W++;
		}
		IFMT = ISP_PAGE_WRITE;				//Page write mode
		//CheckTrapFlag();
		SCMD = 0x46;
		//CheckTrapFlag();
		SCMD = 0xB9;
		nop();
		IFMT=0;
		ISPCR = 0;							//Clear ISPCR

		EA = bEA; 							//restore interrupt

		//Verify
		SectorAddr.W=ByteAddr;
		for(i=0;i<Cnt;i++)
		{
			if(pBuf[i]!=IAP_ReadByte(SectorAddr.W))
			{
				ErrCnt++;
				if(ErrCnt<ERR_CNT_MAX)
				{
					goto Err_Loop;
				}
				else
				{
					goto Err_Return;
				}
			}
			SectorAddr.W++;
		}
		ErrCnt=0;
	Err_Return:
		return ErrCnt;		
}

/***********************************************************************************
*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
	UART0_SetRxTxP30P31();
	// Sets B.R. 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
	
	PORT_SetP1OpenDrainPu(BIT0);				// Set P10 as Open-Drain with pull-up resistor
	P10=1;
	P30=1;
}


/***********************************************************************************
*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();	
	TrapFlag[1]='i';
}




void main()
{
	u8 IAPData;
	u8 i;
	u8 rand;
	bit bOK=TRUE;

	TrapFlag[0]='W';
	
    InitSystem();
    
	LED_G_0=0;LED_G_1=0;LED_R=0;
	DelayXms(1000);
	printf("\nStart IAP DEMO!");
	LED_G_0=1;LED_G_1=1;LED_R=1;

	TrapFlag[2]='n';
	// read IAP low boundary
	i=IAP_ReadPPage(IAPLB_P);
    printf("\nRead IAPLB:%02bX",i);

	//  set IAP low boundary to ISP address,IAP size none
	IAP_WritePPage(IAPLB_P,ISP_ADDRESS/256);
	i=IAP_ReadPPage(IAPLB_P);
    printf("\nNOW IAPLB:%02bX\n",i);
	TrapFlag[2]=0xFF;

	printf("\nOld IAP %04X:\n",IAP_ADDRESS);
	i=0;
	do{
		LED_G_1=0;
		IAPData=IAP_ReadByteByMOVC(IAP_ADDRESS+i);	// read data by MOVC
		LED_G_1=1;
		printf("%02bX ",IAPData);
		if((i&0x0F)==0x0F)
		{
			printf("\n");
		}
		i++;
	}while(i<64);
    

    while(1)
    {
    	rand++;
		LED_G_0=!LED_G_0;
	   	DelayXms(100);
		if(IO_KEY_SAVE_0==0)
		{
			DelayXms(50);
			if(IO_KEY_SAVE_0==0)
			{

				// 
				for(i=0;i<16;i++)
				{
					TestBuf[i]=rand+i;
				}
				
				TrapFlag[2]='n';
				
				// set IAP low boundary to IAP_ADDRESS
				printf("\nWrite IAPLB:%02bX  ",IAP_ADDRESS/256);
				IAP_WritePPage(IAPLB_P,IAP_ADDRESS/256);
				i=IAP_ReadPPage(IAPLB_P);
				printf("\nRead IAPLB:%02bX  ",i);

				// Write data to IAP
				printf("\nWrit IAP %04X...  ",TEST_WRITE_BUF_IAP_ADDRESS_0);
				if(IAP_WriteBuf_With_Verify_Protect(TEST_WRITE_BUF_IAP_ADDRESS_0, &TestBuf[0], 16)==0)
				{// Succeed
					bOK=TRUE;
					printf("OK!!");
				}
				else
				{// Fail
					bOK=FALSE;
					printf("FAIL!!");
				}
				
				// set IAP low boundary to ISP address,IAP size none
				printf("\nWrite IAPLB:%02bX  ",ISP_ADDRESS/256);
				IAP_WritePPage(IAPLB_P,ISP_ADDRESS/256);
				i=IAP_ReadPPage(IAPLB_P);
				printf("\nRead IAPLB:%02bX  ",i);
				TrapFlag[2]=0xFF;
				
				if(bOK)
				{// Succeed
					for(i=0;i<10;i++)
					{
						LED_G_0=0;
						DelayXms(30);
						LED_G_0=1;
						DelayXms(30);
					}
				}
				else
				{// Fail
					LED_R=0;
					DelayXms(500);
					LED_R=1;
				}

				// Wait key release 
				while(IO_KEY_SAVE_0==0)
				{
					DelayXms(50);
				}
			}
		}

		if(IO_KEY_SAVE_1==0)
		{
			DelayXms(50);
			if(IO_KEY_SAVE_1==0)
			{

				// 
				for(i=0;i<16;i++)
				{
					TestBuf[i]=rand+i;
				}
				
				TrapFlag[2]='n';
				
				// set IAP low boundary to IAP_ADDRESS
				printf("\nWrite IAPLB:%02bX  ",IAP_ADDRESS/256);
				IAP_WritePPage(IAPLB_P,IAP_ADDRESS/256);
				i=IAP_ReadPPage(IAPLB_P);
				printf("\nRead IAPLB:%02bX  ",i);

				// write buf to IAP,not protect
				printf("\nWrit IAP %04X...  ",TEST_WRITE_BUF_IAP_ADDRESS_1);
				if(IAP_WriteBuf_With_Verify(TEST_WRITE_BUF_IAP_ADDRESS_1, &TestBuf[0], 16)==0)
				{// pass
					bOK=TRUE;
					printf("OK!!");
				}
				else
				{// fail
					bOK=FALSE;
					printf("FAIL!!");
				}
				
				// set IAP low boundary to ISP address,IAP size none
				printf("\nWrite IAPLB:%02bX  ",ISP_ADDRESS/256);
				IAP_WritePPage(IAPLB_P,ISP_ADDRESS/256);
				i=IAP_ReadPPage(IAPLB_P);
				printf("\nRead IAPLB:%02bX  ",i);
				TrapFlag[2]=0xFF;
				
				if(bOK)
				{// pass
					for(i=0;i<10;i++)
					{
						LED_G_0=0;
						DelayXms(30);
						LED_G_0=1;
						DelayXms(30);
					}
				}
				else
				{// fail
					LED_R=0;
					DelayXms(500);
					LED_R=1;
				}

				// wait key release 
				while(IO_KEY_SAVE_1==0)
				{
					DelayXms(50);
				}
			}
		}

		
    }

}


