I2CDAC.cpp

/**
 * I2CDAC.cpp - for LibTiePie 0.5+
 *
 * This example demonstrates how to use an I2C host supported by LibTiePie.
 * It shows how to control an Analog Devices AD5667 dual 16-bit DAC.
 *
 * Find more information on http://www.tiepie.com/LibTiePie .
 */

#include <iostream>
#include "libtiepie++.h"
#include "PrintInfo.h"

#if defined(__linux) || defined(__unix)
  #include <cstdlib>
#endif

// AD5667 address:
#define AD5667_ADDRESS 12

// AD5667 registers:
#define AD5667_REG_DAC_A   0x00
#define AD5667_REG_DAC_B   0x01
#define AD5667_REG_DAC_ALL 0x07

// AD5667 commands:
#define AD5667_CMD_WRITE            0x00
#define AD5667_CMD_UPDATE           0x08
#define AD5667_CMD_WRITE_UPDATE_ALL 0x10
#define AD5667_CMD_WRITE_UPDATE     0x18
#define AD5667_CMD_POWER            0x20
#define AD5667_CMD_RESET            0x28
#define AD5667_CMD_LDAC_SETUP       0x30
#define AD5667_CMD_REF_SETUP        0x38

using namespace std;
using namespace LibTiePie;

int main()
{
  int status = EXIT_SUCCESS;

  // Initialize library:
  Library::init();

  // Print library information:
  printLibraryInfo();

  // Update device list:
  DeviceList::update();

  // Try to open an I2C host:
  I2CHost* i2c = 0;

  for(uint32_t index = 0; index < DeviceList::count(); index++)
  {
    DeviceListItem* item = DeviceList::getItemByIndex(index);

    if(item->canOpen(DEVICETYPE_I2CHOST))
    {
      i2c = item->openI2CHost();
    }

    delete item;

    if(i2c)
    {
      break;
    }
  }

  if(i2c)
  {
    try
    {
      // Print I2C host info:
      printDeviceInfo(i2c);

      // Turn on internal reference for DAC A:
      i2c->writeByteWord(AD5667_ADDRESS , AD5667_CMD_REF_SETUP | AD5667_REG_DAC_A , 1);

      // Set DAC A to mid level:
      i2c->writeByteWord(AD5667_ADDRESS , AD5667_CMD_WRITE_UPDATE | AD5667_REG_DAC_A , 0x8000);
    }
    catch(const exception& e)
    {
      cerr << "Exception: " << e.what() << endl;
      status = EXIT_FAILURE;
    }

    // Close I2C host:
    delete i2c;
  }
  else
  {
    cerr << "No I2C host available!" << endl;
    status = EXIT_FAILURE;
  }

  // Exit library:
  Library::exit();

  return status;
}