IEC 61131-3: Extend UNION via inheritance

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 :
  nVar1   : WORD;
  stVar2  : ST_Bytes;
TYPE ST_Bytes :
  nLSB   : BYTE;
  nMSB   : BYTE;

This example shows how the lower byte (LSB) and the higher byte (MSB) are determined from a variable of type WORD without bit operations.

  uVar    : U_Test;
  nA, nB  : BYTE;

uVar.nVar1 := 16#1234;
nA := uVar.stVar2.nLSB; // Value: 16#34 (LSB)
nB := uVar.stVar2.nMSB; // Value: 16#12 (MSB)


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.

  nVar1 : WORD;
  // stVar2 : ST_Bytes; // Not necessary, is inherited from ST_Bytes.

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)

Author: Stefan Henneken

I’m Stefan Henneken, a software developer based in Germany. This blog is just a collection of various articles I want to share, mostly related to Software Development.

3 thoughts on “IEC 61131-3: Extend UNION via inheritance”

  1. Nice.
    Tell me, what code will codesys compiler generate?
    I heard that it is not optimizing at all, so it may be much worse than simple shift instruction…

  2. Hi Stefan,
    I read with great interest this contribution and have applied it several times in a multitude of projects.
    Since the recent codesys release this generates a warning “C0542: Inheritance is not intended for data type “UNION”: …”
    Any thoughts from your side regarding this warning?

    1. Hi,

      I think 3S has implemented this warning because the feature is not currently part of the IEC 61331-3 standard. The example is (still) running under TwinCAT V3.1.4024.32. But you can’t be sure if this will still be the case with the upcoming build.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: