Transmitting structures to the PLC

Download: 'Transmitting structures to the PLC'

This example shows how to write a structure to the PLC via ADS. The elements in the structure have different data types:


#include <stdio.h>
#include <tchar.h>
#include "windows.h"

// ADS headers for TwinCAT 3
#include "C:\TwinCAT\3.0\AdsApi\TcAdsDll\Include\TcAdsDef.h"
#include "C:\TwinCAT\3.0\AdsApi\TcAdsDll\Include\TcAdsAPI.h"

// Create new struct
typedef struct PlcStruct {
INT16 shortVal;
INT32 intVal;
byte byteVal;
DOUBLE doubleVal;
FLOAT floatVal;
} SPlcVar, *pSPlcVar;

int _tmain(int argc, _TCHAR* argv[])
{
long nErr, nPort;
AmsAddr Addr;
PAmsAddr pAddr = &Addr;
ULONG lHdlVar;

// New struct. Assign test values
PlcStruct PlcVar;

PlcVar.shortVal = 1;
PlcVar.intVal = 2;
PlcVar.byteVal = 3;
PlcVar.doubleVal = 4.04;
PlcVar.floatVal = (FLOAT)5.05;

// Declare PLC variable which should notify changes
char szVar []={"MAIN.PLCVar"};


// Extract values from struct and write to byte array
// Circumvent memory holes caused by padding
BYTE *pData = new BYTE[19];
int nIOffs = 0;

memcpy_s(&pData[nIOffs], 19, &PlcVar.shortVal, 2);
nIOffs += 2;
memcpy_s(&pData[nIOffs], 17, &PlcVar.intVal, 4);
nIOffs += 4;
memcpy_s(&pData[nIOffs], 13, &PlcVar.byteVal, 1);
nIOffs++;
memcpy_s(&pData[nIOffs], 12, &PlcVar.doubleVal, 8);
nIOffs += 8;
memcpy_s(&pData[nIOffs], 4, &PlcVar.floatVal, 4);


// Open communication port on the ADS router
nPort = AdsPortOpen();
nErr = AdsGetLocalAddress(pAddr);
if (nErr) printf("Error: Ads: Open port: %d\n", nErr);

// TwinCAT 3 PLC1 = 851
pAddr->port = 851;

// Get variable handle
nErr = AdsSyncReadWriteReq(pAddr,
ADSIGRP_SYM_HNDBYNAME,
0x0,
sizeof(lHdlVar),
&lHdlVar,
sizeof(szVar),
szVar);

// Write the struct to the Plc
AdsSyncWriteReq(pAddr,
ADSIGRP_SYM_VALBYHND, // IndexGroup
lHdlVar, // IndexOffset
0x13, // Size of struct
(void*) pData);

if (nErr) printf("Error: Ads: Write struct: %d\n", nErr);

// Close communication
delete [] pData;

//Release handle of plc variable
nErr = AdsSyncWriteReq(pAddr, ADSIGRP_SYM_RELEASEHND, 0, sizeof(lHdlVar), &lHdlVar);
if (nErr) printf("Error: AdsSyncWriteReq: %d \n", nErr);

nErr = AdsPortClose();
if (nErr) printf("Error: Ads: Close port: %d\n", nErr);

getchar();
}