'A reference to the PhidgetNET.dll must be added to new projects in VB.Net
'From the "Project" menu select "Add Reference"
'From the "Add Reference" window select the "Browse" tab
'Browse to the directory you installed the Phidgets library to
'The default is "C:\Program Files\Phidgets"
'Select "PhidgetsNET.dll" and click "OK"
'To view objects that have been added, select the "View" menu
'Select "Object Browser"
'Then expand the PhidgetsNET.dll item

Public Class Form1
    Dim WithEvents phidgetServo As Phidgets.Servo

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'To reduce code complexity we assume that there is one PhidgetServo
        'attached to the PC before the program is run.
        phidgetServo = New Phidgets.Servo
        'Defaults for text fields
        TextBox1.Text = 90
        TextBox2.Text = "Not Connected"
        phidgetServo.open()
    End Sub

    Public Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
    End Sub

    Private Sub TrackBar1_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrackBar1.Scroll
        Dim i As Integer
        TextBox1.Text = TrackBar1.Value
        'Update all motors to the TrackBar value for PhidgetServo 1-Motor this will loop once
        'for PhidgetServo 4-Motor this will loop 4 times
        For i = 0 To phidgetServo.servos.Count - 1
            phidgetServo.servos(i).Position = TrackBar1.Value
        Next i
    End Sub

    Private Sub phidgetServo_Attach(ByVal sender As Object, ByVal e As Phidgets.Events.AttachEventArgs) Handles phidgetServo.Attach
        'When the Phidget servo attaches update the form text boxes
        TextBox2.Text = "Connected"
        TextBox3.Text = phidgetServo.servos.Count
        TextBox4.Text = (Str(phidgetServo.SerialNumber))
        TrackBar1.SetRange(phidgetServo.servos(0).PositionMin + 1, phidgetServo.servos(0).PositionMax)

    End Sub
    Private Sub phidgetServo_Detach(ByVal sender As Object, ByVal e As Phidgets.Events.DetachEventArgs) Handles phidgetServo.Detach
        'If the Phidget servo detaches close the form
        Me.Close()

    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'If the form closes and the Phidget servo is attached Close it.
        If phidgetServo.Attached = True Then
            phidgetServo.close()
        End If
    End Sub

    Private Sub phidgetServo_Error(ByVal sender As Object, ByVal e As Phidgets.Events.ErrorEventArgs) Handles phidgetServo.Error
        'If the Phidget servo is not attached when the form opens show
        'message box and close the form
        MessageBox.Show(e.Description)
        Me.Close()
    End Sub
End Class


