I2CDAC.cs

/* I2CDAC.cs
 *
 * 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 .
 */

using System;
using TiePie.LibTiePie;

class I2CDACExample
{
    // AD5667 address:
    private const UInt16 AD5667_ADDRESS = 12;

    // AD5667 registers:
    private const Byte AD5567_REG_DAC_A = 0x0;
    private const Byte AD5567_REG_DAC_B = 0x1;
    private const Byte AD5667_REG_DAC_ALL = 0x7;

    // AD5667 commands:
    private const Byte AD5667_CMD_WRITE = 0x0;
    private const Byte AD5667_CMD_UPDATE = 0x8;
    private const Byte AD5667_CMD_WRITE_UPDATE_ALL = 0x10;
    private const Byte AD5667_CMD_WRITE_UPDATE = 0x18;
    private const Byte AD5667_CMD_POWER = 0x20;
    private const Byte AD5667_CMD_RESET = 0x28;
    private const Byte AD5667_CMD_LDAC_SETUP = 0x30;
    private const Byte AD5667_CMD_REF_SETUP = 0x38;

    public static void Main()
    {
        // Print library information:
        PrintInfo.PrintLibraryInfo();

        // Enable network search:
        Network.AutoDetectEnabled = true;

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

        // Try to open an I2C host:
        I2CHost I2C = null;

        for (UInt32 i = 0; i < DeviceList.Count; i++)
        {
            DeviceListItem item = DeviceList.GetItemByIndex(i);
            if (item.CanOpen(DeviceType.I2CHost))
            {
                I2C = item.OpenI2CHost();
                break;
            }
        }

        if (I2C != null)
        {
            try
            {
                // Print I2C host info:
                PrintInfo.PrintDeviceInfo(I2C);

                // Turn on internal reference for DAC A:
                I2C.WriteByteWord(AD5667_ADDRESS, AD5667_CMD_REF_SETUP | AD5567_REG_DAC_A, 1);

                // Set DAC A to mid level:
                I2C.WriteByteWord(AD5667_ADDRESS, AD5667_CMD_WRITE_UPDATE | AD5567_REG_DAC_A, 0x8000);
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
                Environment.Exit(1);
            }

            // Close I2C host:
            I2C.Dispose();
            I2C = null;
        }
        else
        {
            Console.WriteLine("No I2C host available!");
            Environment.Exit(1);
        }

        System.Environment.Exit(0);
    }
}