TwinCAT3 ADS协议在C#中的使用

版权声明:Dirichlet_zju https://blog.csdn.net/Dirichlet_zju/article/details/85263063

使用ADS协议可以使上位机访问(获取与赋值)TwinCAT3中的变量。

一、使用

1.新建TwinCAT3项目及解决方案;

2.建立PLC程序和C#项目

3.C#项目引用库文件TwinCAT.Ads.dll,并using TwinCAT.Ads

4.实例化一个ADS客户端

private TcAdsClient tcAdsClient = new TcAdsClient();
tcAdsClient.Connect(851);//连接

二、变量获取与使用

1.变量获取

//变量获取
private int hander1, hander2, hd1, hd2, hd3, hd4;//申明int类型句柄
//生成用户句柄变量
hander1 = tcAdsClient.CreateVariableHandle("MAIN.ivar");
hander2 = tcAdsClient.CreateVariableHandle("MAIN.bvar");
hd1 = tcAdsClient.CreateVariableHandle("MAIN.bvar[0]");
hd2 = tcAdsClient.CreateVariableHandle("MAIN.bvar[1]");
hd3 = tcAdsClient.CreateVariableHandle("MAIN.bvar[2]");
hd4 = tcAdsClient.CreateVariableHandle("MAIN.svar");

 2.变量使用

/****全局变量*****/
private AdsStream iStream;    //int
private AdsStream bStream;    //bool
private AdsStream sStream;    //string
private AdsBinaryReader iBinaryReader;
private AdsBinaryReader bBinaryReader;
private AdsBinaryReader sBinaryReader;
private AdsBinaryWriter sBinaryWriter;

/*****初始化*****/
iStream = new AdsStream(3 * 2);//流数据必须赋值大小,否则报错:无法在流的结尾之外进行读取
bStream = new AdsStream(3);
sStream = new AdsStream(7);
iBinaryReader = new AdsBinaryReader(iStream);
bBinaryReader = new AdsBinaryReader(bStream);
sBinaryReader = new AdsBinaryReader(sStream);
sBinaryWriter = new AdsBinaryWriter(sStream);

/*****获取*****/
//按句柄异步读取数据并写入流
tcAdsClient.Read(hander1, iStream);
tcAdsClient.Read(hander2, bStream);
tcAdsClient.Read(hd4, sStream);

//初始化流的当前位置,对于int类型->>>>
iStream.Position = 0;            //否则报错:无法在流的结尾之外进行读取
textBox1.Text = iBinaryReader.ReadInt16().ToString();//读取两位数,同时position后移两位(ReadInt16的作用)
//...重复三次读取,bool类型相似->>>>>
bool b = bBinaryReader.ReadBoolean();
//string读取两种方法->>>>>
sStream.Position = 0;//流赋初值,很重要
string s;
//1
ASCIIEncoding ascii = new ASCIIEncoding();//或者UnicodeEncoding unicode = new UnicodeEncoding();
s = sBinaryReader.ReadPlcString(4, ascii);
//2
s = sBinaryReader.ReadPlcString(7, unicode);

/*****赋值*****/
sBinaryWriter.WritePlcString(s, 7);

猜你喜欢

转载自blog.csdn.net/Dirichlet_zju/article/details/85263063