/*********************************************************************
*    Project: MG82F5B32-DEMO
*			MG82F5B32 LQFP32_V10 EV Board (TH156A)
*			CpuCLK=24MHz, SysCLK=24MHz
*    Description:
*			SPI(nSS/P33,MOSI/P15,MISO/P16,SPICLK/P17) Read/Write EN25Q32A
*			SPI clock :24MHz/4=6MHz
*    Note:
*		
*    Creat time:
*    Modify:
*    
*********************************************************************/
#define _MAIN_C

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

#include <Stdio.h>  // for printf
#include <string.h>

#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		24000000
/*************************************************/
/*************************************************
*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 SPI_nSS		P14


// SPI FLASH
#define Dummy_Data					0xFF
#define FLASH_BLOCK_SIZE			(64L*1024L)					// 64K Byte

#define FLASH_TEST_START_ADDRESS	0x00000000
#define FLASH_TEST_SIZE_MAX			(1024L*1024L)				// 1M Byte

#define FLASH_WRITE_ENABLE_TIME_MAX		(15+5)					// 15ms
#define FLASH_WRITE_STATUS_TIME_MAX		(15+5)					// 15ms
#define FLASH_PAGE_PROGRAM_TIME_MAX		(5+5)					// 5ms
#define FLASH_SECTOR_ERASE_TIME_MAX		(300+100)				// 300ms
#define FLASH_BLOCK_ERASE_TIME_MAX		(2000+500)				// 2s
#define FLASH_CHIP_ERASE_TIME_MAX		(50000+5000)			// 50s


u16 FlashOverTime;

xdata u8 TestBuf[512];
xdata u8 TestRxBuf[512];

DWordTypeDef dwTime;

/***********************************************************************************
*Function:   	void INT_T0(void)
*Description:	T0 Interrupt handler
*Input:   
*Output:     
*************************************************************************************/
void INT_T0(void) interrupt INT_VECTOR_T0
{
	dwTime.W.WHigh++;
}

/***********************************************************************************
*Function:   	void INT_T1(void)
*Description:	T1 Interrupt handler
*Input:   
*Output:     
*************************************************************************************/
void INT_T1(void) interrupt INT_VECTOR_T1
{
	TM_SetT1LowByte(TIMER_12T_1ms_TL);					// Set TL1
	TM_SetT1HighByte(TIMER_12T_1ms_TH);					// Set TH1
	if(FlashOverTime !=0) FlashOverTime--;
}

/*************************************************
*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 InitTimer0(void)
*Description:	Initialize Timer0
*Input:   
*Output:   		
*************************************************************************************/
void InitTimer0(void)
{
	TM_SetT0Mode_1_16BIT_TIMER();			// TIMER0 Mode: 16-bit
	TM_SetT0Clock_SYSCLKDiv48();			// TIMER0 Clock source: SYSCLK/48
	TM_SetT0Gate_Disable();
	TM_SetT0LowByte(0);						// Set TL0 value
	TM_SetT0HighByte(0);					// Set TH0 value
	//TM_EnableT0();						// Enable TIMER0
}

/***********************************************************************************
*Function:   	void InitTimer1(void)
*Description:	Initialize Timer1
*Input:   
*Output:   		
*************************************************************************************/
void InitTimer1(void)
{
	TM_SetT1Mode_1_16BIT_TIMER();			// TIMER1 Mode: 16-bit
	TM_SetT1Clock_SYSCLKDiv12();			// TIMER1 Clock source: SYSCLK/12
	TM_SetT1Gate_Disable();

	TM_SetT1LowByte(TIMER_12T_1ms_TL);						// Set TL1 value
	TM_SetT1HighByte(TIMER_12T_1ms_TH);					// Set TH1 value

	TM_EnableT1();							// Enable TIMER1
}

/***********************************************************************************
*Function:   	void InitPort()
*Description:	Initialize IO Port
*Input:   
*Output:   		
*************************************************************************************/
void InitPort(void)
{
	PORT_SetP2OpenDrain(0xFF);							// Set P2 as open drain
	PORT_EnP24P25P26P27PullHigh();						// Enable P24,P25,P26,P27 pull-high

	PORT_SetP1PushPull(BIT4|BIT5|BIT7);					// Set P14,P15(MOSI),P17(SPICLK) as Push pull
	PORT_SetP1OpenDrain(BIT6);							// Set P16(MISO) as OpenDrain
	PORT_EnP14P15P16P17PullHigh();						// Enable P14,P15,P16,P17 pull-high
}

/***********************************************************************************
*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_24000000_1T);
	
	UART1_EnS1BRG();					// Enable S1BRG
}

/***********************************************************************************
*Function:   	void InitInterrupt()
*Description:	Initialize Interrupt
*Input:   
*Output:   		
*************************************************************************************/
void InitInterrupt(void)
{
	INT_EnTIMER0();
	INT_EnTIMER1();
	
}

/***********************************************************************************
*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:   	void InitSPI_Master()
*Description:	Initialize SPI Master
*Input:   
*Output:   		
*************************************************************************************/
void InitSPI_Master(void)
{
	// Enable SPI
	SPI_Enable();
	// Set to MASTER
	SPI_SelectMASTERByMSTRbit();
	// Set Clock SYSCLK/4 24M/4=6M
	SPI_SetClock(SPI_CLK_SYSCLK_4);
	// CPOL=0
	SPI_SetCPOL_0();	
	// Data MSB 
	SPI_SetDataMSB();
	// CPHA=0
	SPI_SetCPHA_0();
	// IO Port: nSS/P14,MOSI/P15,MISO/P16,SPICLK/P17
	SPI_SetUseP14P15P16P17();

}

/***********************************************************************************
*Function:   	void Reset_Counter(void)
*Description:	Reset counter
*Input:   
*Output:   		
*************************************************************************************/
void Reset_Counter(void)
{
	// Disable T0
	TM_DisableT0();
	dwTime.DW=0x00000000;
	TM_SetT0HighByte(0);
	TM_SetT0LowByte(0);
	// Enable T0
	TM_EnableT0();
}

/***********************************************************************************
*Function:   	void Send_Counter(void)
*Description:	Send counter
*Input:   
*Output:   		
*************************************************************************************/
void Send_Counter(void)
{
	TM_DisableT0();
	dwTime.B.BMLow=TH0;
	dwTime.B.BLow=TL0;
	printf("%ldus",dwTime.DW*2);
}

/***********************************************************************************
*Function:   	u8 SPITransceiver(u8 SPI_DATA)
*Description:	SPI Master transmit 
*Input:   		u8 SPI_DATA: Data to be send
*Output:   		u8:  Received data
*************************************************************************************/
u8 SPITransceiver(u8 SPI_DATA)
{
	SPI_SendData(SPI_DATA);							// Send data
	while(SPI_ChkCompleteFlag()==0);				// Wait complete
	SPI_ClearCompleteFlag();						// Clear flag
	return SPI_GetData();							// Return data
}


/*
*************************************************************************************
*  SPI FLASH EN25Q32A
*
*************************************************************************************
*/

/***********************************************************************************
*Function:		u8 SPI_Flash_1ByteRead (u32 Address)
*Description:	Read 1 byte from EN25Q32A 
*Input:	uint32_t Address: Address 0x00000000 ~ 0xFFFFFFFF
*Output: uint8_t: data 	  
*************************************************************************************/
u8 SPI_Flash_1ByteRead (u32 Address)
{ 
	u8 x;
	SPI_nSS = 0;
    
    /* Write command */
    SPITransceiver(0x03);
	
    /* Write address */
    SPITransceiver((u8)(Address>>16));
    SPITransceiver((u8)(Address>>8));
    SPITransceiver((u8)(Address));
    
    /* Read data */
    x=SPITransceiver(Dummy_Data);

	SPI_nSS = 1;

    return  x;
}

/***********************************************************************************
*Function:		void SPI_Flash_MultiBytesRead (u32 Address, u8 *BufferAddreass, u16 Length)
*Description:	Read n bytes from EN25Q32A 
*Input:	  u32 Address: Address 0x00000000 ~ 0xFFFFFFFF
*		  u8 *BufferAddreass: Buffer address
*		  u16 Length: Buffer length
*Output: 
*************************************************************************************/
void SPI_Flash_MultiBytesRead (u32 Address, u8 *BufferAddreass, u16 Length)
{
	SPI_nSS = 0;
    /* Write command */
    SPITransceiver(0x03);
	
    /* Write address */
    SPITransceiver((u8)(Address>>16));
    SPITransceiver((u8)(Address>>8));
    SPITransceiver((u8)(Address));
    
    /* Read data */
    while(Length !=0)
	{
		*BufferAddreass=SPITransceiver(Dummy_Data);
        BufferAddreass ++;
        Length--;
	}
	SPI_nSS = 1;
}

/***********************************************************************************
*Function:		u32 SPI_Flash_Read_ID (void)
*Description:	read EN25Q32A ID 
*Input:	
*Output: uint32_t: EN25Q32A ID
*************************************************************************************/
u32 SPI_Flash_Read_ID (void)
{
	DWordTypeDef RDAT;
    
    SPI_nSS = 0;
    /* Write command */
    SPITransceiver(0x9F);
    
    /* Read ID */
    RDAT.B.BHigh=0x00;
    RDAT.B.BMHigh=SPITransceiver(Dummy_Data);
    RDAT.B.BMLow=SPITransceiver(Dummy_Data);
    RDAT.B.BLow=SPITransceiver(Dummy_Data);
	SPI_nSS  = 1;
    
    return RDAT.DW;
}

/***********************************************************************************
*Function:		u8 SPI_Flash_Write_Enable (void)
*Description: 	Enable write Flash
*Input:	
*Output: 		0:Success  1:Fail
*************************************************************************************/
u8 SPI_Flash_Write_Enable(void)
{
	u8 RDAT;
    FlashOverTime=FLASH_WRITE_ENABLE_TIME_MAX;
    while(FlashOverTime!=0)
    {
	    /* Write enable */
		SPI_nSS  = 0;
		SPITransceiver(0x06);
		SPI_nSS  = 1;

		nop();
		nop();
		nop();
		nop();
		nop();
	    /* Read status register */
		SPI_nSS  = 0;
		SPITransceiver(0x05);			//RDSR
	
		RDAT = SPITransceiver(Dummy_Data);                                  // Get received data

		SPI_nSS  = 1;

	    /* Check WEL == 1 */
		if((RDAT & 0x02) != 0x00)
		{
			return 0;
		}
	}
	return 1;
}

/***********************************************************************************
*Function:		u8 SPI_Flash_Check_Busy(u16 BusyTimeMax)
*Description:	check busy 
*Input:			BusyTimeMax: overflow time
*Output: 		0:Success  1:Fail
*************************************************************************************/
u8 SPI_Flash_Check_Busy(u16 BusyTimeMax)
{
	u8 RDAT;
	
    FlashOverTime=BusyTimeMax;

    while(FlashOverTime!=0)
    {
	    /* Read status register */
		SPI_nSS  = 0;
		SPITransceiver(0x05);							//RDSR

		RDAT = SPITransceiver(Dummy_Data);              // Get received data
		
	    /* Check erase or write complete */
		SPI_nSS  = 1;
	
		if((RDAT & 0x01) == 0x00)						
		{
			return 0;
		}
	}
	return 1;
}

/***********************************************************************************
*Function:	u8 SPI_Flash_Write_Status(u8 uStatus)
*Description:	  Write status
*Input:		u8 uStatus:status
*Output: 	0:Success  1:Fail
*************************************************************************************/ 
u8 SPI_Flash_Write_Status(u8 uStatus)
{
    if(SPI_Flash_Write_Enable()!=0) return 1;
    
	SPI_nSS  = 0;
	SPITransceiver(0x01);                               			// Write Status Register(WRSR) command 
                
	
    /* Write Status */
    SPITransceiver(uStatus);
	
	SPI_nSS  = 1;
   
	return 0;
}

/***********************************************************************************
*Function:		u8 SPI_Flash_Page_Program(u32 Addr, u8 *DataSource, u16 Length)
*Description:	Write n bytes to EN25Q32A
*Input:			u32 Addr: Start address. 0x00000000 ~ 0xFFFFFFFF.
*				u8 *DataSource: Buffer address
*				u16 Length: Buffer length, MAX.256 bytes
*Output:  		0:Success  1:Fail
*************************************************************************************/ 
u8 SPI_Flash_Page_Program(u32 Addr, u8 *DataSource, u16 Length)
{
    if(SPI_Flash_Write_Enable()!=0) return 1;
    
	SPI_nSS  = 0;
	SPITransceiver( 0x02);                               // Write command 
	
    /* Write address */
    SPITransceiver((u8)(Addr>>16));
    SPITransceiver((u8)(Addr>>8));
    SPITransceiver((u8)(Addr));
	
	while(Length!=0)                                     // Write Data
	{
		SPITransceiver(*DataSource);
        DataSource++;
		Length--;
	}
	
	SPI_nSS  = 1;
   
	return SPI_Flash_Check_Busy(FLASH_PAGE_PROGRAM_TIME_MAX);
}

/***********************************************************************************
*Function:		u8 SPI_Flash_Block_Erase(u32 Addr)
*Description:	EN25Q32A block erase
*Input:			u32 Addr: start addresss.
*Output:  		0:Success  1:Fail
*************************************************************************************/ 
u8 SPI_Flash_Block_Erase(u32 Addr)
{
    if(SPI_Flash_Write_Enable()!=0) return 1;
    
	SPI_nSS  = 0;
	SPITransceiver(0xD8);                               			// Block Erase command 
                
	
    /* Write address */
    SPITransceiver((u8)(Addr>>16));
    SPITransceiver((u8)(Addr>>8));
    SPITransceiver((u8)(Addr));
	
	SPI_nSS  = 1;
   
	return SPI_Flash_Check_Busy(FLASH_BLOCK_ERASE_TIME_MAX); 
}

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

/***********************************************************************************
*Function:       void InitSystem(void)
*Description:    Initialize MCU
*Input:   
*Output:     
*************************************************************************************/
void InitSystem(void)
{
	
	InitPort();
	InitClock();
	InitSPI_Master();			
	InitUart0_S1BRG();
	InitTimer0();
	InitTimer1();
	InitInterrupt();		// Initialize Interrupt
	
	INT_EnAll();			// Enable global interrupt
}

void main()
{
	u32 i;
	u8 x;
	
	DWordTypeDef dwTemp;
	
    InitSystem();
	
	printf("\nHello!");
	LED_G_1=0;LED_R=0;LED_G_0=0;
	DelayXms(1000);
	LED_G_1=1;LED_R=1;LED_G_0=0;

	// Read Flash ID
	dwTemp.DW=SPI_Flash_Read_ID();
	printf("\r\nFlash ID: %08lX",dwTemp.DW);
	DelayXms(10);

	// Clear write protect
	SPI_Flash_Write_Status(0x00);
	DelayXms(10);
	
	printf("\r\nFlash Erase...");
	i=FLASH_TEST_SIZE_MAX/FLASH_BLOCK_SIZE;
	// erase Flash
	dwTemp.DW=FLASH_TEST_START_ADDRESS;
	Reset_Counter();
	while(i!=0)
	{
		LED_R = 0;
		if(SPI_Flash_Block_Erase(dwTemp.DW)!=0) break;
		LED_R = 1;
		dwTemp.DW=dwTemp.DW+FLASH_BLOCK_SIZE;
		i--;
	}
	LED_R = 1;
	if(i==0)
	{
		Send_Counter();
	}
	else
	{
		printf("Fail (%ld)",i);
		goto TEST_END;
	}

	x=0;
	for(i=0;i<512;i++)
	{
	  TestBuf[i]=x;
	  x++;
	}
	// write Flash
	printf("\r\nFlash Write 1M...");
	i=FLASH_TEST_SIZE_MAX/256;	  
	dwTemp.DW=FLASH_TEST_START_ADDRESS;
	Reset_Counter();
	while(i!=0)
	{
	  LED_R = 0;
	  if(SPI_Flash_Page_Program(dwTemp.DW,&TestBuf[0],256)!=0) break;
	  LED_R = 1;
	  dwTemp.DW=dwTemp.DW+256;
	  i--;
	}
	LED_R = 1;
	if(i==0)
	{
		Send_Counter();
	}
	else
	{
		printf("Fail (%ld)",i);
		goto TEST_END;
	}
	
	// read Flash and verify
	printf("\r\nFlash Read 1M...");
	i=FLASH_TEST_SIZE_MAX/512;	  
	dwTemp.DW=FLASH_TEST_START_ADDRESS;
	Reset_Counter();
	while(i!=0)
	{
		LED_R = 0;
		SPI_Flash_MultiBytesRead(dwTemp.DW,&TestRxBuf[0],512);
		LED_R = 1;
		if(memcmp(&TestBuf[0],&TestRxBuf[0],512)!=0) break;
		dwTemp.DW=dwTemp.DW+512;
		i--;
	}
	LED_R = 1;
	if(i==0)
	{
		Send_Counter();
	}
	else
	{
		printf("Fail (%ld)",i);
		goto TEST_END;
	}

TEST_END:
    while(1)
    {
    	DelayXms(100);
		LED_G_1 = !LED_G_1;
    }
}







