Creating an FB in the first PLC which provides its functionality globally
1. Create a PLC and a new function block (FB) (in this case: FB_Calculation). Derive the function block from the TcBaseModuleRegistered class so that an instance of the function block is available not only in the same PLC but also in a second one. As an alternative, you can modify an FB in an existing PLC.
2. The function block must provide its functionality through methods. These are defined in a global interface whose type is known system-wide and regardless of the programming language. To create a global interface, open the context menu in the “Interface” tab of System Properties and select “New”.
The TMC Editor opens to help create a global interface.
3. Enter the name (in this case: I_Calculation) and append the desired methods. The interface is automatically derived from ITcUnknown to comply with the TwinCAT TcCOM module concept.
4. Enter the names of the methods (in this case: Addition() and Subtraction()) and select HRESULT as return data type. This return type is mandatory if this type of TcCOM communication is to be implemented.
5. Finally, specify the method parameters and close the TMC Editor.
6. Now implement the I_Calculation interface in the FB_Calculation function block and append the “c++_compatible” attribute.
7. Choose the “Implement interfaces...” option in the context menu of the function block in order to obtain the methods belonging to this interface.
8. Delete the two methods TcAddRef() and TcRelease() because the existing implementation of the base class is to be used.
9. Create the FB_reinit() method for the FB_Calculation function block and call the basic implementation. This ensures that the FB_reinit() method of the base class will run during the online change. This is imperative.
10. Implement the TcQueryInterface() method of the Interface ITcUnknown. This method enables other TwinCAT components to obtain an interface pointer to an instance of this function block, allowing them to perform method calls. Calling TcQueryInterface is successful if the function block or its base class provides the interface requested by means of iid (Interface ID). In this case, the interface pointer that was handed over is allocated an address to the function block with its type changed and the reference counter is also incremented using TcAddRef().
11. Add the corresponding code to the Addition() and Subtraction() methods to provide the functionality: nRes := nIn1 + nIn2 and nRes := nIn1 - nIn2
12. Add one or more instances of this function block to the MAIN program block or to a global variable list.
The implementation in the first PLC is complete.
After compiling the PLC, the object ID of the TcCOM object representing the FB_Calculation instance is available as an outlet in the process image.