1.首先在nuget中安装S7NetPlus
下面是读写方法
更多信息可以参考
Home · S7NetPlus/s7netplus Wiki · GitHub
下面的代码测试了Bool,Int,DInt,LReal四中类型。操作PLC感觉比较麻烦。测了好几天才成功。
环境 win10纯净版+博途V17+PLC1200
using CompoundingDeviceWeb.Helper;
using S7.Net;
using System.Diagnostics;namespace CompoundingDeviceWeb.Communication
{public class S7Net{public static S7Net? Instance;public static bool IsConnected { get; set; }public static bool IsAvailable { get; set; }private Plc plc;/*bool DBXDint DBDReal DBWDBD是双字、DBW是字、DBB是字节Siemens C#
BOOL bool
BYTE byte
WORD short / ushort
DWORD int / uint
INT short / ushort
DINT int / uint
REAL float
LREAL double*/public static S7Net GetInstance(){if (Instance == null){Instance = new S7Net();}return Instance;}public async void Connect(){string PLCIP = AppSettingsHelper.Configuration["PLC:IP"];plc = new Plc(CpuType.S71500, PLCIP, 0, 1);try{plc.Open();Debug.WriteLine($"PLC Connect {plc.IsConnected} ");IsConnected = plc.IsConnected;}catch (Exception ex){LogHelper.Error(ex.Message);IsConnected = false;}finally{//IsAvailable =Debug.WriteLine("PLC Connect");SendPLCConnectStatus();}}public string PLCRead(string type, int DB, int startByteAdr, byte bitAdr = 0){if (plc == null || !IsConnected){Connect();}string Result = "";switch (type.ToUpper()){case "BOOL":Result = ((bool)plc.Read(DataType.DataBlock, DB, startByteAdr, VarType.Bit, 1,bitAdr)).ToString();break;case "BYTE":Result = ((byte)plc.Read(DataType.DataBlock, DB, startByteAdr, VarType.Byte, 1)).ToString();break;case "INT":Result = (plc.Read(DataType.DataBlock, DB, startByteAdr, VarType.Int, 1)).ToString();break;case "DINT":Result = ((Int32)plc.Read(DataType.DataBlock, DB, startByteAdr, VarType.DInt, 1)).ToString();break;case "LREAL":Result = ((double)plc.Read(DataType.DataBlock, DB, startByteAdr, VarType.LReal, 1)).ToString();break;}SendPLCConnectStatus();return Result;}public string PLCWrite(string type, int DB, int startByteAdr,string value, byte bitAdr = 0){if (plc == null || !IsConnected){Connect();}string Result = "";switch (type.ToUpper()){case "BOOL":plc.Write(DataType.DataBlock, DB, startByteAdr, bool.Parse(value),bitAdr);break;case "BYTE":plc.Write(DataType.DataBlock, DB, startByteAdr, value, bitAdr); break;case "INT": plc.Write(DataType.DataBlock, DB, startByteAdr, (ushort)(int.Parse(value)));break;case "DINT":plc.Write(DataType.DataBlock, DB, startByteAdr, Int32.Parse(value));break;case "LREAL":double MyData = Convert.ToDouble(value);plc.Write(DataType.DataBlock, DB, startByteAdr, MyData);break;}return Result;}}
}
另外博途要设置 允许远程操作否则S7Net会报错!
报错的信息也有说要设置下面。我这里是设置上面就OK了