Reputation: 61
I am working on a moving average algorithm to analyze a sensor values and the values are stored in an Array. BUT, the length of Array is variabla (depends on speed of one motor).
how can I Creat an array in CoDeSys with changeable size. It's wrong to define Array so :
Name: ARRAY[1...SpeedValue] OF INT ;
Upvotes: 4
Views: 11750
Reputation: 21
Dynamic array is possible with the help of pointers and operators "__NEW", "__DELETE":
VAR
arrnValues : POINTER TO INT;
SpeedValue : UDINT;
END_VAR
SpeedValue := 100;
arrnValues := __NEW(INT, SpeedValue);
__DELETE(arrnValues);
You must also activate dynamic memory allocation in the Application Properties: Application Build Options
Upvotes: 2
Reputation: 2428
I am sorry to tell you that there is no changeable size for arrays in Codesys V2/V3. The general explanation is that there is no Dynamic Memory Allocation available in a PLC because Dynamic Memory Allocation is considered to be too unreliable.
Your only choice is to define an array with a constant ARRAY[1..N_MAX_SPEED_VALUE] and just use the array until SpeedValue
VAR
arrnValues : ARRAY[1..N_MAX_SPEED_VALUE] OF INT;
END_VAR
VAR CONSTANT
N_MAX_SPEED_VALUE : INT := 100; (*Max Array Size*)
END_VAR
For myself I am really bugged by this limitation. I already requested a feature many times, to define arrays like ARRAY[*], have keywords for start and end and define the actual start and end size when instantiating. This has nothing todo with dynamic memory allocation, because size is defined at compile time.
Upvotes: 3
Reputation: 21
I would recomend you the following post.
https://stefanhenneken.wordpress.com/2016/09/27/iec-61131-3-arrays-with-variable-length/
Stefan describes step by step what is possible to do with variable length arrays.
I wouldn't recommend what Felix sugested because:
First: You never want to have variable scan times.
Second: If for some reason, lets just say something broke and the SpeedValue that you want to be the upper bound of your array is impossible to reach, then you either have a deadlock or a bad output without really knowing if something is wrong
Upvotes: 2