/*******************************************************************************
*	Application: Demo code for IIC using in HHD32F0xx
*	Edition:		Version:1.0
*	Company: 		
*	Time: 			October 2015
*******************************************************************************/
#include "hhd32f0xx.h"
#include "hhd_SYS.h"
#include "hhd_iic.h"
#include "hhd_uart.h"
#include "SD2405ALPI.h"
#include "LM75A.h"
#include "at24c02.h"


//#define LM75A  1
//#define SD2405 1
#define AT24C02 1
/*****************************************************************************
* Function name:    Main Function
*
* Descriptions:     Use OUT,SET,CLR,NOT,PIN to show different pin control
*
* parameters:       None
* Returned value:   None
* 
*****************************************************************************/
int main(void)
{
	uint32_t i;
	volatile uint32_t Temp;
	uint8_t Read_Data[7];
	uint8_t Transmit[7] = {0x00,0x16,0x22,0x02,0x09,0x10,0x12};
	
	//System Initial
	SYS_SystemInitial();
	
	IIC->CONCLR.all = 0xFF;
	// Initial TWS, Mode--Master(1), Rate---200KHz, Slave Address is 0x90;
	IIC_Init(1,200,LM75A_ADDR); 

	UART_Open(UART0, 115200, UART_NO_PARITY, UART_RX_NOT_EMPTY);
	 while ( 1 )
	{
		#if SD2405  // Operate SD2405
				
		SD2405ALPI_WriteReg(REG_CTR2,0x80); // Write WRTC1 to 1
		SD2405ALPI_WriteReg(REG_CTR1,0x84);	// Write WRTC2,WRTC3 to 1, the three bit enable write
		//SD2405ALPI_WriteReg(REG_HOUR,5);  // Write Hour value
		SD2405ALPI_WriteArray(REG_SEC,Transmit,7); // Write time, Sec->Min->Hour->Week->Day->Mon->Year
		SD2405ALPI_WriteReg(REG_CTR1,0x00);	// Write WRTC2,WRTC3 to 0
		SD2405ALPI_WriteReg(REG_CTR2,0x00);	// Write WRTC1 0, the three bit disable write

		i = 0xFFFFF;
		while(i--);

		Temp = 	SD2405ALPI_ReadReg(REG_HOUR);  // Read hour value
		SD2405ALPI_ReadArray(REG_SEC,7, Read_Data); // Read time value,Sec->Min->Hour->Week->Day->Mon->Year				  
		
		UART_PutString(UART0,"Following are Sec->Min->Hour->Week->Day->Mon->Year");
		UART_ByteWrite(UART0,'\n');
		for(i = 0; i < 7; i++)
		{
			UART_PutHex(UART0,Read_Data[i]); // Send value to UART
			UART_ByteWrite(UART0,'\n');
		}
		#endif

		#if LM75A // When LM75A is 1, read LM75A temperature value

		LM75A_ReadArray(LM75A_TEMP,2,Read_Data);  // Read LM75A temperature value

		Temp = ( ( ( Read_Data[0] << 8 ) | Read_Data[1] ) >> 3 ) * 0.03125; // Temperature Value
		i = 0xFFFFF;
		while(i--);

		UART_PutString(UART0,"Recent Temperature is ");
		UART_PutHex(UART0,Temp);  // Send temperatrue value to UART
		UART_ByteWrite(UART0,'\n');

		#endif
		
		#if AT24C02 // When AT24C02 is 1, write one byte and read it back

		AT24C02_WriteBYTE(0,0x55);
		while(1)
		{
			Temp=AT24C02_ReadBYTE(0);
		}
		i = 0xFFFFF;
		while(i--);
		UART_PutHex(UART0,Temp);  // Send temperatrue value to UART
		UART_ByteWrite(UART0,'\n');
		#endif

	}

}
