首页 > 解决方案 > 使用 S7netplus 在 C# 中读取 Siemens PLC s7 字符串

问题描述

我无法使用 S7netplus 读取 Siemens PLC S7 1500 的 DB 中的数据。

情况:

但我不知道如何读取字符串数据(见下图)

PLC 数据

要读取 Boolean 等其他数据,我使用以下调用:

plc.Read("DB105.DBX0.0")

我知道在数据块 105 (DB105) 中读取的数据类型为布尔 (DBX),偏移量为 0.0 我想对字符串应用相同类型的读取。所以我在我的例子中尝试了“DB105.DBB10.0”。但它返回一个字节类型的值“40”(我应该有别的东西)

我看到还有另一种阅读方法

plc.ReadBytes(DataType DB, int DBNumber, int StartByteArray, int lengthToRead)

但是我很难看到如何将它应用到我的示例中(我知道我必须在之后将其转换为字符串)。

继续: - 是否有一种简单的方法可以使用“DB105.DBX0.0”之类的字符串来读取西门子 PLC 中的字符串数据?- 如果不是如何在我的示例中使用 ReadBytes 函数?

谢谢你的帮助

标签: c#plcsiemens

解决方案


我设法通过 ReadBytes 方法读取了我的字符串值。在我的示例中,我需要传递如下值:

plc.Read(DataType.DataBlock, 105, 12, VarType.String, 40);

为什么是12?因为字节字符串的前 2 个八位字节用于长度。所以 10 到 12 返回一个值为 40 的值,即长度。

我已经重写了 read 方法来接受这样的“简单字符串”调用:

    public T Read<T>(object pValue)
            {
                var splitValue = pValue.ToString().Split('.');
                //check if it is a string template (3 separation ., 2 if not)
                if (splitValue.Count() > 3 && splitValue[1].Substring(2, 1) == "S")
                {
                    DataType dType;

                    //If we have to read string in other dataType need development to make here.
                    if (splitValue[0].Substring(0, 2) == "DB")
                        dType = DataType.DataBlock;
                    else
                        throw new Exception("Data Type not supported for string value yet.");

                    int length = Convert.ToInt32(splitValue[3]);
                    int start = Convert.ToInt32(splitValue[1].Substring(3, splitValue[1].Length - 3));
                    int MemoryNumber = Convert.ToInt32(splitValue[0].Substring(2, splitValue[0].Length - 2));

                    // the 2 first bits are for the length of the string. So we have to pass it
                    int startString = start + 2;
                    var value = ReadFull(dType, MemoryNumber, startString, VarType.String, length);
                    return (T)value;
                }
                else
                {
                    var value = plc.Read(pValue.ToString());

                    //Cast with good format.
                    return (T)value;
                }
}

所以现在我可以像这样调用我的读取函数:使用基本的现有调用:

  • var element = mPlc.Read<bool>("DB10.DBX1.4").ToString();=> 在数据块 10 中读取字节 1 和八位字节 4 的布尔值
  • var element = mPlc.Read<uint>("DB10.DBD4.0").ToString();=> 在数据块 10 中读取字节 4 和八位字节 0 的 int 值

对字符串的覆盖调用:

  • var element = mPlc.Read<string>("DB105.DBS10.0.40").ToString()=> 在数据块 105 中读取字节 10 和八位字节 0 上的字符串值,长度为 40

希望这对其他人有帮助:)


推荐阅读