|
Read/Write of OPC Data with OPC Data Control using VB Code Writing the Code - sample code without comments
Now it's time to write the Visual Basic code for this example. Double click the Exit
button on your form. This will bring up the code section for our form. Important: In the code shown below, you only need to insert the code NOT shown in blue text. We also have this code available with comments.
Feel free to "cut and paste" the code from here. You may also download our code exactly as it's written for this document and modify it to suit your needs.
Insert the following code for Exit button click event.
Private Sub cmdExit_Click() Dim result As Long
result = OPCData1.Disconnect
'end program End End Sub
Insert the following code for Multiple Write button click event.
Private Sub cmdMultipleWrite_Click()
Dim result As Long Dim States As Variant Dim VarNames(0 To 1) As String
Dim VarValues(0 To 1) As Variant
Label1 = "" Label2 = ""
VarNames(0) = "Device1.Group1.Tag1" VarNames(1) = "Device1.Group1.Tag2"
VarValues(0) = txtMultipleWriteValue1.Text VarValues(1) = txtMultipleWriteValue2.Text
result = OPCData1.WriteMultiVariables(VarNames, VarValues, States)
If result = 0 Then Label1 = "Multiple Write Success" Else
Label1 = "Multiple Write Failure" End If
End Sub
Type the following code for Multiple Read button click event.
Private Sub cmdMultipleRead_Click()
Dim result As Long Dim States As Variant Dim VarValues As Variant
Dim VarNames(0 To 1) As String
Label2 = ""
VarNames(0) = "Device1.Group1.Tag1" VarNames(1) = "Device1.Group1.Tag2"
result = OPCData1.ReadMultiVariables(VarNames, VarValues, States)
If result = 0 Then
Label2 = "Multiple Read Success Value 1 = " & VarValues(0) & " Value 2 = " &
VarValues(1) Else Label2 = "Multiple Read Failure" End If
End Sub
Type the following code for Single Read button click event.
Private Sub cmdSingleRead_Click()
Dim result As Long Dim State As Long Dim Value As Variant
Label4 = ""
result = OPCData1.ReadVariable("Device1.Group1.Tag1", Value, State, 3000)
If result = 0 Then Label4 = "Single Read Success Value = " & Value Else
Label4 = "Single Read Failure" End If
End Sub
Type the following code for Single Write button click event.
Private Sub cmdSingleWrite_Click()
Dim result As Long Dim Value As Variant
Label3 = "" Label4 = ""
Value = txtSingleWriteValue
result = OPCData1.WriteVariable("Device1.Group1.Tag1", Value, 3000)
'display write result If result = 0 Then Label3 = "Single Write Success"
Else Label3 = "Single Write Failure" End If
End Sub
You should now be able to run your project and access data from your plc.
|