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

问题描述 投票:1回答:1

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

情况:

  • 我正在运行C#应用程序。
  • 我在PLC上连接得很好。
  • 我可以读取诸如布尔,UInt,UShot,字节之类的数据

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

“

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

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# plc siemens
1个回答
2
投票

我设法通过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;
                }
}

所以现在我可以这样调用我的read函数:现有的基本通话:

  • [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中读取长度为40的字节10和八位字节0上的字符串值

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

© www.soinside.com 2019 - 2024. All rights reserved.