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

      i2cl16.c    ( Light Version )
      v1.0 (17/04/2003)

      i2c protocol with 16 bits address memory acces
      Library for HI-TECH PIC C - master mode only.
      Light version without returned error check
      Supported divices: 24xx32, 24xx64, 24xx65, 24xx128, 24xx256

      This library use light version of i2c library for low level I/O.

      Written by Philippe Corbes <philippe.corbes@laposte.net>
      This code is free for personal use. 
      You need my agreement for a commercial use.


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

  #include <pic.h>
  #include "delay.h"
  #include "i2cl.h"
  #include "i2cl16.h"


  /*
   *  Read a byte from the slave and acknowledges the transfer
   *  Return: - the byte
   */
  unsigned char
  i2c16_read( unsigned char   component,
              unsigned int    address)
  {
      unsigned char abyte;

      i2c_start();
      i2c_write(component);
      i2c_write(address>>8);
      i2c_write(address);
      i2c_repStart();
      i2c_write(component + 1);
      abyte = i2c_read(I2C_LAST);
      i2c_stop();
      return(abyte);
  }

  /*
   *  Write specified data byte in 24lc65 
   */
  void
  i2c16_write(    unsigned char   component,
                  unsigned int    address,
                  unsigned char   abyte )
  {
      i2c_start();
      i2c_write(component);
      i2c_write(address>>8);
      i2c_write(address);
      i2c_write(abyte);
      i2c_stop();
      DelayMs(I2C_EEPROM_UPDATE);
      return;
  }


  /*
   *  Read a numbrer of bytes and strore them at '*data'
   *  Te number of bytes to read is specified by 'length'
   */
  void
  i2c16_read_seq( unsigned char   component,
                  unsigned int    address,
                  unsigned char   length,
                  unsigned char   *abyte)
  {
      i2c_start();
      i2c_write(component);
      i2c_write(address>>8);
      i2c_write(address);
      i2c_repStart();
      i2c_write(component+1);

      // read with acnowledge to signal we desire additionnal data
      length -=1;
      while((length--) > 0)
          *abyte++ = i2c_read(I2C_MORE);

      // read with no ack to signal this is the last data
      *abyte = i2c_read(I2C_LAST);

      i2c_stop();
      return;
  }

  /*
   *  Write a numbrer of bytes from '*data' to the 24c65
   *  Te number of bytes to write is specified by 'length'
   */
  void
  i2c16_write_seq(unsigned char   component,
                  unsigned int    address,
                  unsigned char   length,
                  unsigned char   *abyte)
  {
      i2c_start();
      i2c_write(component);
      i2c_write(address>>8);
      i2c_write(address);

      while((length--) > 0)
          i2c_write(*abyte++);

      i2c_stop();
      DelayMs(I2C_EEPROM_UPDATE);
      return;
  }