我在使用 S7netplus 读取西门子 PLC S7 1500 的 DB 中的数据时遇到问题。
情况:
但我不知道如何读取字符串数据(见下图)

要读取布尔值等其他数据,我使用以下调用:
plc.Read("DB105.DBX0.0")
Run Code Online (Sandbox Code Playgroud)
我了解到,在数据块 105 (DB105) 中读取数据类型为布尔值 (DBX),偏移量为 0.0 我想对字符串应用相同类型的读取。所以我在我的示例中尝试了“DB105.DBB10.0”。但它返回一个字节类型的值“40”(我应该有别的东西)
我看到还有另一种阅读方法
plc.ReadBytes(DataType DB, int DBNumber, int StartByteArray, int lengthToRead)
Run Code Online (Sandbox Code Playgroud)
但我很难了解如何将其应用到我的示例中(我知道之后必须将其转换为字符串)。
继续: - 有没有一种简单的方法可以使用“DB105.DBX0.0”这样的字符串来读取西门子PLC中的字符串数据?- 如果不是,如何在我的示例中使用 ReadBytes 函数?
感谢您的帮助
我设法通过 ReadBytes 方法读取我的字符串值。在我的示例中,我需要传递如下值:
plc.Read(DataType.DataBlock, 105, 12, VarType.String, 40);
Run Code Online (Sandbox Code Playgroud)
为什么是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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在我可以像这样调用我的读取函数:使用基本的现有调用:
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 的字符串值希望这对其他人有帮助:)
| 归档时间: |
|
| 查看次数: |
7857 次 |
| 最近记录: |