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

bit bES0;
u8 LedTime;
u8 Cnt100;

u8 TWI0TestTime;

u8 TWI0OvTime;

enum{
	EE_IDLE=0,
	EE_SEND_START,
	EE_SEND_SLA,
	EE_WRITE_ADDR_H,
	EE_WRITE_ADDR_L,
	EE_SEND_RESTART,
	EE_WRITE_DATA,
	EE_READ_DATA,
	EE_SEND_STOP
}EE_STATUS;

#define EE_SUCCESS		0x00

#define DATA_LENGTH          16
WordTypeDef TWI0TestAddr;

xdata u8 TWI0WriteBuf[DATA_LENGTH];
xdata u8 TWI0ReadBuf[DATA_LENGTH];

#define TWI0_TEST_INTERVAL_TIME	(400/100)			// *100ms	TWI0 test interval time

#define IIC_OVTIME_MAX		20						// *1ms IIC overtime


#define EE_MODE_WRITE		0
#define EE_MODE_READ		1

typedef struct 
{
	u8 EEMode;
	u8 EEStatus;
	u8 EEDeviceAddr;
	u16 EEDataAddr;
	u8 *EEDataBuf;
	u8 EEFlag;
	u8 EEDataInx;
	u8 EEDataLength;
}EEPROM_PROC_STRUCT;

idata EEPROM_PROC_STRUCT EE_TWI0;


u8 rand;

/***********************************************************************************
*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(LedTime!=0) LedTime--;
	if(TWI0OvTime!=0) TWI0OvTime--;
	Cnt100++;
	if(Cnt100>=100)
	{
		Cnt100=0;
		if(TWI0TestTime!=0) TWI0TestTime--;
	}
}

/***********************************************************************************
*Function:   void INT_TWSI(void)
*Description:TWI0 Interrupt handler
*Input:   
*Output:     
*************************************************************************************/
void INT_TWI0() interrupt INT_VECTOR_TWI0
{
	_push_(SFRPI);
	SFR_SetPage(0);

	if(SISTA==0x08)
	{ // Tx:Start
		SICON=SICON&(~STA);
		SIDAT=EE_TWI0.EEDeviceAddr&0xFE;
		EE_TWI0.EEStatus=EE_SEND_SLA;
	}
	else if(SISTA==0x18)
    { // Tx:SLA+W Rx:ACK
    	// To send RegAddr high
		SICON=SICON|(AA);
    	SIDAT=(u8)(EE_TWI0.EEDataAddr>>8);
		EE_TWI0.EEStatus=EE_WRITE_ADDR_H;
    }
    else if(SISTA==0x20)
    { // Tx:SLA+W Rx:NACK
		EE_TWI0.EEFlag=EE_TWI0.EEStatus+0x80;
		EE_TWI0.EEStatus=EE_SEND_STOP;
		SICON=SICON|(STO);
    }
    else if(SISTA==0x28)
    { // Tx:DAT Rx:ACK
		if(EE_TWI0.EEStatus==EE_WRITE_ADDR_H)
		{
			// To send RegAddr LOW
			SICON=SICON|(AA);
			SIDAT=(u8)(EE_TWI0.EEDataAddr);
			EE_TWI0.EEStatus=EE_WRITE_ADDR_L;
		}
		else if(EE_TWI0.EEStatus==EE_WRITE_ADDR_L)
		{
			// Send RegAddr Done
			if(EE_TWI0.EEMode==EE_MODE_READ)
			{
				// Read mode: To Tx ReStart;
				SICON=SICON|(STA);
				EE_TWI0.EEStatus=EE_SEND_RESTART;
			}
			else
			{
				// Write mode: To Tx Data;
				SICON=SICON|(AA);
				EE_TWI0.EEStatus=EE_WRITE_DATA;
				EE_TWI0.EEDataInx=0;
				SIDAT=EE_TWI0.EEDataBuf[EE_TWI0.EEDataInx];
				EE_TWI0.EEDataInx++;
			}
		}
		else if(EE_TWI0.EEStatus==EE_WRITE_DATA)
		{
			if(EE_TWI0.EEDataInx>=EE_TWI0.EEDataLength)
			{
				SICON=SICON|(STO);
				EE_TWI0.EEFlag= EE_SUCCESS;
				EE_TWI0.EEStatus=EE_SEND_STOP;
			}
			else
			{
				SICON=SICON|(AA);
				SIDAT=EE_TWI0.EEDataBuf[EE_TWI0.EEDataInx];
				EE_TWI0.EEDataInx++;
			}
		}
		else
		{
			SICON=SICON|(STO);
			EE_TWI0.EEFlag=EE_TWI0.EEStatus+0x80;
			EE_TWI0.EEStatus=EE_SEND_STOP;
		}
    }
    else if(SISTA==0x30)
    { // Tx:DAT Rx:NACK
		EE_TWI0.EEFlag= EE_TWI0.EEStatus+0x80;
		if(EE_TWI0.EEStatus==EE_WRITE_DATA)
		{
			if(EE_TWI0.EEDataInx==EE_TWI0.EEDataLength)
			{
				EE_TWI0.EEFlag= EE_SUCCESS;
			}
		}
		SICON=SICON|(STO);
		EE_TWI0.EEStatus=EE_SEND_STOP;
    }
	else if(SISTA==0x10)
	{ // Tx:ReStart
		SICON=SICON&(~STA);
		SIDAT=EE_TWI0.EEDeviceAddr|0x01;
		EE_TWI0.EEStatus=EE_SEND_SLA;
	}
    else if(SISTA==0x40)
    { // Tx:SLA+R Rx:ACK
		SICON=SICON|(AA);
		EE_TWI0.EEDataInx=0;
		EE_TWI0.EEStatus=EE_READ_DATA;
    }
    else if(SISTA==0x48)
    { // Tx:SLA+R Rx:NACK
		EE_TWI0.EEFlag=EE_TWI0.EEStatus+0x80;
		EE_TWI0.EEStatus=EE_SEND_STOP;
		SICON=SICON|(STO);
    }
    else if(SISTA==0x50)
    { // Rx:DAT Tx:ACK
		if(EE_TWI0.EEStatus==EE_READ_DATA)
		{
			if(EE_TWI0.EEDataInx>=EE_TWI0.EEDataLength)
			{
				SICON=SICON|(STO);
				EE_TWI0.EEFlag= EE_SUCCESS;
				EE_TWI0.EEStatus=EE_SEND_STOP;
			}
			else
			{
				EE_TWI0.EEDataBuf[EE_TWI0.EEDataInx]=SIDAT;
				EE_TWI0.EEDataInx++;
				if(EE_TWI0.EEDataInx>=EE_TWI0.EEDataLength-1)
				{
					SICON=SICON&(~AA);
				}
				else
				{
					SICON=SICON|(AA);
				}
			}
		}
		else
		{
			EE_TWI0.EEFlag=EE_TWI0.EEStatus+0x80;
			EE_TWI0.EEStatus=EE_SEND_STOP;
			SICON=SICON|(STO);
		}
    }
    else if(SISTA==0x58)
    { // Rx:DAT Tx:NACK
		EE_TWI0.EEFlag= EE_TWI0.EEStatus+0x80;
		if(EE_TWI0.EEStatus==EE_READ_DATA)
		{
			EE_TWI0.EEDataBuf[EE_TWI0.EEDataInx]=SIDAT;
			EE_TWI0.EEDataInx++;
			if(EE_TWI0.EEDataInx==EE_TWI0.EEDataLength)
			{
				EE_TWI0.EEFlag= EE_SUCCESS;
			}
		}
		SICON=SICON|(STO);
		EE_TWI0.EEStatus=EE_SEND_STOP;
    }
	TWI0OvTime=IIC_OVTIME_MAX;
	SICON=SICON&(~SI);
	_pop_(SFRPI);
}

/***********************************************************************************
*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_32);
	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_EnTWI0();						// Enable TWI0 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:       void TWI0_StartWriteBuf(u8 DevAddr,u16 RegStartAddr,u8 *pByte)
*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:     
*************************************************************************************/
void TWI0_StartWriteBuf(u8 DevAddr,u16 RegStartAddr,u8 *pBuf,u8 Len)
{
	
	EE_TWI0.EEMode=EE_MODE_WRITE;
	EE_TWI0.EEDataBuf=pBuf;
	EE_TWI0.EEDeviceAddr=DevAddr;
	EE_TWI0.EEDataAddr=RegStartAddr;
	EE_TWI0.EEDataLength=Len;
	EE_TWI0.EEStatus=EE_SEND_START;
	// start TWI0
	TWI0OvTime=IIC_OVTIME_MAX;
	TWI0_SendSTART();	
}


/***********************************************************************************
*Function:       void TWI0_StartReadBuf(u8 DevAddr,u16 RegStartAddr,u8 *pByte)
*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:
*************************************************************************************/
void TWI0_StartReadBuf(u8 DevAddr,u16 RegStartAddr,u8 *pBuf,u8 Len)
{
	EE_TWI0.EEMode=EE_MODE_READ;
	EE_TWI0.EEDataBuf=pBuf;
	EE_TWI0.EEDeviceAddr=DevAddr;
	EE_TWI0.EEDataAddr=RegStartAddr;
	EE_TWI0.EEDataLength=Len;
	EE_TWI0.EEStatus=EE_SEND_START;
	// start TWI0
	TWI0OvTime=IIC_OVTIME_MAX;
	TWI0_SendSTART();	
}

void TWI0_TestProc(void)
{
	u8 i;
	
	if(EE_TWI0.EEStatus==EE_IDLE)
	{
		if(TWI0TestTime==0)
		{
			LED_R=0;
			if(EE_TWI0.EEMode!=EE_MODE_WRITE)
			{ // Start write test
				SendStr("\nTWI0 Write EEPROM Start...");
				SendHex(TWI0TestAddr.B.BHigh);
				SendHex(TWI0TestAddr.B.BLow);
				i=0;
				for(i=0;i<DATA_LENGTH;i++)
				{
					TWI0WriteBuf[i]=i+rand;
					i++;
				}
				TWI0_StartWriteBuf(I2C_SLAVE_ADDR, TWI0TestAddr.W, &TWI0WriteBuf[0],DATA_LENGTH);
			}
			else
			{
				SendStr("\nTWI0 Read EEPROM Start...");
				SendHex(TWI0TestAddr.B.BHigh);
				SendHex(TWI0TestAddr.B.BLow);
				TWI0_StartReadBuf(I2C_SLAVE_ADDR, TWI0TestAddr.W, &TWI0ReadBuf[0],DATA_LENGTH);
				TWI0TestAddr.W=TWI0TestAddr.W+DATA_LENGTH;
				if(TWI0TestAddr.W>=0x1000)
				{
					TWI0TestAddr.W=0;
				}
			}
		}
	}
	else if(EE_TWI0.EEStatus==EE_SEND_STOP)
	{ // IIC finished
		LED_R=1;
		TWI0TestTime=TWI0_TEST_INTERVAL_TIME;
		if(EE_TWI0.EEFlag != EE_SUCCESS)
		{
			SendStr("\nTWI0 Err: 0x");
			SendHex(EE_TWI0.EEFlag);
		}
		else
		{
			if(EE_TWI0.EEMode==EE_MODE_READ)
			{
				for(i=0;i<DATA_LENGTH;i++)
				{
					if(TWI0WriteBuf[i]!=TWI0ReadBuf[i]) break;
				}
				if(i>=DATA_LENGTH)
				{// Check success
					SendStr("\nTWI0 WR Success!!");
					for(i=0;i<6;i++)
					{
						LED_R=!LED_R;
						DelayXms(30);
					
					}
				}
				else
				{// Check failure
					SendStr("\nTWI0 Verify Fail!! 0x");
					SendHex(i);
				}
			}	
			else
			{
				SendStr("\nTWI0 Wrtie Done!");
				DelayXms(5);
				TWI0TestTime=0;
			}
		}
		EE_TWI0.EEStatus=EE_IDLE;
	}
	else
	{
		if(TWI0OvTime==0)
		{ // IIC over time
			LED_R=1;
			SendStr("\nTWI0 Fail-->TWI0_Reset..");
			InitTWI0();
			EE_TWI0.EEStatus=EE_IDLE;
			EE_TWI0.EEMode=EE_MODE_READ;
			TWI0TestTime=TWI0_TEST_INTERVAL_TIME;
		}
	}
}

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

	rand = 0x80;

	TWI0TestAddr.W=0x0000;
	EE_TWI0.EEStatus=EE_IDLE;
	EE_TWI0.EEMode=EE_MODE_READ;
	TWI0TestTime=TWI0_TEST_INTERVAL_TIME;

	
    while(1)
    {
		rand++;
		TWI0_TestProc();
    }
}


