Zugriff per Variablenname

Download

Voraussetzungen

Sprache / IDE

Beispielprogram auspacken

C# / Visual Studio

Sample15.zip

Beschreibung

Das folgende Programm greift auf eine SPS-Variable zu, die keine Adresse besitzt. Der Zugriff muss deshalb per Variablenname erfolgen. Die SPS-Variable wird vom Beispielprogramm wieder auf 0 zurückgesetzt, wenn diese den Wert 10 überschritten hat.

C# Programm


static void Main(string[] args)
{
//Create a new instance of class TcAdsClient
TcAdsClient tcClient = new TcAdsClient();
AdsStream dataStream = new AdsStream(4);
AdsBinaryReader binReader = new AdsBinaryReader(dataStream);

int iHandle = 0;
int iValue = 0;

try
{
// Connect to local PLC - Runtime 1 - TwinCAT 3 Port=851
tcClient.Connect(851);

//Get the handle of the PLC variable "PLCVar"
iHandle = tcClient.CreateVariableHandle("MAIN.PLCVar");

Console.WriteLine("Press enter to continue and any other key to abort..");

do
{
//Use the handle to read PLCVar
tcClient.Read(iHandle, dataStream);
iValue = binReader.ReadInt32();
dataStream.Position = 0;

Console.WriteLine("Current value is: " + iValue);

if (iValue >= 10)
{
//Reset PLC variable to zero
tcClient.WriteAny(iHandle, 0);
}

} while (Console.ReadKey().Key.Equals(ConsoleKey.Enter));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
//Delete variable handle
tcClient.DeleteVariableHandle(iHandle);
tcClient.Dispose();
}
}