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 :
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)

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…
    RegRds
    Jan

  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.

      Stefan

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: