6ES7288-2DR16-0AA0现货西门子代理
6ES7288-2DR16-0AA0现货西门子代理
6ES7288-2DR16-0AA0现货西门子代理
一个连接西门子plc设备的.net库,搞自动化的有福了!
前言
(一)S7Net动态库说明
如下图所示,rack为0,slot为1。
public Plc(CpuType cpu, string ip, short rack, short slot); public enum CpuType { S7200 = 0, S7300 = 10, S7400 = 20, S71200 = 30, S71500 = 40 }
获取是否连接成功:
public bool IsConnected { get; }
连接PLC:
public void Open(); public Task OpenAsync();
按位写操作:参数db代表访问的DB块编号,如下图所示UISendInt编号为3,UIReadInt编号为4。
public void WriteBit(DataType dataType, int db, int startByteAdr, int bitAdr, bool value); public enum DataType { Counter = 28, Timer = 29, Input = 129, Output = 130, Memory = 131, DataBlock = 132 }
public byte[] ReadBytes(DataType dataType, int db, int startByteAdr, int count);
public void WriteBytes(DataType dataType, int db, int startByteAdr, byte[] value);
(二)PLC设置
(三)C#程序
using S7.Net;
Plc plc; public S7(S7DataType.CpuType cpuType,string ip,Int16 rack,Int16 slot) { plc = new Plc((CpuType)cpuType,ip, rack,slot); } ~S7() { this.plc.Close(); }
public void OpenAsync() { this.plc.OpenAsync(); } public void Close() { this.plc.Close(); }
public byte[] PlcReadBytes(int db, int startByteAdr=0, int count=1) { try { lock (this) { return this.plc.ReadBytes(DataType.DataBlock, db, startByteAdr, count); } } catch { return new byte[2]; } } public void PlcWriteBytes(int db, byte[] value, int startByteAdr = 0) { lock (this) { this.plc.WriteBytes(DataType.DataBlock, db, startByteAdr, value); } } public void PlcWriteBit(int db, int bitAdr, bool value, S7DataType.DataType dataType = S7DataType.DataType.DataBlock) { int temp1 = bitAdr / 8; int temp2 = bitAdr % 8; lock (this) { this.plc.WriteBit((DataType)dataType, db, temp1, temp2, value); } }
public static byte[] Int16ToBytes(Int16 data) { byte[] temp = new byte[2]; temp[0] =(byte) (data >> 8); temp[1] = (byte)(data); return temp; } public static Int16 BytesToInt16(byte[] bytes) { Int16 temp; temp =(Int16)( bytes[0] << 8 | bytes[1]); return temp; }