
/*! @file Register access routines for I2C controlled image sensor
*/

// A wrapper of LPC43xx_i2c.c I2C routines, need to change to LPCOpen in future
// PixArt's sensor can use this module, but often fails on OV7670, damn it!

#include <string.h>
#include "lpc43xx.h"
#include "AppDefs.h"
#include "lpc43xx_i2c.h"

extern DS_CamCB SHARERAM s_ccb;

#define USEDI2CDEV_M		0
	
#if (USEDI2CDEV_M == 0)
#define I2CDEV_M LPC_I2C0
#elif (USEDI2CDEV_M == 1)
#define I2CDEV_M LPC_I2C1
#else
#error "Master I2C device not defined!"
#endif


unsigned int ReadI2CRegister(uint8_t SlaveID, uint8_t Address,uint8_t *Data)
{
	I2C_M_SETUP_Type transferMCfg;
	uint8_t Transfer_Buf[1];
  uint8_t Receive_Buf[1];
	Status  I2C_Status;
	
	/*
	Transfer_Buf[0] = Address;
	Receive_Buf[0]  = 0x00;
	
	transferMCfg.sl_addr7bit = SlaveID;
	transferMCfg.tx_data = Transfer_Buf ;
	transferMCfg.tx_length = 1;
	transferMCfg.rx_data = Receive_Buf;
	transferMCfg.rx_length = 1;
	transferMCfg.retransmissions_max = 0;
	*/
	Transfer_Buf[0] = Address;
	Receive_Buf[0]  = 0x00;
	
	transferMCfg.sl_addr7bit = SlaveID;
	transferMCfg.tx_data = Transfer_Buf ;
	transferMCfg.tx_length = 1;
	transferMCfg.rx_data = NULL;
	transferMCfg.rx_length = 0;
	transferMCfg.retransmissions_max = 0;
	
	I2C_Status=I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);
	if(I2C_Status == ERROR)
		;
	
	Transfer_Buf[0] = Address;
	Receive_Buf[0]  = 0x00;
	
	transferMCfg.sl_addr7bit = SlaveID;
	transferMCfg.tx_data = NULL ;
	transferMCfg.tx_length = 0;
	transferMCfg.rx_data = Receive_Buf;
	transferMCfg.rx_length = 1;
	transferMCfg.retransmissions_max = 0;
	
	I2C_Status=I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);
	if(I2C_Status == ERROR)
		;
	
	
	
	*Data = Receive_Buf[0];
	
	return 1;	
}

unsigned int WriteI2CRegister(uint8_t SlaveID, uint8_t Address,uint8_t Data)
{
	I2C_M_SETUP_Type transferMCfg;
	uint8_t Transfer_Buf[2];
	Status  I2C_Status;
  	
	Transfer_Buf[0] = Address;
	Transfer_Buf[1] = Data;	
	
	transferMCfg.sl_addr7bit = SlaveID;
	transferMCfg.tx_data = Transfer_Buf ;
	transferMCfg.tx_length = 2;
	transferMCfg.rx_data = NULL;
	transferMCfg.rx_length = 0;
	transferMCfg.retransmissions_max = 0;
	
	I2C_Status=I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);
	
	if(I2C_Status == ERROR)
		;
	return 1;	
}


unsigned int InitialSensor_I2C(void)
{
	/* I2C block ------------------------------------------------------------------- */
		
	// Initialize Slave I2C peripheral
	I2C_Init(I2CDEV_M, 90000);
	// I2C_Init(I2CDEV_M, 320000);
	
	/* Enable Slave I2C operation */
	I2C_Cmd(I2CDEV_M, ENABLE);
	return 1;
}
