The answer below is for starting and stopping a specific PLC instance. To change the entire TwinCAT runtime between Config and Run, connect to the System Service ADS port (port 10000) and set the state to AdsState.Run
or AdsState.Config
.
All valid state values can be found here. All the port values can be found here.
static void Main(string[] args)
{
//Create a new instance of class TcAdsClient
TcAdsClient tcClient = new TcAdsClient();
try
{
// Connect to TwinCAT System Service port 10000
tcClient.Connect(AmsPort.SystemService);
// Send desired state
tcClient.WriteControl(new StateInfo(AdsState.Config, tcClient.ReadState().DeviceState));
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
tcClient.Dispose();
}
}
To Start or Stop the TwinCAT runtime programmatically, you can use ADS commands to change AdsState to Run or Stop. Beckhoff provides C# and C++ libraries for this. A C# example:
static void Main(string[] args)
{
//Create a new instance of class TcAdsClient
TcAdsClient tcClient = new TcAdsClient();
try
{
// Connect to local PLC - Runtime 1 - TwinCAT 3 Port=851
tcClient.Connect(851);
Console.WriteLine(" PLC Run\t[R]");
Console.WriteLine(" PLC Stop\t[S]");
Console.WriteLine("\r\nPlease choose \"Run\" or \"Stop\" and confirm with enter..");
string sInput = Console.ReadLine().ToLower();
//Process user input and apply chosen state
do{
switch (sInput)
{
case "r": tcClient.WriteControl(new StateInfo(AdsState.Run, tcClient.ReadState().DeviceState)); break;
case "s": tcClient.WriteControl(new StateInfo(AdsState.Stop, tcClient.ReadState().DeviceState)); break;
default: Console.WriteLine("Please choose \"Run\" or \"Stop\" and confirm with enter.."); sInput = Console.ReadLine().ToLower(); break;
}
} while (sInput != "r" && sInput != "s");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
tcClient.Dispose();
}
}
Source: https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_adssamples_net/185266187.html&id=6127144084214800894
A C++ example is here: https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_adsdll2/9007199379562763.html&id=8444596171373533137
To my knowledge, Automation Interface requires at least Visual Studio Shell to be installed. When you use Automation Interface, you can see an instance of devenv.exe
that gets launched in the background.