I2CDAC.vb

' I2CDAC.vb
'
' 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 .

Imports System
Imports TiePie.LibTiePie

Module I2CDACExample

    ' AD5667 address:
    Const AD5667_ADDRESS = 12

    ' AD5667 registers:
    Const AD5567_REG_DAC_A = &H0
    Const AD5567_REG_DAC_B = &H1
    Const AD5667_REG_DAC_ALL = &H7

    ' AD5667 commands:
    Const AD5667_CMD_WRITE = &H0
    Const AD5667_CMD_UPDATE = &H8
    Const AD5667_CMD_WRITE_UPDATE_ALL = &H10
    Const AD5667_CMD_WRITE_UPDATE = &H18
    Const AD5667_CMD_POWER = &H20
    Const AD5667_CMD_RESET = &H28
    Const AD5667_CMD_LDAC_SETUP = &H30
    Const AD5667_CMD_REF_SETUP = &H38

    Sub Main()
        ' Print library information:
        PrintLibraryInfo()

        ' Enable network search:
        Network.AutoDetectEnabled = True

        ' Update device list:
        DeviceList.Update()

        ' Try to open an I2C host:
        Dim I2C As I2CHost = Nothing

        If DeviceList.Count <> 0 Then
            For i As UInt32 = 0 To DeviceList.Count - 1
                Dim item As DeviceListItem = DeviceList.GetItemByIndex(i)
                If item.CanOpen(DeviceType.I2CHost) Then
                    I2C = item.OpenI2CHost()
                    Exit For
                End If
            Next
        End If

        If Not IsNothing(I2C) Then
            Try
                ' Print I2C info:
                PrintDeviceInfo(I2C)

                ' Turn on internal reference for DAC A:
                I2C.WriteByteWord(AD5667_ADDRESS, AD5667_CMD_REF_SETUP Or AD5567_REG_DAC_A, 1)

                ' Set DAC A to mid level:
                I2C.WriteByteWord(AD5667_ADDRESS, AD5667_CMD_WRITE_UPDATE Or AD5567_REG_DAC_A, &H8000)

            Catch e As System.Exception
                Console.WriteLine("Exception: " + e.Message)
                System.Environment.Exit(1)
            End Try

            ' Close I2C host:
            I2C.Dispose()
            I2C = Nothing
        Else
            Console.WriteLine("No I2C host available!")
            Environment.Exit(1)
        End If

        Environment.Exit(0)
    End Sub

End Module