Übertragen von Strukturen an die SPS
Dieses Beispiel zeigt die Übertragung einer Struktur an die SPS per ADS. Die Struktur besteht aus Elementen von verschiedenen Datentypen.
Download: sample20-c-ads-dll-writestructure.zip
#include <stdio.h>
#include <tchar.h>
#include "windows.h"
#include "c:\twincat\adsapi\tcadsdll\include\tcadsdef.h"
#include "c:\twincat\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);
pAddr->port = 801;
// 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);
else printf("Structure successful written\n");
// 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();
}