Start/stop PLC

Download: 'Start/stop PLC'.

The following program starts or stops run-time system 1 in the PLC.

#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()
{
USHORT nAdsState;
USHORT nDeviceState = 0;
long nErr, nPort;
int ch;
void *pData = NULL;
AmsAddr Addr;
PAmsAddr pAddr = &Addr;

// Open communication port on the ADS router
nPort = AdsPortOpen();
nErr = AdsGetLocalAddress(pAddr);
if (nErr) cerr << "Error: AdsGetLocalAddress: " << nErr << '\n';

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

cout << "(R) -> PLC Run\n";
cout << "(S) -> PLC Stop\n";
cout.flush();
ch = getch();
ch = toupper(ch);
while ( (ch == 'R') || (ch == 'S') )
{
switch (ch)
{
case 'R':
nAdsState = ADSSTATE_RUN;
break;
case 'S':
nAdsState = ADSSTATE_STOP;
break;
}
nErr = AdsSyncWriteControlReq (pAddr, nAdsState, nDeviceState, 0, pData);
if (nErr) cerr << "Error: AdsSyncWriteControlReq: " << nErr << '\n';
ch = getch();
ch = toupper(ch);
}

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