Sorting functions have increasing use in PLC programs thanks to more powerful processors and more memory. One example is sorting an array of motor runtimes from lowest runtime to highest runtime so that the next run cycle will utilize the motor with the lowest runtime first. This example is useful for pump applications and is referred to in the post about pointers in CODESYS.
To implement a pump runtime based sort, other elements in CODESYS such as DUT’s( user defined data types) and structures could probably be useful. The reason is that the result of the sorting function is to know which pump to run next. This can be done by having two dimensions in the array, a Pump ID/Number along with the Pump Runtime. For the purpose of simplicity, only a simply bubble sort with two FOR loops is shown below, the DUT approach is not shown here.
A simple bubble sort can be implemented in CODESYS with the following code. Instead of sorting the actual array, this example sorts an array of pointers ( dereferenced to get the actual values from the pointers). This way the original array data locations do not need to be altered. Not altering the original array locations is a good thing because in some cases, these array locations may be hardcoded to physical inputs.
(*Prior to implementing the sort, an array if pointers is loaded *)
FOR l:=0 TO n BY 1 DO
pointToArrayElement[l]:=ADR(TestArray[l]);
END_FOR
(*Bubble sort- The value of n should be equivalent to the last array element*)
FOR i:=0 TO n BY 1 DO
(* The second FOR loop compares two elements of the array at a time and sorts*)
FOR j:=0 TO n-1 BY 1 DO
IF(pointToArrayElement[j]^>pointToArrayElement[j+1]^) THEN
temp := pointToArrayElement[j+1];
pointToArrayElement[j+1] := pointToArrayElement[j];
pointToArrayElement[j] := temp;
END_IF
END_FOR
END_FOR
The variables used in this example:
VAR
TestArray: ARRAY [0..4] OF Pump;
TestArrayPointers: ARRAY [0..4] OF POINTER TO INT;
i: INT;
n: INT;
j: INT;
l: INT;
temp: pointer to INT;
pointToArrayElement: ARRAY OF POINTER TO INT;
END_VAR
Other notables: If this is implemented in a function or even in a program , the integers used in the FOR loop iteration need to be reset after the sorting is complete and it would be required to sequence through the loading of the array of pointers, sorting and resetting of the iterative integers possibly using a CASE structure or some IF statements.