• C#与西门子PLC S71500 S7协议通信(2) 读写数据


    1.类库使用S7netplus

    2.连接PLC

    private Plc plc = null;
    //PLC类型 IP地址 机架号 槽号
    Plc MyPlc = new Plc(CpuType.S71500, "192.168.1.10", 0, 0);
    MyPlc.Open();
    if (MyPlc.IsConnected == false)
    {
      MessageBox.Show("PLC连接失败");
    }
    else
    {
      MessageBox.Show("PLC连接成功");
      plc = MyPlc;
    }                

    3.读写数据   这边注意:String稍微特殊。参考S7.Net与西门子PLC通讯——纯新手必看 - Minily - 博客园 (cnblogs.com)

           //Bool
                plc.Write("DB1.DBX0.0", true);
                var IsRight = plc.Read("DB1.DBX0.0");
                Console.WriteLine("DB1.DBX0.0: " + IsRight);
    
                //Int
                plc.Write("DB1.DBW2.0", Convert.ToInt16(1));
                int Score = (ushort)plc.Read("DB1.DBW2.0");
                Console.WriteLine("DB1.DBW2.0: " + Score);
    
                // Real
                plc.Write("DB1.DBD4.0", Convert.ToSingle(1.1));
                var Money = ((uint)plc.Read("DB1.DBD4.0")).ConvertToFloat();
                Console.WriteLine("DB1.DBD4.0: " + Money);
    
                //String写入
                var temp = Encoding.ASCII.GetBytes("Chen");   //将val字符串转换为字符数组
                var bytes = S7.Net.Types.S7String.ToByteArray("Chen", temp.Length);
                plc.WriteBytes(DataType.DataBlock, 1, 8, bytes);
                //String读取
                var reservedLength = (byte)plc.Read(DataType.DataBlock, 1, 8, VarType.Byte, 1);//获取字符串长度
                var Name = (string)plc.Read(DataType.DataBlock, 1, 8, VarType.S7String, reservedLength);//获取对应长度的字符串
                Console.WriteLine("DB1.8.0: " + Name);
    
                // DInt
                plc.Write("DB1.DBD264.0", Convert.ToInt32(20));
                var dIntVar = (uint)plc.Read("DB1.DBD264.0");
                Console.WriteLine("DB1.DBD264.0: " + dIntVar);
    
                // DWord
                plc.Write("DB1.DBD268.0", 123456);
                var dWordVar = (uint)plc.Read("DB1.DBD268.0");
                Console.WriteLine("DB1.DBD268.0: " + dWordVar);
    
                // Word
                plc.Write("DB1.DBD270.0", 12345678);
                var wordVar = (uint)plc.Read("DB1.DBD270.0");
                Console.WriteLine("DB1.DBD270.0: " + wordVar);

    4.测试成功

    TIA博图软件 可以在线监视数据

  • 相关阅读:
    Python之模块
    Python之request模块-基础用法
    Linux小知识点
    python之pip安装软件包常用命令
    windows设置多个JDK环境
    window配合虚拟机VMware搭建虚拟ubuntu服务器入坑集锦
    Linux服务器相关信息查询
    达梦数据库
    创业公司如何快速构建高效的监控系统?
    干货分享:智慧工厂时代下大数据 + 智能的深度实践
  • 原文地址:https://www.cnblogs.com/cdjbolg/p/16394927.html
Copyright © 2020-2023  润新知