本文主要是介绍c#通过OPC server与西门子S7-200 smart实现通信示范代码txwtech,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
c#通过OPC server与西门子S7-200 smart实现通信示范代码txwtech
public bool ConnetOPC()//连接OPC并创建组{int i = 0;try{string hostname = Dns.GetHostName();object serverList = opcServer.GetOPCServers(hostname);opcServer.Connect("S7200SMART.OPCServer", "192.168.10.2");//连接OPC,输入本地网口IP地址if (opcServer.ServerState == (int)OPCServerState.OPCRunning)//连接成功{Console.WriteLine("连接OPC成功");opcGroup = opcServer.OPCGroups.Add();//创建组Console.WriteLine("创建组完成");SetGroupProperty();for (i = 0; i < strItemIDs.Length; i++)//创建组里的项{//创建每个项,并为每个项分配编号,范围:1~strItemIDs.Length//因此每个项的编号为它在数组strItemIDs中的索引值+1。opcItems[i] = opcGroup.OPCItems.AddItem("MWSMART.PLC." + strItemIDs[i], i + 1);}Console.WriteLine("创建组里的项完成");SyncReadWriteThread.Start();Console.WriteLine("启动读PLC线程");return true;}else{Console.WriteLine("连接OPC失败" + opcServer.ServerState);return false;}}catch (Exception e){//Console.WriteLine("ConnetOPC函数catch到异常!" + e.Message + " " + i);MessageBox.Show("ConnetOPC函数catch到异常!" + e.Message + "\r\n" + "创建第" + i + "项时发生异常!");return false;}}
连接代码:
private void ToolStripMenuItem_ConnectPLC_Click(object sender, EventArgs e) //菜单栏连接PLC{bool result = false;OPCServer = new COPCServer();result = OPCServer.ConnetOPC();//连接OPCif (result){ConnectPLC_ToolStripMenuItem.BackColor = Color.Green;ConnectPLC_ToolStripMenuItem.Text = "PLC已连接!";ConnectPLC_ToolStripMenuItem.Enabled = false;if (ConnectRobot_ToolStripMenuItem.BackColor == Color.Green) toolStripMenuItem_通讯口设置.BackColor = Color.Green;}else{ConnectPLC_ToolStripMenuItem.BackColor = Color.Red;ConnectPLC_ToolStripMenuItem.Text = "PLC未连接!";ConnectPLC_ToolStripMenuItem.Enabled = true;toolStripMenuItem_通讯口设置.BackColor = Color.Red;}}
源代码这里找: s7-200smart通信项目实例c#.rar
https://blog.csdn.net/txwtech/article/details/96737086
这篇关于c#通过OPC server与西门子S7-200 smart实现通信示范代码txwtech的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!