/***************************************************************************/
/*                                                                         */
/*                  (C) Copyright 2010 NXP Semiconductors                  */
/*                                                                         */
/***************************************************************************/

#include "i2c.h"
#include "uart.h"

static I2C_MSG wrMsg;                      // PCA9500 EEPROM write
static BYTE    wrBuf[2];                   // PCA9500 EEPROM write buffer

static I2C_MSG rdMsg;                      // PCA9500 EEPROM read
static BYTE    rdBuf[1];                   // PCA9500 EEPROM read buffer


BYTE EEPROM_Read(BYTE add)                 // random read to the PCA9500
{
    wrMsg.address = SLA_PCA9500_EE;        // first write slave address
    wrMsg.buf     = wrBuf;                 // and memory address to the
    wrMsg.nrBytes = 1;                     // PCA9500. Then generate repeated
    wrMsg.next    = (LONG) &rdMsg;         // and read back the contents
    wrBuf[0]      = add;                   // of the memory address

    rdMsg.address = SLA_PCA9500_EE | 1;    // slave address + read
    rdMsg.buf     = rdBuf;
    rdMsg.nrBytes = 1;
    rdMsg.next    = 0;

    switch (I2C_Transfer(&wrMsg))
    {
      case I2C_OK              : break;
      case I2C_NO_DATA         : PrintString("buffer empty\n");      break;
      case I2C_NACK_ON_DATA    : PrintString("no ack on data\n");    break;
      case I2C_NACK_ON_ADDRESS : PrintString("no ack on address\n"); break;
      case I2C_TIME_OUT        : PrintString("time-out\n");          break;
      default                  : PrintString("time-out\n");          break;
    }

    return rdBuf[0];
}

void EEPROM_Write(BYTE add, BYTE val)
{
    wrMsg.address = SLA_PCA9500_EE;
    wrMsg.buf     = wrBuf;
    wrMsg.nrBytes = 2;
    wrMsg.next    = 0;
    wrBuf[0]      = add;
    wrBuf[1]      = val;
    switch (I2C_Transfer(&wrMsg))
    {
      case I2C_OK              : break;
      case I2C_NO_DATA         : PrintString("buffer empty\n");      break;
      case I2C_NACK_ON_DATA    : PrintString("no ack on data\n");    break;
      case I2C_NACK_ON_ADDRESS : PrintString("no ack on address\n"); break;
      case I2C_TIME_OUT        : PrintString("time-out\n");          break;
      default                  : PrintString("time-out\n");          break;
    }
}

void EEPROM_Init(BYTE add, BYTE val)
{
    I2C_Init();                            // initialize I2C bus
}
