【问题标题】:How to Read/Write struct from PLC with libnodave如何使用 libnodave 从 PLC 读取/写入结构
【发布时间】:2017-12-16 06:03:33
【问题描述】:

我正在编写一个小的 c# 应用程序,它可以读取/写入一些数据到 S7-300 PLC 的 DB 内存。我正在使用 PLCSim 模拟器和 DotNetSiemensPLCToolBoxLibrary 来执行一些测试。如您所知,DotNetSiemensPLCToolBoxLibrary 是 libnodave 之上的一层,所以我经常直接使用 libnodave。 我可以与 PLC 成功连接,我可以写/读输入、merker 和字符串。 但是当我尝试写入/读取结构时遇到问题。 这是在 plc 中编写结构的代码:

//PLCTagGeneric
PLCTag<TestStruct> tst = new PLCTag<TestStruct>() { DataBlockNumber = 1, ByteAddress = 0 };
tmpConn.ReadValue(tst);
TestStruct read = tst.GenericValue;
TestStruct wrt = new TestStruct();
wrt.bb = 1;
wrt.cc = true;
wrt.ee = 14;           
wrt.test = "Bin da!";
tst.Controlvalue = wrt;
tmpConn.WriteValue(tst);

这是阅读代码:

PLCTag<TestStruct> tst = new PLCTag<TestStruct>() { DataBlockNumber = 1, ByteAddress = 0 };
tmpConn.ReadValue(tst);

byte[] buf = new byte[18];
int res = tmpConn._dc.readBytes(libnodave.daveDB, 1, 0, 18, buf);
tst._readValueFromBuffer(buf, 0);
TestStruct t = tst.GenericValue; 

这是结构:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct TestStruct
    {
        public SByte bb;
        public Boolean cc;
        public UInt32 ee;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
        public string test;
    }

读数的输出是:

bb: 0
ee: 920583
cc: false
test: n da!

为什么?我需要帮助。 谢谢

【问题讨论】:

    标签: c# struct libnodave


    【解决方案1】:

    已解决。 在 PLC 中,数据只是字节流。所以如果你写一个 Int16|Int32|string 的序列,你必须以相同的顺序读取,否则会导致解析字节时出错。 希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 2016-06-13
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      相关资源
      最近更新 更多