/*********************************************************************
*Project:MG82F6B08_001_104-DEMO
*			MG82F6B08_001_104 SOP16_V11 EV Board (TH221A)
*			CpuCLK=8MHz, SysCLK=8MHz
*Description:
*			TWSI0 (SCL/P33, SDA/P46) Master
*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 TWI0_SCL		P33
#define TWI0_SDA		P46


#define SLAVE_ADDRESS_A0	0xA0
#define SLAVE_ADDRESS_B0	0xB0
#define TEST_BUF_SIZE	16

u8	TWI0OvTime;

u8 rand;

WordTypeDef TWI0TestAddr;

bit bES0;
u8 LedTime;
xdata u8 WriteBuf[TEST_BUF_SIZE];
xdata u8 ReadBuf[TEST_BUF_SIZE];
u8 TestBufLen;

/***********************************************************************************
*Function:   void INT_T0(void)
*Description:T0 Interrupt handler
*Input:   
*Output:     
*************************************************************************************/
void INT_T0(void) interrupt INT_VECTOR_T0
{
	TH0=TIMER_12T_1ms_TH;
	TL0=TIMER_12T_1ms_TL;
	if(TWI0OvTime!=0) TWI0OvTime--;
	if(LedTime!=0) LedTime--;
}

/***********************************************************************************
*Function:   void SendByte(u8 tByte)
*Description:Uart send byte
*Input: 
*		u8 tByte: the data to be send
*Output:

*************************************************************************************/
void SendByte(u8 tByte)
{
	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;
	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 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 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 InitTimer0(void)
*Description:Initialize Timer0
*Input:   
*Output:     
*************************************************************************************/
void InitTimer0(void)
{
	TM_SetT0Mode_1_16BIT_TIMER();			// TIMER0 Mode: 16-bit
	TM_SetT0Clock_SYSCLKDiv12();			// TIMER0 Clock source: SYSCLK/12
	TM_SetT0Gate_Disable();

	TM_SetT0LowByte(TIMER_12T_1ms_TL);						// Set TL0 value
	TM_SetT0HighByte(TIMER_12T_1ms_TH);					// Set TH0 value

	TM_EnableT0();							// Enable T0
}

/***********************************************************************************
*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,TWI0_SCL
	PORT_SetP4OpenDrainPu(BIT6);				// Set P46 Open-Drain with pull-up resistor,for TWI0:SDA
}

/***********************************************************************************
*Function:   void InitTWI0(void)
*Description:Initialize TWI0
*Input:   
*Output:     
*************************************************************************************/
void InitTWI0()
{
	TWI0_Clear();
	TWI0_SetClock(TWI0_CLK_SYSCLK_128);
	TWI0_SetSCLSDAP33P46();
	TWI0_Enable();
}

/***********************************************************************************
*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 InitInterrupt(void)
*Description:   Initialize Interrupt 
*Input:   
*Output:     
*************************************************************************************/
void InitInterrupt(void)
{
	INT_EnTIMER0();						// Enable T0 interrupt
	INT_EnAll();						// Enable global interrupt
}	

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

/***********************************************************************************
*Function:   u8 TWI0_WriteBuf(u8 DevAddr,u16 RegStartAddr,u8 *pByte,u8 Len)
*Description:Send data to slave through TWI0
*Input: 
*		u8 DevAddr: Slave Device address
*		u16 RegStartAddr: Slave data address
*		u8 *pBuf: Address of the buffer to be send
*		u8 Len: Data length
*Output:u8: 0->succeed, other->failure
*************************************************************************************/
u8 TWI0_WriteBuf(u8 DevAddr,u16 RegStartAddr,u8 *pBuf,u8 Len)
{
	u8 i;
	u8 Flag;
	Flag=1;

	SICON |=STA;						// send I2C START
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_WRITE_ERR;}		//  wait completed, if time overflow,then return fail.
	SICON &=~STA;

	SICON=SICON|(AA);	   

	Flag++;
	SIDAT = DevAddr&0xFE;				// send Slave Device address 
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_WRITE_ERR;}		//  wait completed, if time overflow,then return fail.

	Flag++;
	SIDAT = HIBYTE(RegStartAddr);		// send Slave data address high byte
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_WRITE_ERR;}		//  wait completed, if time overflow,then return fail.

	Flag++;
	SIDAT = LOBYTE(RegStartAddr);		// send Slave data address low byte
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_WRITE_ERR;}		//  wait completed, if time overflow,then return fail.


	Flag++;
	i=0;
	while(i<Len)
	{
		if(i==(Len-1))
		{
			SICON=SICON&(~AA);	   
		}
		else
		{
			SICON=SICON|(AA);	   
		}
		SIDAT=pBuf[i];			// send data
		TWI0OvTime=5;
		SICON &=~SI;			
		while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_WRITE_ERR;}		//  wait completed, if time overflow,then return fail.
		i++;
	}
	
	Flag++;
	SICON |= STO;				// send I2C STOP
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&STO)==STO){if(TWI0OvTime==0) goto TWI0_WRITE_ERR;}		//  wait completed, if time overflow,then return fail.
	SICON &=~STO;

	SICON = SICON &(~SI);		// Clear flag

	return 0;
	
TWI0_WRITE_ERR:
	return Flag;
}

/***********************************************************************************
*Function:   u8 TWI0_ReadBuf(u8 DevAddr,u16 RegStartAddr,u8 *pBuf,u8 Len)
*Description:Read data from slave through TWI0
*Input: 
*		u8 DevAddr: Slave Device address
*		u16 RegStartAddr: Slave data address
*		u8 *pBuf: Address of the buffer to be save
*		u8 Len: Data length
*Output:u8: 0->succeed, other->failure
*************************************************************************************/
u8 TWI0_ReadBuf(u8 DevAddr,u16 RegStartAddr,u8 *pBuf,u8 Len)
{
	u8 i;
	u8 Flag;
	Flag=1;
	
	SICON |=STA;				// send START
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.
	SICON &=~STA;

	Flag++;
	SICON=SICON|(AA);	   

	SIDAT = DevAddr&0xFE;		// send Slave Device address 
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.

	Flag++;
	SIDAT = HIBYTE(RegStartAddr);		// send Slave data address high byte
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.

	Flag++;
	SIDAT = LOBYTE(RegStartAddr);		// send Slave data address low byte
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.

	Flag++;
	SICON |= STA;				// resend START
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.
	SICON &=~STA;

	Flag++;
	SIDAT = DevAddr|0x01;		// send Slave Device address,enter read mode
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.

	Flag++;
	i=0;
	while(i<Len)
	{
		if(i==(Len-1))
		{
			SICON=SICON&(~AA);	   
		}
		else
		{
			SICON=SICON|(AA);	   
		}
		TWI0OvTime=5;
		SICON &=~SI;			
		while((SICON&SI)!=SI){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.
		pBuf[i] = SIDAT; 			// read data
		i++;
	}
	
	Flag++;
	SICON |= STO;				// send STOP
	TWI0OvTime=5;
	SICON &=~SI;			
	while((SICON&STO)==STO){if(TWI0OvTime==0) goto TWI0_READ_ERR;}		//  wait completed, if time overflow,then return fail.
	SICON &=~STO;

	SICON = SICON &(~SI);		// clear Flag

	return 0;
	
TWI0_READ_ERR:
	SICON |= STO;				// send STOP
	SICON = SICON &(~SI);		// clear Flag
	return Flag;
}

void TWI0_TestProc(void)
{
	u8 S0Ret;
	u8 i;
	
	SendStr("\nTWI0 Test ");
	SendHex(TWI0TestAddr.B.BHigh);
	SendHex(TWI0TestAddr.B.BLow);
	
	for(i=0;i<TEST_BUF_SIZE;i++)
	{
		WriteBuf[i]=0x78+i+rand;
	}
	
	S0Ret=TWI0_WriteBuf(SLAVE_ADDRESS_A0, TWI0TestAddr.W, &WriteBuf[0],TEST_BUF_SIZE);
	if(S0Ret==0)
	{
		DelayXms(5); // EEPROM writing delay
		S0Ret=TWI0_ReadBuf(SLAVE_ADDRESS_A0,TWI0TestAddr.W,&ReadBuf[0],TEST_BUF_SIZE);
		if(S0Ret==0)
		{
			for(i=0;i<TEST_BUF_SIZE;i++)
			{
				if(WriteBuf[i] != ReadBuf[i]) break;
			}
			if(i<TEST_BUF_SIZE)
			{
				SendStr("...Err--Verify:");
				SendHex(i);
				SendByte(0x20);
				SendHex(WriteBuf[i]);
				SendByte(0x20);
				SendHex(ReadBuf[i]);
				
			}
			else
			{
				SendStr("...SUCCESS!");
				for(i=0;i<6;i++)
				{
					LED_R=!LED_R;
					DelayXms(30);

				}
			}
		}
		else
		{
			SendStr("...Err--R:");
			SendHex(S0Ret);
		}
	}
	else
	{
		SendStr("...Err--W:");
		SendHex(S0Ret);
	}
	if(S0Ret!=0)
	{
		// Error,reset TWI0
		InitTWI0();
	
	}
	TWI0TestAddr.W=TWI0TestAddr.W+TEST_BUF_SIZE;
	if(TWI0TestAddr.W>=0x1000)
	{
		TWI0TestAddr.W=0;
	}
}

void main()
{
	
    InitSystem();
	
 	SendStr("\nStart");
	LED_R=0;
	DelayXms(1000);
	LED_R=1;

	rand = 0x00;
	TWI0TestAddr.W=0x0000;

    while(1)
    {
		rand++;
    	if(LedTime==0)
    	{
			LED_R=0;
			TWI0_TestProc();
			LED_R=1;
			LedTime=200;
		}
    }
}


