操作本例之前,参考准备文章:《在TwinCAT 3.0上开发PLC编程调试Lamp DEMO》https://www.jianshu.com/p/0bea791e24c7
1. 创建Windows Forms C#工程
在Solution下,选择Add new project,选择Visual C#下的Classic Desktop中的Windows Forms Application。
.Net framework 版本选择4.0。
2. 添加ADS支持
在Project窗口中选择References,右键点击Add Reference,Browse中选择TwinCAT sdk所在目录:C:\TwinCAT\AdsApi.NET\v4.0.30319,并添加TwinCAT.Ads.dll库。
![](https://img.haomeiwen.com/i10658030/df352cf79ce60986.png)
3. 建立ADS链接
创建TcAdsClient实例,链接851端口。
bool bLampStat = false;
int hvarLamp;
AdsStream dataStream;
TcAdsClient tcClient;
private void Form1_Load(object sender, EventArgs e)
{
tcClient = new TcAdsClient();
try
{
tcClient.Connect(851);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (!tcClient.IsConnected)
{
this.Close();
}
}
3. 通过ADS读取Lamp状态
通过CreateVariableHandle函数,指定PLC中的变量,调用ReadAny函数读取相关的数值。
private void updateLampBtn()
{
int hvar = tcClient.CreateVariableHandle("MAIN.lamp");
bLampStat = (bool)(tcClient.ReadAny(hvar, typeof(bool)));
buttonToggleLamp.Text = bLampStat ? "Lamp ON" : "Lamp Off";
tcClient.DeleteVariableHandle(hvar);
}
4. 通过ADS写入RocketSwitch状态
通过CreateVariableHandle函数,指定PLC中的变量,调用WriteAny函数写入相关的数值。
private void buttonToggleLamp_Click(object sender, EventArgs e)
{
int hvar = tcClient.CreateVariableHandle("MAIN.Switch");
tcClient.WriteAny(hvar, !bLampStat);
tcClient.DeleteVariableHandle(hvar);
}
5. 注册通知Lamp状态的改变
注册Event函数tcClient_OnNotification(),用于监听lamp变量的变化。
dataStream = new AdsStream(1 * 2);
hvarLamp = tcClient.AddDeviceNotification("MAIN.lamp", dataStream, 0, 2, AdsTransMode.OnChange, 100, 0, null);
tcClient.AdsNotification += new AdsNotificationEventHandler(tcClient_OnNotification);
实现Event相应函数,注意避免跨线程操作UI。
public void tcClient_OnNotification(object sender, AdsNotificationEventArgs e)
{
try
{
e.DataStream.Position = e.Offset;
if (e.NotificationHandle == hvarLamp)
{
bLampStat = e.DataStream.ReadByte() > 0 ? true : false;
SetText(bLampStat ? "Lamp ON" : "Lamp Off");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public delegate void StringArgReturningVoidDelegate(string str);
private void SetText(string str)
{
if (this.buttonToggleLamp.InvokeRequired)
{
StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetText);
this.Invoke(d, new object[] { str });
}
else
{
this.buttonToggleLamp.Text = str;
}
}
至此,实现了通过Windows Forms Application的Button控制PLC中的lamp控件,并经过Notification接收lamp改变的消息。另外,可以通过Visualization中的RocketSwitch控制lamp控件,并且在Windows Forms Application同步状态。
如果有HMI和PLC编程相关的交流,可以微信联系VictorACheung。
HMI和PLC编程相关文章参考:
《在Windows 10上安装TwinCAT 3.0》https://www.jianshu.com/p/77c00ab76efa
《在TwinCAT 3.0上开发PLC编程调试Lamp DEMO》 https://www.jianshu.com/p/0bea791e24c7
《利用C#通过ADS与TwinCAT 3.0的PLC通信DEMO》 https://www.jianshu.com/p/678ef8f40bce
网友评论