/*
 * "Hello World" example.
 *
 * This example prints 'Hello from Nios II' to the STDOUT stream. It runs on
 * the Nios II 'standard', 'full_featured', 'fast', and 'low_cost' example
 * designs. It runs with or without the MicroC/OS-II RTOS and requires a STDOUT
 * device in your system's hardware.
 * The memory footprint of this hosted application is ~69 kbytes by default
 * using the standard reference design.
 *
 * For a reduced footprint version of this template, and an explanation of how
 * to reduce the memory footprint for a given application, see the
 * "small_hello_world" template.
 *
 */

#include <stdio.h>
#include <altera_avalon_i2c.h>

/* I2C0 devices addresses */
/* TI TMP411A Temperature sensor (U5) */
#define I2C0_TMP411A_ADDR 0x4c
/* ST M24128-BW EEPROM (U16) */
#define I2C_M24128B_MEM_ADDR 0x54


int main()
{
  printf("Hello from Nios II!\n");

  /* I2C0 */
  ALT_AVALON_I2C_DEV_t *i2c0_dev; //pointer to instance structure

  alt_u8 txbuffer[0x200];
  alt_u8 rxbuffer[0x200];

  ALT_AVALON_I2C_STATUS_CODE status;

  i2c0_dev = alt_avalon_i2c_open("/dev/i2c_0");
  if (NULL == i2c0_dev) {
	  printf("Error: Cannot find /dev/i2c_0\n");
	  return 1;
  }

  /* Temp monitor */
  alt_avalon_i2c_master_target_set(i2c0_dev, I2C0_TMP411A_ADDR);

  txbuffer[0] = 0xfe; // Manufacturer ID

  status = alt_avalon_i2c_master_tx_rx(i2c0_dev, txbuffer, 1, rxbuffer, 1, ALT_AVALON_I2C_NO_INTERRUPTS);

  if (status!=ALT_AVALON_I2C_SUCCESS) {
	  printf("alt_avalon_i2c_master_tx_rx(temp_mon): fail: %d\n", (int) status);
	  return 1; //FAIL
  } else printf("alt_avalon_i2c_master_tx_rx(temp_mon): 0x%02x\n", rxbuffer[0]);

  /* EEPROM */
  alt_avalon_i2c_master_target_set(i2c0_dev, I2C_M24128B_MEM_ADDR);

  status = alt_avalon_i2c_master_rx(i2c0_dev, rxbuffer, 1, ALT_AVALON_I2C_NO_INTERRUPTS);

  if (status!=ALT_AVALON_I2C_SUCCESS) {
	  printf("alt_avalon_i2c_master_tx_rx(mem): fail: %d\n", (int) status);
	  return 1; //FAIL
  } else printf("alt_avalon_i2c_master_tx_rx(mem): 0x%02x\n", rxbuffer[0]);


  //write data to an eeprom at address 0x0200
  //txbuffer[0]=2; txbuffer[1]=0;
  //The eeprom address which will be sent as first two bytes of data
  //for (i=0; i < 0x10; i++)
  //  txbuffer[i+2] = i;

  //some data to write
  //status = alt_avalon_i2c_master_tx(i2c_dev, txbuffer, 0x10+2, ALT_AVALON_I2C_NO_INTERRUPTS);

  //if (status != ALT_AVALON_I2C_SUCCESS) return 1; //FAIL
  //read back the data into rxbuffer
  //This command sends the 2 byte eeprom data address required by the eeprom
  //Then does a restart and receives the data.
//  status = alt_avalon_i2c_master_tx_rx(i2c0_dev, txbuffer, 1, rxbuffer, 1, ALT_AVALON_I2C_NO_INTERRUPTS);
//
//
//  if (status!=ALT_AVALON_I2C_SUCCESS) {
//	  printf("alt_avalon_i2c_master_tx_rx(): fail: %d\n", status);
//	  return 1; //FAIL
//  } else printf("alt_avalon_i2c_master_tx_rx(): 0x%02x\n", rxbuffer[0]);

  return 0;
}
