-1

I am using TwinCat, when making a program to read my XML file. I need to read an array of points in the XML file. but the amount of points can variate. Is there a method to create an array depending on the XML data.

swapsster
  • 13
  • 1

1 Answers1

0

You can't define a dynamic array in most of the Codesys based systems. However, it is possible to create functions and blocks with to handle dynamic size arrays through VAR_IN_OUT if required (TwinCAT 3 - see this link).

NOTE: Actually in newest TwinCAT 3 versions it's also possible to allocate dynamic memory with __NEW command (see this link). I haven't tested it yet but there is an example how to create a byte array size of 25 at runtime. This could be a great way but there could be some problems as you need to delete the memory used after no more needed with __DELETE function.

It's a common convention in these systems to create an array that is as big as will ever be needed. So think a theoretical maximum of how many points you will ever have in the file and create an array of that size. Then you just have to know how many points you have added for later use. This method is very safe to use, so I would suggest you to start with it instead of the __NEW.

Small simple code to help you understand:

PROGRAM PRG_XmlTest
VAR CONSTANT
    MAXIMUM_ARRAY_SIZE  : UINT := 9999;
END_VAR
VAR
    PointArray      : ARRAY[0..MAXIMUM_ARRAY_SIZE] OF REAL;
    PointsInArray   : UINT;
    i               : UINT;
END_VAR

//Deleting old data before loading
MEMSET(
    destAddr := ADR(PointArray), 
    fillByte := 0, 
    n        := SIZEOF(PointArray)
);
PointsInArray := 0;

//Loading your XML. NOTE: This is not a working code
WHILE Xml.HasPoints() DO 
    IF PointsInArray < MAXIMUM_ARRAY_SIZE THEN
        PointArray[PointsInArray] := XmlReader.GetPoint();
        PointsInArray := PointsInArray + 1;
    ELSE
        //Overflow, array is full. Do something
        EXIT;
    END_IF
END_WHILE

//To do something with your data.
//NOTE: Using MIN to prevent faults if PointsInArray has too large value
FOR i := 0 TO MIN(PointsInArray, MAXIMUM_ARRAY_SIZE) DO
    DoSomething(PointArray[i]);
END_FOR
Quirzo
  • 1,183
  • 8
  • 10