Join us today!
Variable length array - ARRAY [*] OF
When you don't know the exact length of an array that you want to use in a function block, method or function, you can declare your array VAR_IN_OUT section as variable length array. Then you can use LOWER_BOUND and UPPER_BOUND to determine index limits of the array.
Let's assume you want to create a part data analysis function block, but you don't know how many parts there will be and you also don't know the data types of the elements in part type struct. You only know that part struct will have 10 or less fields.
You can declare the elements in part struct as T_Arg.
ST_Generic:
TYPE ST_Generic : STRUCT element_1 : T_Arg; element_2 : T_Arg; element_3 : T_Arg; element_4 : T_Arg; element_5 : T_Arg; element_6 : T_Arg; element_7 : T_Arg; element_8 : T_Arg; element_9 : T_Arg; element_10: T_Arg; END_STRUCT END_TYPE
Now we will define a variable length array which is type of ST_Generic in FB_PartDataAnaylsis function block.
FB_PartDataAnaylsis:
FUNCTION_BLOCK FB_PartDataAnalysis VAR_INPUT END_VAR VAR_OUTPUT END_VAR VAR nIndex : DINT; END_VAR VAR_IN_OUT aPartData : ARRAY[*] OF ST_Generic; END_VAR
In the implementation you can LOWER_BOUND and UPPER_BOUND to get the index limits of aPartData array. You can also check the data type of each element of ST_Generic.
FOR nIndex := LOWER_BOUND(aPartData, 1) TO UPPER_BOUND(aPartData, 1) DO //your code here (* IF aPartData[nIndex].element_1.eType = E_ArgType.ARGTYPE_INT THEN //do something... END_IF . . . . . *) END_FOR
We will add a parameter file to modify the number of the parts later in the library. Once you know the exact part amount, you can modify this value from the library.
Param:
{attribute 'qualified_only'} VAR_GLOBAL CONSTANT cNumberOfParts : INT := 2; END_VAR
In the MAIN program, declare your part array and the part data analysis function block and pass the part array to this function block.
PROGRAM MAIN VAR aMyPart : ARRAY[1..Param.cNumberOfParts] OF ST_Generic; fbDataAnaylsis : FB_PartDataAnalysis; END_VAR
fbDataAnaylsis(aPartData:=aMyPart);
When you know the data types of the elements for STRUCT, initialize the aMyPart array with the correct data types and the values.
In case you want to say thank you !)
We'd be very grateful if you could share this community with your colleagues and friends. You can also buy us a coffee to keep us fueled 😊 This is the best way to say thank you to this project and support your community.
twinControls - https://twincontrols.com/
- 17 Forums
- 267 Topics
- 942 Posts
- 2 Online
- 722 Members