Search code examples
codesysstructured-text

How do you group variables in Structured Text?


How do you group variables in Structured Text?
Say I have n global variables for lamps:

lamp1
lamp2
lamp3
... // and so on

Then I have a button, and pressing it should set all variables to TRUE:

IF buttonPressed Then
    lamp1 := TRUE;
    lamp2 := TRUE;
    lamp3 := TRUE;
    ... // and so on
END_IF

How can I group the lamps in a way to not to have to set every varriable to TRUE manually?


Solution

  • To set multiple variables at once, you would first have to collect the values you want to set in an array:

    VAR 
        lamp1 : BOOL;
        lamp2 : BOOL;
        lamp3 : BOOL;
        lamps : ARRAY[1..3] OF BOOL := [lamp1, lamp2, lamp3];
    END_VAR
    

    and then set the values in a for loop.

    FOR i := 1 TO 3 DO
        lamps[i] := TRUE;
    END_FOR
    

    Result

    enter image description here

    Function

    You can also define a custom function if you have to do it a lot:

    FUNCTION SetAllBools : BOOL
    VAR_IN_OUT
        bools : BOOL;
    END_VAR
    VAR_INPUT
        newValue : BOOL;
    END_VAR
    VAR
        i : INT;
    END_VAR
    

    which can then be used as SetAllBool(lamps, TRUE);.