使用S7netplus读取C#中的Siemens PLC s7字符串

时间:2019-10-02 18:47:24

标签: c# plc siemens

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

情况:

  • 我正在运行一个C#应用程序。
  • 我在PLC上连接得很好。
  • 我可以读取布尔值,UInt,UShot,字节等数据

但是我不知道如何读取String数据(请参见下图)

PLC Datas

要读取其他数据(例如布尔值),请使用此调用:

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函数?

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

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

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

为什么12?因为字节字符串的前两个字节是长度。因此10到12会返回一个值为40的长度。

我已经重写了read方法,以接受“ easy string”调用,如下所示:

    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的字符串值

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

相关问题