Access by variable name

All data that ADS devices make available to the outside is organized by means of IndexGroups and IndexOffset. An IndexGroup can be thought of as a table, with each entry being addressed by the IndexOffset. The TwinCAT PLC has, for example, IndexGroups in which the variables that belong to the input/output or flags regions are stored. IndexGroups are also available to the TwinCAT PLC through which system functions may be addressed.

The IndexGroups ADSIGRP_SYM_HNDBYNAME and ADSIGRP_ SYM_VALBYHND are important for the sample program. The IndexGroup ADSIGRP_SYM_HNDBYNAME is used to request a handle from a PLC variable identified by name. The variable can be accessed with the aid of this handle and the IndexGroup ADSIGRP_SYM_VALBYHND. The variable's handle is passed as the IndexOffset.

Download: sample09-c-ads-dll-readbyname.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"

using namespace std;

void main()

  long      nErr, nPort; 
  AmsAddr   Addr; 
  PAmsAddr  pAddr = &Addr; 
  ULONG     lHdlVar, nData; 
  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;

  // Get the handle of the PLC-variable  
  nErr = AdsSyncReadWriteReq(pAddr, ADSIGRP_SYM_HNDBYNAME, 0x0, sizeof(lHdlVar), &lHdlVar, sizeof(szVar), szVar);
  if (nErr) cerr << "Error: AdsSyncReadWriteReq: " << nErr << '\n';
  do 
  { 
    // Read the value of a PLC-variable, via handle 
    nErr = AdsSyncReadReq( pAddr, ADSIGRP_SYM_VALBYHND, lHdlVar, sizeof(nData), &nData ); 
    if (nErr) 
      cerr << "Error: AdsSyncReadReq: " << nErr << '\n'; 
    else 
      cout << "Value: " << nData << '\n'; 
    cout.flush(); 
    if (nData > 10)
    { 
      // Write the value of the PLC variable to 0 
      nData = 0; 
      nErr = AdsSyncWriteReq(pAddr, ADSIGRP_SYM_VALBYHND, lHdlVar, sizeof(nData), &nData); 
      if (nErr) cerr << "Error: AdsSyncWriteReq: " << nErr << '\n';
    }
  }
  while ( _getch() == '\r');  // Get next value with ENTER-button

  // Release the handle of the PLC-variable
  nErr = AdsSyncWriteReq(pAddr, ADSIGRP_SYM_RELEASEHND, 0, sizeof(lHdlVar), &lHdlVar); 
  if (nErr) cerr << "Error: AdsSyncWriteReq: " << nErr << '\n';

  // Close the communication port
  nErr = AdsPortClose(); 
  if (nErr) cerr << "Error: AdsPortClose: " << nErr << '\n';
}