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

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

      i2c protocol with 16 bits address memory acces
      Library for HI-TECH PIC C - master mode only.
      Light version without returned error code, optimized to reduce code size
      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"

  //Global struct for I2C link
  struct I2C16  i2c16 ;



  /*
   *  Start a transaction, select a component and init Address
   *
   *  Input:  - i2c16.component
   *          - i2c16.address
   *  Output: noting
   */
  void
  i2c16_start(void)
  {
      i2c_start();
      i2c_write(i2c16.component);
      i2c_write(i2c16.address>>8);
      i2c_write(i2c16.address);
  }


  /*
   *  Read a byte from the slave and acknowledges the transfer
   *
   *  Input:  - i2c16.component
   *          - i2c16.address
   *  Output: update i2c16.data
   */
  void
  i2c16_read(void)
  {
      i2c16_start();
      i2c_repStart();
      i2c_write(i2c16.component + 1);
      i2c16.data = i2c_read(I2C_LAST);
      i2c_stop();
  }


  /*
   *  Write specified data byte in i2c device 
   *
   *  Input:  - i2c16.component
   *          - i2c16.address
   *  Output: nothing
   */
  void
  i2c16_write(    unsigned char   abyte )
  {
      i2c16_start();
      i2c_write(abyte);
      i2c_stop();
      DelayMs(I2C_EEPROM_UPDATE);
  }


  /*
   *  Read a numbrer of bytes and strore them at '*data'
   *  The number of bytes to read is specified by 'length'
   *
   *  Input:  - i2c16.component
   *          - i2c16.address
   *  Output: nothing
   */
  void
  i2c16_read_seq( unsigned char   length,
                  unsigned char   *abyte)
  {
      i2c16_start();
      i2c_repStart();
      i2c_write(i2c16.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();
  }


  /*
   *  Write a numbrer of bytes from '*data' to the i2c component
   *  The number of bytes to write is specified by 'length'
   *
   *  Input:  - i2c16.component
   *          - i2c16.address
   *  Output: nothing
   */
  void
  i2c16_write_seq(unsigned char   length,
                  unsigned char   *abyte)
  {
      i2c16_start();
      while((length--) > 0)
          i2c_write(*abyte++);
      i2c_stop();
      DelayMs(I2C_EEPROM_UPDATE);

  }