Home > IEC 61131-3 (english) > IEC 61131-3: Extend UNION via inheritance

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)
Advertisements
  1. Jan Beránek
    November 6, 2017 at 11:49 PM

    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

  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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: