亲爱的工程师们,是否正在为如何方便地连接西门子PLC而烦恼?今天给大家推荐一款强大且实用的.NET库——s7netplus。这是一款专门用于连接西门子PLC的库,让你在.NET环境下轻松实现PLC的通讯和控制。S7Net Plus 是 Juergen1969 在 S7.Net 项目上所做的工作的延续。由于S7.net停止了更新,S7Net Plus作者在做一些自动化工作,看到了一些可以改进代码库的地方。因为 S7.Net 作者没有回应 对于S7Net Plus作者提交代码的请求,所以S7Net Plus作者决定在 GitHub 上从 S7.Net的基础上继续开发更新。
S7.Net is compatible with S7-200, S7-300, S7-400, S7-1200, S7-1500
使用s7netplus非常简单,只需按照以下步骤操作即可:
- To create an instance of the driver you need to use this constructor:
- public Plc(CpuType cpu, string ip, Int16 rack, Int16 slot)
- Cpu: this specify what CPU you are connecting to. The supported CPU are:
- public enum CpuType {
- S7200 = 0,
- S7300 = 10,
- S7400 = 20,
- S71200 = 30,
- S71500 = 40,
- }
- Ip: this contains the IP address of the CPU of external Ethernet card
- Rack: this contains the rack of the plc, that you can find in hardware configuration in Step7
- Slot: this is the slot of the CPU, that you can find in hardware configuration in Step7
- Example:
- This code creates a Plc object for a S7-300 plc at the IP address 127.0.0.1, that it’s localhost, for a plc that
- it’s in rack 0 and a cpu that it’s in slot 2 of the hardware configuration:
- Plc plc = new Plc(CpuType.S7300, "127.0.0.1", 0, 2);
-
- Connecting to the PLC
- public ErrorCode Open()
- For example this line of code open the connection:
- plc.Open();
- Disconnecting from the PLC
- public void Close()
- For example this closes the connection:
- plc.Close();
- public byte[] ReadBytes(DataType dataType, int db, int startByteAdr, int count)
- public ErrorCode WriteBytes(DataType dataType, int db, int startByteAdr, byte[] value)
-
- public enum DataType
- {
- Input = 129,
- Output = 130,
- Memory = 131,
- DataBlock = 132,
- Timer = 29,
- Counter = 28
- }
-
- Example:
- This method reads the first 200 bytes of DB1:
- var bytes = plc.ReadBytes(DataType.DataBlock, 1,0,200);
- Example with recursion:
- private List<byte> ReadMultipleBytes(int numBytes, int db, int startByteAdr = 0)
- {
- List<byte> resultBytes = new List<byte>();
- int index = startByteAdr;
- while (numBytes > 0)
- {
- var maxToRead = (int)Math.Min(numBytes, 200);
- byte[] bytes = ReadBytes (DataType.DataBlock, db, index, (int)maxToRead);
- if (bytes == null)
- return new List<byte>();
- resultBytes.AddRange(bytes);
- numBytes -= maxToRead;
- index += maxToRead;
- }
- return resultBytes;
- }
-
通过使用s7netplus库,自动化工程师们可以更加便捷地与西门子PLC进行通讯和控制。无论是初学者还是资深工程师,都能从中受益匪浅。
https://github.com/S7NetPlus/s7netplus