// This example reads the ambient light using the Maxim MAX44000PMB1 Pmod


/***************************** Include Files **********************************/
#include "xparameters.h"
#include "xiicps.h"
#include "xil_printf.h"
#include <stdio.h>
#include "platform.h"
#include "sleep.h"
#include "xgpiops.h"

#define MAX44000_IIC_ADDRESS            0x4A   //!< The actual address is 8'b1001 010x (0x94)
#define MAX44000_MAIN_CONFIG_REG        0x01   // Main configuration register
#define MAX44000_RECV_CONFIG_REG        0x02   // Receive configuration register
#define MAX44000_LED_DRIVE_CURRENT_REG  0x03   // LED Drive Current register
#define MAX44000_LUX_HIGH_BYTE_REG      0x04   // Lux High-Byte register (overflow bit + bits 13:8 of lux reading)
#define MAX44000_LUX_LOW_BYTE_REG       0x05   // Lux Low-Byte register (bits 7:0 of lux reading)

int MAX44000_write(u32 ZynqIicAddress, u8 register_offset, u8 write_value);
int MAX44000_read(u32 ZynqIicAddress, u8 register_offset, u8 *read_value);

XIicPs Iic;		/**< Instance of the IIC Device */

#define GPIO_DEVICE_ID  	XPAR_XGPIOPS_0_DEVICE_ID

/*
 * The following constant is used to wait after an LED is turned on to make
 * sure that it is visible to the human eye.  This constant might need to be
 * tuned for faster or slower processor speeds.
 */
#define LED_DELAY		10000000

/*
 * Following constant define the Input and Output pins.
 */
#define LED1		47	/* Pin connected to JX3.40, LED/Output */
#define LED2		50	/* Pin connected to JX3.66, LED/Output */
#define PB			51	/* Pin connected to Switch/Input */
#define MUX_SEL		0   /* Pin connected to eMMC/Pmod mux select */

#define LED_MAX_BLINK		0x10	/* Number of times the LED Blinks */

XGpioPs Gpio;	/* The driver instance for GPIO Device. */

int main()
{
	u8 LuxHighByte=0;
	u8 LuxLowByte=0;
	unsigned int LuxReading=0;
	u8 loop;
	XIicPs_Config *Config;
	int Status;
	//u32 InputData;
	XGpioPs_Config *ConfigPtr;
	u32 Data;
	volatile int Delay;
	u32 LedLoop;

    init_platform();

	ConfigPtr = XGpioPs_LookupConfig(GPIO_DEVICE_ID);
	Status = XGpioPs_CfgInitialize(&Gpio, ConfigPtr,
					ConfigPtr->BaseAddr);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

    printf("Blinking LEDs\n\r");;

	XGpioPs_SetDirectionPin(&Gpio, LED1, 1);
	XGpioPs_SetOutputEnablePin(&Gpio, LED1, 1);
	XGpioPs_SetDirectionPin(&Gpio, LED2, 1);
	XGpioPs_SetOutputEnablePin(&Gpio, LED2, 1);

	XGpioPs_WritePin(&Gpio, LED1, 0x0);
	XGpioPs_WritePin(&Gpio, LED2, 0x0);

	for (LedLoop = 0; LedLoop < LED_MAX_BLINK; LedLoop ++) {
		for (Delay = 0; Delay < LED_DELAY; Delay++);
		XGpioPs_WritePin(&Gpio, LED1, 0x1);
		XGpioPs_WritePin(&Gpio, LED2, 0x1);
		Data = XGpioPs_ReadPin(&Gpio, LED1);
		if (Data != 1 ) {
			printf("Writing LED1 Failed\n\r");;
		}
		Data = XGpioPs_ReadPin(&Gpio, LED2);
		if (Data != 1 ) {
			printf("Writing LED2 Failed\n\r");;
		}
		for (Delay = 0; Delay < LED_DELAY; Delay++);
		XGpioPs_WritePin(&Gpio, LED1, 0x0);
		XGpioPs_WritePin(&Gpio, LED2, 0x0);
		Data = XGpioPs_ReadPin(&Gpio, LED1);
		if (Data != 0 ) {
			printf("Writing LED1 Failed\n\r");;
		}
		Data = XGpioPs_ReadPin(&Gpio, LED2);
		if (Data !=0 ) {
			printf("Writing LED2 Failed\n\r");;
		}
	}

	XGpioPs_SetDirectionPin(&Gpio, MUX_SEL, 1);
	XGpioPs_SetOutputEnablePin(&Gpio, MUX_SEL, 1);
	XGpioPs_WritePin(&Gpio, MUX_SEL, 0x1);

	/*
	 * Initialize the IIC driver so that it's ready to use
	 * Look up the configuration in the config table,
	 * then initialize it.
	 */

	Config = XIicPs_LookupConfig(XPAR_XIICPS_0_DEVICE_ID);
	if (NULL == Config) {
		return XST_FAILURE;
	}

	Status = XIicPs_CfgInitialize(&Iic, Config, Config->BaseAddress);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	// Perform a self-test to ensure that the hardware was built correctly.
	Status = XIicPs_SelfTest(&Iic);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	//Set the IIC serial clock rate.
	XIicPs_SetSClk(&Iic, 100000);

    printf("PS I2C Initialized\n\r");

    // Set to Ambient Light Sensor mode
    MAX44000_write(XPAR_PS7_I2C_0_DEVICE_ID, MAX44000_MAIN_CONFIG_REG, 0x24);

    // Set the Ambient Light Sensor programmable gain
    // Value = 0x00 sets up 14-bit resolution, gain = 0.03125 LUX/lsb
    MAX44000_write(XPAR_PS7_I2C_0_BASEADDR, MAX44000_RECV_CONFIG_REG, 0x00);

    // Now take 30 readings, 1 second apart
    // Experiment covering and uncovering the device to see if it really
    //   is detecting the changes in light. Use a flashlight to
    //   force the device to overflow. What happens? How would you fix it?
    for(loop=0; loop<30; loop++)
    {
       sleep(1); // sleep 1s
       MAX44000_read(XPAR_PS7_I2C_0_BASEADDR, MAX44000_LUX_HIGH_BYTE_REG, &LuxHighByte);
       MAX44000_read(XPAR_PS7_I2C_0_BASEADDR, MAX44000_LUX_LOW_BYTE_REG, &LuxLowByte);
       if((LuxHighByte & 0x50)== 0x50)
          printf("Overflow occurred\r\n");
       LuxReading = (LuxHighByte & 0x3F);
       LuxReading = LuxReading << 8;
       LuxReading += LuxLowByte;
       LuxReading /= 32; // Undo the previous gain entered
       printf("Lux Value = %d\r\n",LuxReading);
    }

    printf("Testing Complete\n\r");

	XGpioPs_WritePin(&Gpio, MUX_SEL, 0x0);

    cleanup_platform();
    return 0;
}

int MAX44000_write(u32 ZynqIicAddress, u8 register_offset, u8 write_value)
/*
* \brief       Use the Zynq IIC Controller to write a value to a
*              MAX44000 register at a given offset
*
* \param[in]   ZynqIicAddress    - address of the I2C Controller
* \param[in]   register_offset   - offset of register inside the MAX44000
* \param[in]   write_value       - value to be written to MAX44000 register
*
* \return      XST_SUCCESS if operation succeeded
*/
{
	int Status = XST_SUCCESS;
	u8 TxBuffer[128]; // Only need this to be size 2, but making larger for future use

	TxBuffer[0] = register_offset;  // Offset of register to write
	TxBuffer[1] = write_value;  // value to write there
	/* ADD HERE
	 *  Add code to send the 2 bytes contained in TxBuffer over I2C to
	 *  the device responding to I2C address MAX44000_IIC_ADDRESS.
	 *  The first byte of TxBuffer contains the offset to the register
	 *  inside the MAX44000. The second byte contains the data to be
	 *  written to that register. If the transfer fails, then
	 *  set Status to XST_FAILURE
	 */
	Status = XIicPs_MasterSendPolled(&Iic, TxBuffer, 2, MAX44000_IIC_ADDRESS);
	if (Status != XST_SUCCESS) return XST_FAILURE;
	//Wait until bus is idle to start another transfer.
	while (XIicPs_BusIsBusy(&Iic)) {/* NOP */}

	return(Status);
}

int MAX44000_read(u32 ZynqIicAddress, u8 register_offset, u8 *read_value)
/*
* \brief       Use the Zynq IIC Controller to read a value from a
*              MAX44000 register at a given offset
*
* \param[in]   ZynqIicAddress    - address of the I2C Controller
* \param[in]   register_offset   - offset of register inside the MAX44000
* \param[in]   *read_value       - pointer to data read from MAX44000 register
*
* \return      XST_SUCCESS if operation succeeded
*/
{
	int Status = XST_SUCCESS;
	u8 TxBuffer[128]; // Only need this to be size 1, but making larger for future use
	u8 RxBuffer[128]; // Only need this to be size 1, but making larger for future use

	TxBuffer[0] = register_offset;
	/* ADD HERE
	 *  Add code to send 1 byte contained in TxBuffer over I2C to
	 *  the device responding to I2C address MAX44000_IIC_ADDRESS.
	 *  TxBuffer contains the offset to the register
	 *  inside the MAX44000. If the transfer fails, then
	 *  set Status to XST_FAILURE
	 */
	Status = XIicPs_MasterSendPolled(&Iic, TxBuffer, 1, MAX44000_IIC_ADDRESS);
	if (Status != XST_SUCCESS) return XST_FAILURE;
	//Wait until bus is idle to start another transfer.
	while (XIicPs_BusIsBusy(&Iic)) {/* NOP */}

	/* ADD HERE
	 *  Add code to receive 1 byte into RxBuffer over I2C from
	 *  the device responding to I2C address MAX44000_IIC_ADDRESS.
	 *  Since we previously sent the offset to the register
	 *  inside the MAX44000, the MAX44000 will now return the data
	 *  contained within that register. If the transfer fails, then
	 *  set Status to XST_FAILURE
	 */
	Status = XIicPs_MasterRecvPolled(&Iic, RxBuffer, 1, MAX44000_IIC_ADDRESS);
	if (Status != XST_SUCCESS)
		return XST_FAILURE;

	if(Status==XST_SUCCESS)
		*read_value = RxBuffer[0];

	usleep(100000); // Delay 100 ms, which is 100K us
	return(Status);
}
