Read flag synchronously from the PLC

Download: 'Read flag synchronously from PLC'

In this example program the value in flag double word 0 in the PLC is read and displayed on the screen.

#include <iostream.h>
#include <windows.h>
#include <conio.h>

// ADS headers for TwinCAT 3
#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;
// Open communication port on the ADS router
nPort = AdsPortOpen();
nErr = AdsGetLocalAddress(pAddr);
if (nErr) cerr << "Error: AdsGetLocalAddress: " << nErr << '\n';

// TwinCAT3 PLC1 = 851
pAddr->port = 851;
// Read value from MD0 and display
do
{
nErr = AdsSyncReadReq(pAddr, 0x4020, 0x0, 0x4, &dwData);
if (nErr) cerr << "Error: AdsSyncReadReq: " << nErr << '\n';
cout << dwData << '\n';
cout.flush();
}
while (getch() == '\r'); // Read the next value (use Carriage return as delimitter), stop otherwise
// Close communication port
nErr = AdsPortClose();
if (nErr) cerr << "Error: AdsPortClose: " << nErr << '\n';
}