Write array to PLC or read array from PLC
System requirements:
- Delphi 6.0 or higher;
- TwinCAT v2.10 or higher
Use the "released" methods for particular data types. If you want, for example, to read an array in the PLC of type INT, then the following methods may be used, depending on the access type:
AdsSyncReadIntegerVarReq( hVar : Integer, length : Integer, var pData : Smallint )
AdsSyncReadIntegerReq( indexGroup : Integer, indexOffset : Integer, length : Integer, var pData : Smallint )
AdsSyncWriteIntegerVarReq(hVar : Integer, length : Integer, var pData : Smallint )
AdsSyncWriteIntegerReq( indexGroup : Integer, indexOffset : Integer, length : Integer, var pData : Smallint )
AdsReadIntegerReq( nInvokeId : Integer, nIndexGroup : Integer, nIndexOffset : Integer, cbLength : Integer )
AdsWriteIntegerReq( nInvokeId : Integer, nIndexGroup : Integer, nIndexOffset : Integer, cbLength : Integer, var pData : Smallint )
String arrays cannot be accessed in this way. The length of the data to be read or written is determined by the number of elements to be read or written multiplied by the byte size of an element. This length must be passed in the length or cbLength parameters. The parameter pData is used to pass the first element of the Delphi array.
Sample:
PROGRAM MAIN
VAR
varIntArray :ARRAY[1..9] OF INT:=9(1);
END_VAR
Delphi 6 program:
Reading an array from the PLC:
procedure TForm1.SyncReadArrayVarButtonClick(Sender: TObject);
var i, hVar, AdsResult:integer;
varIntArray : ARRAY[1..9] OF Smallint;
begin
AdsResult := AdsOcx1.AdsCreateVarHandle( 'MAIN.VARINTARRAY', hVar );
if AdsResult = 0 then
begin
AdsResult := AdsOcx1.AdsSyncReadIntegerVarReq( hVar, sizeof(varIntArray), varIntArray[1] );
if AdsResult = 0 then
begin
ListBox1.Clear();
for i:=1 to 9 do
ListBox1.Items.Add( Format('varIntArray[%d] = %d', [i, varIntArray[i]] ) );
end
else Label1.Caption := Format('AdsSyncReadIntegerVarReq error:%d', [AdsResult] );
AdsOcx1.AdsDeleteVarHandle( hVar );
end
else Label1.Caption := Format('AdsCreateVarHandle error:%d', [AdsResult] );
end;
Writing an array into the PLC:
procedure TForm1.SyncWriteArrayVarButtonClick(Sender: TObject);
var i, hVar, AdsResult:integer;
varIntArray : ARRAY[1..9] OF Smallint;
begin
for i:=1 to 9 do
varIntArray[i] := i;
AdsResult := AdsOcx1.AdsCreateVarHandle( 'MAIN.VARINTARRAY', hVar );
if AdsResult = 0 then
begin
AdsResult := AdsOcx1.AdsSyncWriteIntegerVarReq( hVar, sizeof(varIntArray), varIntArray[1] );
if AdsResult > 0 then
Label1.Caption := Format('AdsSyncWriteIntegerVarReq error:%d', [AdsResult] );
AdsOcx1.AdsDeleteVarHandle( hVar );
end
else Label1.Caption := Format('AdsCreateVarHandle error:%d', [AdsResult] );
end;
Language / IDE | Unpack sample program |
---|---|
Delphi XE2 | |
Delphi 6 or higher (classic) |