plctwincatcodesys

Twincat compare a FB with interface


In my project, I've developed FB_Modes that allow me to perform certain actions depending on the mode. These FBs implement the same I_Mode interface.

To check which mode is active, I'd like to compare the current I_Mode with an FB, but Twincat doesn't allow direct comparison between an FB and an interface. I'd like to be able to do something like this.

IF fbMachine.itfActualMode = fbMode2 THEN
    <Do something>
END_IF

Is there a way to do this? Or another way to directly compare FBs with the interface with the address.

To get around this problem, I use a unique property for each FB. But I use STRING comparison and I think this solution is not clean.

IF fbMachine.itfActualMode.sName = fbMode2.sName THEN
    <Do something>
END_IF

Solution

  • One solution is to add a method Equals() to the I_Mode and then implement it in the function blocks. Idea is to create a temporary interface and then compare if they match.

    METHOD Equals : BOOL
    VAR_INPUT
        Compare : I_Mode;
    END_VAR
    VAR
        Temp : I_Mode;
    END_VAR
    
    //Code starts
    Temp := THIS^;
    
    Equals := Compare = Temp;
    

    Then you can check if the FB is equal to the interface like this

    IF fbMachine.itfActualMode.Equals(fbMode2) THEN
        //...
    END_IF
    

    This only checks if the instances match. So it doesn't compare types, as the Guiorgy's answer does.