Read synchronously from the PLC
In this sample program the value in flag double word 0 in the PLC is read and displayed on the screen.
Download: sample03-c-ads-dll-readflag.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;
DWORD dwData;
// Kommunikationsport auf dem ADS Router öffnen
nPort = AdsPortOpen();
nErr = AdsGetLocalAddress(pAddr);
if (nErr) cerr << "Error: AdsGetLocalAddress: " << nErr << '\n';
// TwinCAT2 RTS1 Port = 801
pAddr->port = 801;
// Werte aus MD0 auslesen und anzeigen
do
{
nErr = AdsSyncReadReq(pAddr, 0x4020, 0x0, 0x4, &dwData);
if (nErr) cerr << "Error: AdsSyncReadReq: " << nErr << '\n';
else cout << dwData << '\n';
cout.flush();
}
while (getch() == '\r'); // mit Carriage return nächsten Wert auslesen, sonst Ende
// Kommunikationsport schließen
nErr = AdsPortClose();
if (nErr) cerr << "Error: AdsPortClose: " << nErr << '\n';
}