我无法使用 S7netplus 读取西门子 PLC S7 1500 的数据库中的数据。
情况:
- 我正在运行一个 C# 应用程序。
- 我在 PLC 上连接得很好。
- 我可以读取 Boolean、UInt、UShot、Bytes 等数据
但我不知道如何读取String数据(见下图)
要读取 bool 值等其他数据,我使用此调用:
plc.Read("DB105.DBX0.0")
我知道这是在数据 block 105 (DB105) 中读取的,数据类型为 bool (DBX),偏移量为 0.0 我想对字符串应用相同类型的阅读。所以我在我的例子中尝试了“DB105.DBB10.0”。但它返回一个字节类型的值“40”(我应该有其他东西)
我看到还有一种阅读方法
plc.ReadBytes(DataType DB, int DBNumber, int StartByteArray, int lengthToRead)
但我很难看出如何将它应用到我的示例中(我知道我必须在之后将它转换为字符串)。
要恢复: - 有没有一种简单的方法可以使用像“DB105.DBX0.0”这样的字符串来读取西门子PLC中的字符串数据? - 如果不是,如何在我的示例中使用 ReadBytes 函数?
谢谢你的帮助
最佳答案
我设法通过 ReadBytes 方法读取了我的字符串值。 在我的示例中,我需要像这样传递值:
plc.Read(DataType.DataBlock, 105, 12, VarType.String, 40);
为什么是 12?因为字节串的前 2 个八位字节是长度。所以 10 到 12 返回一个值 40,这是长度。
我已经重写了读取方法来接受这样的“简单字符串”调用:
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();
=> 在数据 block 10 中读取字节 1 和八位字节 4 的 bool 值 -
var element = mPlc.Read<uint>("DB10.DBD4.0").ToString();
=> 在数据 block 10 中读取字节 4 和八位字节 0 上的 int 值
对字符串的重写调用:
-
var element = mPlc.Read<string>("DB105.DBS10.0.40").ToString()
=> 在数据 block 105 中读取字节 10 和八位字节 0 上长度为 40 的字符串值
希望这对其他人有帮助:)
关于c# - 使用 S7netplus 在 C# 中读取西门子 PLC s7 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207603/