Accessing an array in the PLC

Task

The PLC contains an array that is to be read by Visual Basic using a read command.

Description

The PLC contains an array of 100 elements of type integer (2 bytes). The array is filled in the PLC with the values 3500 to 3599.
In the load event function of the Visual Basic program, the handle of the PLC variable is fetched first. When the program is terminated, this is released again in the Unload event function.
If the user presses the button on the form, the method AdsSyncRead[Datatype]VarReq() reads the complete array from the PLC into the Visual Basic variable Data.
The variable Data must have the same structure as the corresponding variable in the PLC; 100 elements of type integer (2 bytes). The length specification in the method call is 200, because the length of the requested data is 200 bytes (100 elements with 2 bytes each).
In the following FOR loop, the array from the PLC is displayed in a list box control.

Visual Basic 6 program

Dim hVar As Long
Dim Data(100) As Integer

'--- wird beim Starten aufgerufen ---
Private Sub Form_Load()
  '--- Exception freigeben --- AdsOcx1.EnableErrorHandling = True
  Call AdsOcx1.AdsCreateVarHandle("Main.PLCVar", hVar)
End Sub

'--- wird beim Beenden aufgerufen ---
Private Sub Form_Unload(Cancel As Integer)
  Call AdsOcx1.AdsDeleteVarHandle(hVar)
End Sub

'--- wird vom Bediener aufgerufen ---
Private Sub cmd_read_Click()
  Dim intIndex As Integer
  '--- Array komplett auslesen ---
  Call AdsOcx1.AdsSyncReadIntegerVarReq(hVar, 200, Data(0))
  '--- Array Elemente in Form anzeigen ---
  lstArray.Clear 
  For intIndex = 0 To 99
    lstArray.AddItem (CStr(intIndex) & Chr(vbKeyTab) & _ CStr(Data(intIndex)))
  Next
End Sub

PLC program

PROGRAM MAIN
VAR
  PLCVar : ARRAY [0..99] OF INT;
  Index: BYTE;
END_VAR

FOR Index := 0 TO 99 DO
  PLCVar[Index] := 3500 + INDEX;
END_FOR

 

Language / IDE

Unpack sample program

Visual Basic 6

ADS-OCX Sample01.exe