我使用TwinCAT。广告(TwinCAT 3)通过c#应用程序为倍福plc通信。应用是读写几个plc变量。我得到一个错误:
"无法封送对象。参数名称:value "
同时写入struct变量数组。然而,应用程序正在读取它,没有任何错误。任何帮助都将不胜感激。下面是我的代码示例。
Plc结构
TYPE Station :
STRUCT
ClusterID : STRING[10];
Tech_Type : USINT;
Status : BOOL;
Reject : BOOL;
Rej_Detail : STRING[50];
Rej_Catagory : USINT;
END_STRUCT
END_TYPE
c#中的Class
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public class Station
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
public string ClusterID;
public byte Tech_Type;
[MarshalAs(UnmanagedType.I1)]
public bool Status;
[MarshalAs(UnmanagedType.I1)]
public bool Reject;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 51)]
public string Rej_Detail;
public byte Rej_Catagory;
}
我正在写下面的代码,其中handles[0]是变量句柄,stations是长度为5的类数组。
adsClient.WriteAny(handles[0], stations, new int[] { 5 });
我想你缺少PLC中的对应项。请确保在PLC中声明了一个站点数组,如下所示:
// I have it in a global variable list named: STG_Variables
stat_array_Var : array [0..5] of Station;
这个c#代码为我工作:
TcAdsClient AdsComClient = new TcAdsClient();
AdsComClient.Connect(NetID_TwinCat, 851);
int handle_array = AdsComClient.CreateVariableHandle("STG_Variables.stat_array_Var");
// get some test stations:
Station station = new Station();
Station station2 = new Station();
Station station3 = new Station();
Station station4 = new Station();
Station station5 = new Station();
Station[] station_plural = new Station[] { station, station2, station3, station4, station5 };
// write some stuff to recognize that write test worked
for (int i = 0; i < station_plural.Length; i++)
{
station_plural[i].ClusterID = "ID: " + i.ToString();
}
// just use the normal WriteAny method without the new int[] { 5 } parameter!
// send it down to the plc
AdsComClient.WriteAny(handle_array, plural);
我不知道你的手柄handles[0]
指向哪里。编写Station
的数组不应该在plc中的一个单一结构体中结束。试试我的版本,请评论一下是否适合你。
编辑:我在c#中使用了这个类定义:
[StructLayout(LayoutKind.Sequential, Pack = 0)]
public class Station
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 11)]
public string ClusterID;
public byte Tech_Type;
[MarshalAs(UnmanagedType.I1)]
public bool Status;
[MarshalAs(UnmanagedType.I1)]
public bool Reject;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 51)]
public string Rej_Detail;
public byte Rej_Catagory;
}
创建了一个DUT
,并在PLC中使用了这个结构体定义:
TYPE Station :
STRUCT
ClusterID : STRING[10];
Tech_Type : USINT;
Status : BOOL;
Reject : BOOL;
Rej_Detail : STRING[50];
Rej_Catagory : USINT;
END_STRUCT
END_TYPE
,并如上所述声明了Station
s的数组变量。
它起作用了。我能够将结构写入PLC,并在数组
"ID: 0"
, "ID: 1"
, "ID: 2"
等字符串。