S7. Net: Ethernet communication driver designed specifically for Siemens PLC

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

S7. Net: Ethernet communication driver designed specifically for Siemens PLC缩略图

Overview

S7. Net is a PLC driver designed specifically for Siemens PLCs, which only supports Ethernet connections. This means that your PLC must have a Profinet CPU or Profinet external card (such as a CPxxx card). S7. Net is fully written in C #, so you can easily debug without dealing with local DLLs.

Supported PLC models

S7. Net is compatible with Siemens PLCs of the following models: S7-200, S7-300, S7-400, S7-1200, and S7-1500.

Start using S7. Net

To start using S7. Net, you need to download and include S7. Net. dll into your project. You can achieve this by downloading the VNet package or by downloading the source code and compiling it.

Create PLC instance, connect and disconnect

When creating a driver instance, you need to use the following constructor:

public Plc(CpuType cpu, string ip, Int16 rack, Int16 slot)
  • cpu: Specify the CPU type you want to connect to. The supported CPU types are:
  public enum CpuType {
      S7200 = 0,
      S7300 = 10,
      S7400 = 20,
      S71200 = 30,
      S71500 = 40,
  }
  • ip: specifies the IP address of the CPU or external Ethernet card.
  • rack: Contains the rack number of the PLC, which can be found in the hardware configuration of Step 7.
  • slot: This is the slot number of the CPU, which can also be found in the hardware configuration of Step 7.

For example, the following code creates a PLC object for S7-300 PLC with IP address 127.0.0.1, located in rack 0 and CPU in slot 2:

Plc plc = new Plc(CpuType.S7300, "127.0.0.1", 0, 2);

Connect to PLC

public void Open()

. For example, the following code line opens the connection:

plc.Open();

Disconnect from PLC

public void Close()

. For example, the following code closes the connection:

plc.Close();

Error handling

Any method may causePlcExceptionYou should implement appropriate error handling.PlcExceptionProvided aErrorCodeAnd an appropriate error message.

The following is an enumeration of incorrect types:

public enum ErrorCode
{
    NoError = 0,
    WrongCPU_Type = 1,
    ConnectionError = 2,
    IPAddressNotAvailable, 
    WrongVarFormat = 10,
    WrongNumberReceivedBytes = 11, 
    SendData = 20,
    ReadData = 30, 
    WriteData = 50
}

Check PLC availability

To check if the PLC is available (open a socket), you can use the property:

public bool IsAvailable

When you check this property, the driver will attempt to connect to the PLC and return true if it can connect, otherwise return false.

Check PLC connection

Checking the PLC connection is simple, as you need to check if the PC socket is connected and if the PLC is still connected to the other end of the socket. In this case, the attributes you need to check are:

public bool IsConnected

You can callOpen()After the method is successful, check this property to see if the connection is still active.

Read Byte/Write Byte

This library provides multiple methods for reading variables. The most basic and commonly used method isReadBytes.

public byte[] ReadBytes(DataType dataType, int db, int startByteAdr, int count)

public void WriteBytes(DataType dataType, int db, int startByteAdr, byte[] value)

This method reads all the bytes you specify from the given memory location. If the number of bytes exceeds the maximum number of bytes that can be transmitted in a single request, this method will automatically process multiple requests.

  • dataType: You must use enumerationDataTypeto specify the memory location:
  public enum DataType
  {
      Input = 129,
      Output = 130,
      Memory = 131,
      DataBlock = 132,
      Timer = 29,
      Counter = 28
  }
  • db: the address of dataType. For example, if you want to read DB1, this field is "1"; If you want to read T45, this field is 45.
  • startByteAdr: The address of the first byte you want to read, for example, if you want to read DB1.DBW200, this is 200.
  • count: Contains the number of bytes you want to read.
  • value[]: Byte array to be read from PLC.

Example: This method reads the first 200 bytes of DB1:

var bytes = plc.ReadBytes(DataType.DataBlock, 1, 0, 200);

Read and decode/write decoded

This method allows you to read and receive decoded results based on the provided varType. This is very useful when you read multiple fields of the same type (such as 20 consecutive DBWs). If you specify VarType.Byte, it has the same functionality as Readbytes.

public object Read(DataType dataType, int db, int startByteAdr, VarType varType, int varCount)

public void Write(DataType dataType, int db, int startByteAdr, object value)
  • dataType: You must use enumerationDataTypeto specify the memory location.
  • db: DataType's address, for example, if you want to read DB1, this field is "1"; If you want to read T45, this field is 45.
  • startByteAdr: The address of the first byte you want to read, for example, if you want to read DB1.DBW200, this is 200.
  • varType: Specify the data you want to convert bytes into.
  public enum VarType
  {
      Bit,
      Byte,
      Word,
      DWord,
      Int,
      DInt,
      Real,
      String,
      StringEx,
      Timer,
      Counter
  }
  • count: Contains the number of variables you want to read.
  • value: To write the value array to the PLC. It can be a single value or an array, just remember that the type is unique (e.g. double array, int array, shorts array, etc.).

Example: This method reads the first 20 DWords of DB1:

var dwords = plc.Read(DataType.DataBlock, 1, 0, VarType.DWord, 20);

Read/write a single variable

This method reads a single variable from the PLC by parsing a string and returning the correct result. Although this is the simplest way to get started, it is very inefficient because the driver sends TCP requests for each variable.

public object Read(string variable)

public void Write(string variable, object value)
  • variable: Specify the variable to be read by using strings such as "DB1. DBB20", "T45", "C21", "DB1. DBD400", etc.

Example: This reads the variable DB1.DBW0. The result must be converted to ushort to obtain the correct 16 bit format in C #.

ushort result = (ushort)plc.Read("DB1.DBW0");

Read Structure/Write Structure

This method reads all bytes from the specified DB to fill the structure in C # and returns the structure containing the value. When you want to read multiple variables in a single data block, it is recommended to use it. The 'Read Structure' and 'Write Structure' methods do not support strings.

The 'read structure' and 'write structure' methods do not support strings.

public object ReadStruct(Type structType, int db, int startByteAdr = 0)

public void WriteStruct(object structValue, int db, int startByteAdr = 0)
  • structType: Type of struct to be read, for example: typeof (MyStruct)
  • db: Index of DB to be read
  • startByteAdr: Specify the first address of the byte to be read (default is zero).

Example: Define a Data Block in a PLC and then Add a structure similar to a DB in a PLC to the Net application:

public struct testStruct
{
    public bool varBool0;
    public bool varBool1;
    public bool varBool2;
    public bool varBool3;
    public bool varBool4;
    public bool varBool5;
    public bool varBool6;
    public byte varByte0;
    public byte varByte1;
    public ushort varWord0;
    public float varReal0;
    public bool varBool7;
    public float varReal1;
    public byte varByte2;
    public UInt32 varDWord;
}

, and then add code to read or write the complete structure:

// 从起始地址0读取DataBlock 1中的结构体
testStruct myTestStruct = (testStruct) plc.ReadStruct(typeof(testStruct), 1, 0);

* * Read Class/Write

Class * *

This method reads all bytes from the specified DB to fill the classes in C #. Class is passed as a reference, using reflection to assign values. When you want to read multiple variables in a single data block, it is recommended to use it. The 'Read Class' and' Write Class' methods do not support strings.

The 'read class' and' write class' methods do not support strings.

public void ReadClass(object sourceClass, int db, int startByteAdr = 0)

public void WriteClass(object classValue, int db, int startByteAdr = 0)
  • sourceClass: Instance of the class you want to assign a value to
  • db: Index of the DB to be read
  • startByteAdr: Specify the first address of the byte to be read (default is zero).

Example: Define a Data Block in a PLC and then Add a class similar to DB in PLC to the Net application:

public class TestClass
{
    public bool varBool0 { get; set;}
    public bool varBool1 { get; set;}
    public bool varBool2 { get; set;}
    public bool varBool3 { get; set;}
    public bool varBool4 { get; set;}
    public bool varBool5 { get; set;}
    public bool varBool6 { get; set;}

    public byte varByte0 { get; set;}
    public byte varByte1 { get; set;}

    public ushort varWord0 { get; set;}

    public float varReal0 { get; set;}
    public bool varBool7 { get; set;}
    public float varReal1 { get; set;}

    public byte varByte2 { get; set;}
    public UInt32 varDWord { get; set;}
}

, and then add code to read or write the complete class:

// 从起始地址0读取DataBlock 1中的类
TestClass myTestClass = new TestClass();
plc.ReadClass(myTestClass, 1, 0);

to read multiple variables

This method reads multiple variables in a single request. Variables can be located in the same or different data blocks.

public void Plc.ReadMultibleVars(List<DataItem> dataItems);
  • List<>: You must specify a DataItem list that contains all the data items to be read.

Example: This method reads several variables from a data block:

First define data items:

private static DataItem varBit = new DataItem()
{
    DataType = DataType.DataBlock,
    VarType = VarType.Bit,
    DB = 83,
    BitAdr = 0,
    Count = 1,
    StartByteAdr = 0,
    Value = new object()
};

...

Then define a list to store DataItems:

private static List<DataItem> dataItemsRead = new List<DataItem>();

Add data items to the list:

dataItemsRead.Add(varBit);
dataItemsRead.Add(varByteArray);
dataItemsRead.Add(varInt);
dataItemsRead.Add(varReal);
dataItemsRead.Add(varString);
dataItemsRead.Add(varDateTime);

Open PLC connection and immediately read item list:

myPLC.Open();

// 读取变量列表
myPLC.ReadMultipleVars(dataItemsRead);

// 关闭连接
myPLC.Close();

// 访问列表的值
Console.WriteLine("Int:" + dataItemsRead[2].Value);

Write multiple variables

This method writes multiple variables in a single request.

public void Plc.Write(Array[DataItem] dataItems);
  • Array[]You must specify a DataItem array that contains all the items to be written.

Example: This method writes multiple variables into one data block:

Define data items:

private static DataItem varWordWrite = new DataItem()
{
    // ... (与上文重复的数据项定义省略)
};

... (omitting duplicate data item definitions in the middle)

is the data item assignment value. Pay attention to using the correct data conversion to adapt to the S7 data type:

varWordWrite.Value = (ushort)67;
varIntWrite.Value = (ushort)33;
varDWordWrite.Value = (uint)444;
varDIntWrite.Value = 6666;
varRealWrite.Value = 77.89;
varStringWrite.Value = "Writting";

. Then define a list to store data items and add the created items to the list:

private static List<DataItem> dataItemsWrite = new List<DataItem>();

// 将数据项添加到要写入的数据项列表中
dataItemsWrite.Add(varWordWrite);
dataItemsWrite.Add(varIntWrite);
dataItemsWrite.Add(varDWordWrite);
dataItemsWrite.Add(varDIntWrite);
dataItemsWrite.Add(varRealWrite);
dataItemsWrite.Add(varStringWrite);

. Finally, open the PLC connection and write the items all at once. use. ToArrange() converts lists into arrays:

// 打开连接
myPLC.Open();

// 写入项目
myPLC.Write(dataItemsWrite.ToArray());

// 关闭连接
myPLC.Close();

This article provides a detailed introduction to S7. Net software, including its features, how to get started, how to create PLC instances, connect and disconnect, error handling, checking PLC availability and connection status, reading and writing bytes, reading and writing structures and classes, and how to read and write multiple variables at once. I hope this article can help you better understand S7. Net.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.