C# 和 OPC DA 服务器通信的代码
时间: 2023-11-09 18:05:51 浏览: 40
以下是使用C#和OPC DA服务器进行通信的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OPCAutomation;
namespace OPCDASample
{
class Program
{
static void Main(string[] args)
{
OPCServer opcServer = new OPCServer();
OPCGroups opcGroups;
OPCGroup opcGroup;
OPCItems opcItems;
OPCItem opcItem;
// 连接到OPC服务器
opcServer.Connect("OPCServerName");
// 创建OPC组
opcGroups = opcServer.OPCGroups;
opcGroup = opcGroups.Add("OPCGroupName");
opcGroup.UpdateRate = 1000; // 更新频率为每秒1次
opcGroup.IsActive = true;
// 创建OPC项
opcItems = opcGroup.OPCItems;
opcItem = opcItems.AddItem("OPCItemName", 1);
// 读取OPC项的值
object itemValue;
OPCItemState itemState;
opcItem.Read(1, out itemValue, out itemState);
Console.WriteLine("OPCItemValue: " + itemValue);
// 写入OPC项的值
opcItem.Write("NewOPCItemValue");
// 断开与OPC服务器的连接
opcServer.Disconnect();
}
}
}
```
请注意,此示例代码仅用于演示目的。实际应用程序中可能需要添加错误处理和其他功能。