C# 读取西门子S7系列PLC教程及源码

创建 PLC 实例,连接和断开连接

若要创建驱动程序的实例,需要使用此构造函数:

public Plc(CpuType cpu, string ip, Int16 rack, Int16 slot)
  • CPU:这指定您要连接到的 CPU。支持的 CPU 包括:
public enum CpuType {
    S7200 = 0,
    S7300 = 10,
    S7400 = 20,
    S71200 = 30,
    S71500 = 40,
}
  • ip:指定 CPU 或外部以太网卡的 IP 地址
  • 机架:它包含PLC的机架,您可以在Step7的硬件配置中找到
  • 插槽:这是CPU的插槽,您可以在Step7的硬件配置中找到

例:

此代码为 IP 地址为 7.300.127.0 的 S0-1 plc 创建一个 Plc 对象,为 CPU 位于插槽 0 的机架 2 中的 plc 创建一个 Plc 对象:

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

连接到 PLC

public void Open()

例如,这行代码打开连接:

plc.Open();

断开与 PLC 的连接

public void Close()

例如,这将关闭连接:

plc.Close();

错误处理

任何方法都可能导致各种错误。您应该实现正确的错误处理。 提供了 和 足够的错误消息。PlcExceptionPlcExceptionErrorCode

以下是错误的类型:

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

检查 PLC 可用性

要检查 plc 是否可用(打开套接字),您可以使用该属性

public bool IsAvailable

当您检查此属性时,驱动程序将尝试连接到 plc,如果它可以连接,则返回 true,否则返回 false。

检查 PLC 连接

检查 plc 连接是微不足道的,因为您必须检查 PC 插座是否已连接,而且还要检查 PLC 是否仍连接在插座的另一侧。 在这种情况下,您必须检查的属性是:

public bool IsConnected

在调用方法 Open() 并且结果成功后,可以检查此属性,以检查连接是否仍处于活动状态。

读取字节/写入字节

该库提供了几种读取变量的方法。基本和最常用的是ReadBytes。

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

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

这将从给定内存位置读取您指定的所有字节。此方法会自动处理多个请求,以防字节数超过单个请求中可以传输的最大字节数。

  • 数据类型:您必须使用枚举数据类型指定内存位置
public enum DataType
{
    Input = 129,
    Output = 130,
    Memory = 131,
    DataBlock = 132,
    Timer = 29,
    Counter = 28
}
  • db:数据类型的地址,例如如果要读取 DB1,此字段为 “1”;如果要读取 T45,则此字段为 45。
  • startByteAdr:要读取的第一个字节的地址,例如,如果要读取 DB1。DBW200,这是200。
  • 计数:包含要读取的字节数。
  • 值[ ]:要从PLC读取的字节数组。

例: 此方法读取 DB200 的前 1 个字节:

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

读写解码

此方法允许根据提供的varType读取和接收已解码的结果。如果您读取多个相同类型的字段(例如 20 个连续的 DBW),这将非常有用。如果指定 VarType.Byte,则它具有与 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)
  • 数据类型:您必须使用枚举数据类型指定内存位置
public enum DataType
{
    Input = 129,
    Output = 130,
    Memory = 131,
    DataBlock = 132,
    Timer = 29,
    Counter = 28
}
  • db:数据类型的地址,例如如果要读取 DB1,此字段为 “1”;如果要读取 T45,则此字段为 45。
  • startByteAdr:要读取的第一个字节的地址,例如,如果要读取 DB1。DBW200,这是200。
  • varType:指定要转换字节的数据。
public enum VarType
{
    Bit,
    Byte,
    Word,
    DWord,
    Int,
    DInt,
    Real,
    String,
    StringEx,
    Timer,
    Counter
}
  • count:包含要读取的变量数。
  • :要写入 PLC 的值数组。它可以是单个值或数组,只需记住该类型是唯一的(例如双精度数组、整数数组、短整型数组等)。

例: 此方法读取 DB20 的前 1 个 DWord:

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

读取单个变量/写入单个变量

此方法通过解析字符串并返回正确的结果,从 plc 读取单个变量。虽然这是最简单的入门方法,但效率非常低,因为驱动程序为每个变量发送 TCP 请求。

public object Read(string variable)

public void Write(string variable, object value)
  • variable: specify the variable to read by using strings like “DB1.DBW20”, “T45”, “C21”, “DB1.DBD400”, etc.

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

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

读取结构/编写结构

This method reads all the bytes from a specified DB needed to fill a struct in C#, and returns the struct that contains the values. It is recommended to use when you want to read many variables in a single data block in some continuous memory range.

The "read struct" and "write struct" 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 the struct to be read, for example: typeOf(MyStruct))
  • db: index of the DB to read
  • startByteAdr: specified the first address of the byte to read (the default is zero).

Then add a struct into your .Net application that is similiar to the DB in the plc:

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

then add the code to read or write the complete struct

// reads a struct from DataBlock 1 at StartAddress 0
testStruct myTestStruct = (testStruct) plc.ReadStruct(typeof(testStruct), 1, 0);

Read a class / Write a class

This method reads all the bytes from a specified DB needed to fill a class in C#. The class is passed as reference and values are assigned by using reflection. It is recommended to use when you want to read many variables in a single data block in some continuous memory range.

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 that you want to assign the values
  • db: index of the DB to read
  • startByteAdr: specified the first address of the byte to read (the default is zero). 

Then add a struct into your .Net application that is similiar to the DB in the plc:

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

then add the code to read or write the complete class

// reads a class from DataBlock 1, startAddress 0
TestClass myTestClass = new TestClass();
plc.ReadClass(myTestClass, 1, 0);

Read multiple variables

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

public void Plc.ReadMultibleVars(List<DataItem> dataItems);
  • List<>: you have to specify a list of DataItem which contains all data items you want to read

Example: this method reads several variables from a data block

define the data items first

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

private static DataItem varByteArray = new DataItem()
{
    DataType = DataType.DataBlock,
    VarType = VarType.Byte,
    DB = 83,
    BitAdr = 0,
    Count = 100,
    StartByteAdr = 0,
    Value = new object()
};

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

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

private static DataItem varString = new DataItem()
{
    DataType = DataType.DataBlock,
    VarType = VarType.StringEx,
    DB = 83,
    BitAdr = 0,
    Count = 20,         // max lengt of string
    StartByteAdr = 116,
    Value = new object()
};
    
private static DataItem varDateTime = new DataItem()
{
    DataType = DataType.DataBlock,
    VarType = VarType.DateTime,
    DB = 83,
    BitAdr = 0,
    Count = 1,
    StartByteAdr = 138,
    Value = new object()
}; 

Then define a list where the DataItems will be stored in

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

add the data items to the list

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

open the connection to the plc and read the items at once

myPLC.Open();

// read the list of variables
myPLC.ReadMultipleVars(dataItemsRead);

// close the connection
myPLC.Close();

// access the values of the list
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 have to specifiy an array of DataItem which contains all the items you want to write

Example: this method writes multiple variables into one data block

define the data items

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

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

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

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

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

private static DataItem varStringWrite = new DataItem()
{
    DataType = DataType.DataBlock,
    VarType = VarType.StringEx,
    DB = 83,
    BitAdr = 0,
    Count = 20,
    StartByteAdr = 162,
    Value = new object()
};

Asign the values to the data items. Be aware to use the correct data conversion for the variables to fit into the S7-data types

// asign values to the variable to be written                
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 the data items and add the created items to the list

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

// add data items to list of data items to write                
dataItemsWrite.Add(varWordWrite);
dataItemsWrite.Add(varIntWrite);
dataItemsWrite.Add(varDWordWrite);
dataItemsWrite.Add(varDIntWrite);
dataItemsWrite.Add(varRealWrite);
dataItemsWrite.Add(varStringWrite);

Finally open a connection to the plc and write the items at once. Use to convert the list into an array..ToArray()

// open the connection
myPLC.Open();

// write the items
myPLC.Write(dataItemsWrite.ToArray());

// close the connection
myPLC.Close();

开源下载链接:C#读取西门子S7系列PLC教程及源码Profinet-网络基础文档类资源-CSDN文库

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

泰勒~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值