TwinCAT3 ADS协议在C#中的使用

本文详细介绍了如何使用ADS协议使C#应用程序与TwinCAT3环境中的变量进行交互,包括创建项目、引用库文件、实例化ADS客户端、变量获取与赋值等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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);

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值