C#与西门子PLC S7-1500 S7协议PLC读写数据

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稍微特殊

 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);

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

C#与西门子PLC S7-1500 S7协议PLC读写数据_第1张图片

你可能感兴趣的:(c#,前端,开发语言)