您当前的位置: 首页 >  ar

txwtech

暂无认证

  • 3浏览

    0关注

    813博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

c#通过OPC server与西门子S7-200 smart实现通信示范代码txwtech

txwtech 发布时间:2019-10-30 12:23:06 ,浏览量:3

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();//连接OPC

            if (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

 

关注
打赏
1665060526
查看更多评论
立即登录/注册

微信扫码登录

0.0377s