Accessing an array in the PLC
An array, located in the PLC, is to be read. The variable is addressed here by handle. The AdsSyncReadReq() function passes the length of the entire array. The address of the first array element is used as the variable.
Download: sample07-c-ads-dll-arrayaccess.zip
#include <iostream.h>
#include <windows.h>
#include <conio.h>
// ADS headers
#include "C:\TwinCAT\AdsApi\TcAdsDll\Include\TcAdsDef.h"
#include "C:\TwinCAT\AdsApi\TcAdsDll\Include\TcAdsApi.h"
void main()
{
long nErr, nPort;
AmsAddr Addr;
PAmsAddr pAddr = &Addr;
unsigned long lHdlVar;
int nIndex;
short Data[10];
char szVar []={"MAIN.PLCVar"};
// Open communication port on the ADS router
nPort = AdsPortOpen();
nErr = AdsGetLocalAddress(pAddr);
if (nErr) cerr << "Error: AdsGetLocalAddress: " << nErr << '\n';
pAddr->port = AMSPORT_R0_PLC_RTS1;
// Fetch handle for the PLC variable
nErr = AdsSyncReadWriteReq( pAddr,
ADSIGRP_SYM_HNDBYNAME,
0x0,
sizeof(lHdlVar),
lHdlVar,
sizeof(szVar),
szVar);
if (nErr) cerr << "Error: AdsSyncReadWriteReq: " << nErr << '\n';
// Read values of the PLC variables (by handle)
nErr = AdsSyncReadReq(pAddr, ADSIGRP_SYM_VALBYHND, lHdlVar, sizeof(Data), &Data[0]);
if (nErr)
cerr << "Error: AdsSyncReadReq: " << nErr << '\n';
else
{
for (nIndex = 0; nIndex < 10; nIndex++)
cout << "Data[" << nIndex << "]: " << Data[nIndex] << '\n';
}
cout.flush();
_getch();
// Close communication port
nErr = AdsPortClose();
if (nErr) cerr << "Error: AdsPortClose: " << nErr << '\n';
}
PLC program
PROGRAM MAIN
VAR
PLCVar : ARRAY[0..9] OF WORD;
TP_1 : ARRAY[0..9] OF TP;
TOGGEL : BOOL;
nIndex : INT;
END_VAR
TOGGEL := NOT TOGGEL;
FOR nIndex := 0 TO 9 DO
TP_1[nIndex]( IN := TOGGEL, PT := t#1s);
IF (TP_1[nIndex].Q = 0) THEN
PLCVar[nIndex] := PLCVar[nIndex] + 1 + nIndex;
END_IF
END_FOR