In the post IEC 61131-3: Additional language extensions, I briefly described the UNION. A reader comment has pointed out to me the possibility, that a UNION can also be expanded by EXTENDS. Since this simplifies the handling of a UNION and the norm does not indicate that, I would like to introduce this possibility in a (very) short post.
As already described in a post, a UNION makes it possible to define your own data types, all elements of which share the same storage space. Here is once more the example, where a 16-bit variable can be accessed individually to the low byte and the high byte. First, a structure consisting of two bytes is created.
TYPE U_Test : UNION nVar1 : WORD; stVar2 : ST_Bytes; END_UNION END_TYPE
TYPE ST_Bytes : STRUCT nLSB : BYTE; nMSB : BYTE; END_STRUCT END_TYPE
This example shows how the lower byte (LSB) and the higher byte (MSB) are determined from a variable of type WORD without bit operations.
PROGRAM MAIN VAR uVar : U_Test; nA, nB : BYTE; END_VAR uVar.nVar1 := 16#1234; nA := uVar.stVar2.nLSB; // Value: 16#34 (LSB) nB := uVar.stVar2.nMSB; // Value: 16#12 (MSB)
EXTENDS for UNIONS
The same task can also be solved with inheritance, which is a bit more elegant. In this case, the union U_Test inherits from ST_Bytes.
TYPE U_Test EXTENDS ST_Bytes : UNION nVar1 : WORD; // stVar2 : ST_Bytes; // Not necessary, is inherited from ST_Bytes. END_UNION END_TYPE
Access to nLSB and nMSB no longer needs to be done via a variable explicitly declared in the UNION.
uVar.nVar1 := 16#1234; nA := uVar.nLSB; // Value: 16#34 (LSB) nB := uVar.nMSB; // Value: 16#12 (MSB)