/*********************************************************************
*Project:MG82F6B08_001_104-DEMO
*			MG82F6B08_001_104 SOP16_V11 EV Board (TH221A)
*			CpuCLK=8MHz, SysCLK=8MHz
*Description:
*			UART0,LIN 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 LIN_TXD			P31
#define LIN_RXD			P30

#define LIN_TIME_MAX				10

#define LIN_SYNC_BYTE				0x55

#define LIN_AUTO_BAUDRATE_FLAG		0		// 0->Disable auto Baud-Rate 1->Enable auto Baud-Rate			

#define LIN_PID_MASTER_TX_MSG0		0x10		
#define LIN_PID_MASTER_TX_MSG1		0x11	

#define LIN_PID_MASTER_RX_MSG0		0x21
#define LIN_PID_MASTER_RX_MSG1		0x31




// define LIN status
typedef enum
{
  LIN_IDLE_BREAK=0,
  LIN_SYNC,
  LIN_PID,
  LIN_MASTER_RX_DATA,
  LIN_MASTER_RX_CHECKSUM,
  LIN_MASTER_RX_DONE,
  LIN_MASTER_TX_DATA,
  LIN_MASTER_TX_CHECKSUM,
  LIN_MASTER_TX_DONE,
  LIN_ERR
}LIN_State;

// define LIN mode
typedef enum
{
  	LIN_MODE_MASTER_TX=0,
	LIN_MODE_MASTER_RX,
	LIN_MODE_SLAVE_TX,
	LIN_MODE_SLAVE_RX
}LIN_Mode;

// define frame struct
typedef struct
{
	LIN_Mode Mode;
  	LIN_State State;
  	u8 PID ;
  	u8 Data[8];
  	u8 DataLength;
  	u8 DataInx;
  	u8 Check;
} LIN_Frame ;

#define BIT(A,B)      ((A>>B)&0x01)   // A variable

idata LIN_Frame LINFrame;


u8 LedTime;
u8 LINOverTime;

void LIN_Master_StartFrame(void);
u8 LIN_CalcParity(u8 id);
u8 LIN_CalcChecksum(u8 id,u8 *lindata,u8 length);

/***********************************************************************************
*Function:   void INT_UART0(void)
*Description:UART0 Interrupt handler
		 
*Input:   
*Output:     
*************************************************************************************/
void INT_UART0(void) interrupt INT_VECTOR_UART0
{
	if(RI0==1)
	{
		if(LINFrame.State==LIN_MASTER_RX_DATA)
		{ // Rx data
			
			LINFrame.Data[LINFrame.DataInx] = S0BUF;
			LINFrame.DataInx++;
			if(LINFrame.DataInx>=LINFrame.DataLength)
			{
				LINFrame.State++;
			}

		}
		else if(LINFrame.State==LIN_MASTER_RX_CHECKSUM)
		{ // Rx checksum
			LINFrame.Check=S0BUF;
			LINFrame.State++;
			
		}
		else if(LINFrame.State==LIN_MASTER_RX_DONE)
		{ // Rx done
		
		}
		else
		{
			LINFrame.State=LIN_ERR;
		}
		RI0 = 0;
	}
	else
	{
		TI0 = 0;
		
		if(LINFrame.State==LIN_IDLE_BREAK)
		{
			if((S0CFG1&SBF0)!=0)
			{ // Send break end
				UART0_LIN_ClrSBF0();
				S0BUF=LIN_SYNC_BYTE;		// Send SYNC
				LINFrame.State++;
			}
		}
		/**/
		else if(LINFrame.State==LIN_SYNC)
		{// Send SYNC end
			LINFrame.State++;
			S0BUF=LINFrame.PID;				// Send PID
		}
		/**/
		else if(LINFrame.State==LIN_PID)
		{// Send PID end 
			if(LINFrame.Mode == LIN_MODE_MASTER_RX)
			{
				LINFrame.DataInx=0;
				LINFrame.State= LIN_MASTER_RX_DATA;
				UART0_LIN_SetRX();			// set UART0 to LIN RX mode
				
			}
			else if(LINFrame.Mode == LIN_MODE_MASTER_TX)
			{// Start send DATA
				S0BUF = LINFrame.Data[0];
				LINFrame.DataInx=1;
				LINFrame.State= LIN_MASTER_TX_DATA;
			}
			else
			{ 
				LINFrame.State=LIN_ERR;
			}
		}
		else if(LINFrame.State==LIN_MASTER_TX_DATA)
		{
			
			S0BUF=LINFrame.Data[LINFrame.DataInx];
			LINFrame.DataInx++;
			if(LINFrame.DataInx>=LINFrame.DataLength)
			{
				LINFrame.State++;
			}

		}
		else if(LINFrame.State==LIN_MASTER_TX_CHECKSUM)
		{
			S0BUF=LINFrame.Check;
			LINFrame.State++;
		}
		else if(LINFrame.State==LIN_MASTER_TX_DONE)
		{
		}
		else
		{
			LINFrame.State=LIN_ERR;
		}
	}
}

/***********************************************************************************
*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(LINOverTime!=0) LINOverTime--;
}


/*************************************************
*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_LIN(void)
*Description:   Initialize Uart0 for LIN mode
*Input:   
*Output:     
*************************************************************************************/
void InitUart0_LIN(void)
{
	
	UART0_SetAccess_S0CR1();			// Set SFR 0xB9 address to access S0CR1
	UART0_SetModeLIN();					// UART0 Mode:LIN 		
	UART0_EnReception();				// Enable reception
	UART0_SetBRGFromS0BRG();			// B.R. source: S0BRG
	UART0_SetS0BRGBaudRateX2();			// S0BRG x2
	UART0_SetS0BRGSelSYSCLK();			// S0BRG clock source:SYSCLK

	// Set S0BRG Value
	UART0_SetS0BRGValue(S0BRG_BRGRL_9600_2X_8000000_1T);
	
	UART0_EnS0BRG();					// Enable S0BRG
	
	UART0_LIN_TxSYNC_16Bit();			// Set TX break 16bit
	
}

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

/***********************************************************************************
*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
}

/***********************************************************************************
*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();
	InitTimer0();
	InitUart0_LIN();
	InitInterrupt();
}

/*
*************************************************************************************
*  Function
*
*************************************************************************************

/***********************************************************************************
*Function:   void LIN_Master_StartFrame(void)
*Description:   LIN Master start frame
*Input:   
*Output:     
*************************************************************************************/
void LIN_Master_StartFrame(void)
{
	UART0_LIN_SetTX();
	UART0_LIN_ClrTXER0();
	UART0_LIN_ClrSBF0();
	TI0=0;
	UART0_LIN_SendSYNC();
	S0BUF=0x55;
}

/***********************************************************************************
*Function:	uint8 LIN_CalcParity(uint8 id)
*Description: LIN calculate parity
*Input:	
*Output:	  
*************************************************************************************/
u8 LIN_CalcParity(u8 id)
{
	u8 parity, p0,p1;
	parity=id; 
	p0=(BIT(parity,0)^BIT(parity,1)^BIT(parity,2)^BIT(parity,4))<<6;     //Even
	p1=(!(BIT(parity,1)^BIT(parity,3)^BIT(parity,4)^BIT(parity,5)))<<7;  //Odd
	parity|=(p0|p1);
	return parity;
}

/***********************************************************************************
*Function:	u8 LIN_CalcChecksum(uint8 id,uint8 *data,uint8 length)
*Description: LIN calculate checksum
*Input:	
*Output:	  
*************************************************************************************/
u8 LIN_CalcChecksum(u8 id,u8 *lindata,u8 length)
{
	u8 i;
	u16 check_sum = 0;
	//0x3C 0x3D use standard checksum
 	if(id != 0x3c && id != 0x7d)  // use enhanced checksum
 	{
	 	check_sum  = id ;
	} 
	else //use standard checksum
	{
	 	check_sum = 0 ;
	}
	for (i = 0; i < length; i++) 
	{    
	 	 check_sum += *(lindata++);
	  
	  	if (check_sum > 0xFF)      //carry
	  	{
	  		check_sum -= 0xFF;
	  	}
	}
	return (~check_sum);  // not
}

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

/***********************************************************************************
*Function:	void TestMasterTxMsgToSlave(u8 uPID)
*Description: Test transmit data to slave
*Input:	u8 uPID: PID ->0x00~0x3F
*Output:	  
*************************************************************************************/
void TestMasterTxMsgToSlave(u8 uPID)
{
	u8 i;

	// Master Tx Test
	LINFrame.Mode=LIN_MODE_MASTER_TX;
	LINFrame.PID=LIN_CalcParity(uPID);
	LINFrame.DataInx=0;
	LINFrame.DataLength=8;						// Data length: 8 Byte
	for(i=0;i<8;i++)
	{
		LINFrame.Data[i]=i+0x30+uPID;			// Test data
	}
	LINFrame.Check=LIN_CalcChecksum(LINFrame.PID, &LINFrame.Data[0],LINFrame.DataLength);
	LINFrame.State=LIN_IDLE_BREAK;
	LIN_Master_StartFrame();
	TI0=0;RI0=0;
	INT_EnUART0();		// Enable UART0 interrupt
	
	LINOverTime=20;
	while (LINOverTime!=0)
	{
		if((LINFrame.State==LIN_ERR)||(LINFrame.State==LIN_MASTER_TX_DONE))
		{
		  break;
		}
	}
	INT_DisUART0(); 	// Disable UART0 interrupt
	if(LINFrame.State==LIN_MASTER_TX_DONE)
	{// transmit OK
		LED_R=0;
	}
	DelayXms(2);
	LED_R=1;
}

/***********************************************************************************
*Function:	void TestMasterRxMsgFromSlave(u8 uPID)
*Description: Test receive data from slave
*Input:	u8 uPID: PID ->0x00~0x3F
*Output:	  
*************************************************************************************/
void TestMasterRxMsgFromSlave(u8 uPID)
{
	u8 i;
	// Master Rx Test
	LINFrame.Mode=LIN_MODE_MASTER_RX;
	LINFrame.PID=LIN_CalcParity(uPID);
	LINFrame.DataInx=0;
	LINFrame.DataLength=8;
	for(i=0;i<8;i++)
	{
		LINFrame.Data[i]=0x00;
	}
	LINFrame.State=LIN_IDLE_BREAK;
	LIN_Master_StartFrame();
	TI0=0;RI0=0;
	INT_EnUART0();		// Enable UART0 interrupt
	
	LINOverTime=20;
	while (LINOverTime!=0)
	{
		if((LINFrame.State==LIN_ERR)||(LINFrame.State==LIN_MASTER_RX_DONE))
		{
		  break;
		}
	}
	INT_DisUART0(); 	// Disable UART0 interrupt
	if(LINFrame.State==LIN_MASTER_RX_DONE)
	{// receive pass
		// check
		if(LINFrame.Check == LIN_CalcChecksum(LINFrame.PID, &LINFrame.Data[0], LINFrame.DataLength))
		{
			LED_R=0;
		}
	}
	DelayXms(2);
	LED_R=1;
}

void main()
{
	u8 uPID;
	
	InitSystem();
	
	LED_G_0=0;LED_R=0;LED_G_1=0;
	DelayXms(1000);
	LED_G_0=1;LED_R=1;LED_G_1=1;	

	INT_EnAll();		// Enable global interrupt

	uPID=0x00;
	
	while(1)
    {
    	DelayXms(50);
		if(uPID<0x20)
		{
			LED_G_0=!LED_G_0;
			LED_G_1=1;
			TestMasterTxMsgToSlave(uPID);
		}
		else
		{
			LED_G_1=!LED_G_1;
    		LED_G_0=1;
			TestMasterRxMsgFromSlave(uPID);
		}
		uPID++;
		if(uPID>=0x40)
		{
			uPID=0x00;
		}
		
    }

}


