twincatcodesysst

How can link BIT2 type to a variable?


In most input cards of Beckhoff, there are two variables, Limit 1 and limit 2. They have a BIT2 datatype, size of 0.2 bytes, which means they have two bits, as shown in the following figure for Limit 1:

Bit0: Value smaller/equal Limit 1
Bit1: Value bigger/equal Limit 1

enter image description here

so there are some questions: what kind of datatype should I define to link this variable to it, and how can I access both of its bits.

Any help would be appreciated.


Solution

  • You can use the BIT datatype in TwinCAT, but this is only available within a struct or a function block.

    You can for example define a STRUCT as follows (see also InfoSys):

    TYPE Limits:
    STRUCT
        SmallerThanOrEqualTo : BIT;
        LargerThanOrEqualTo : BIT;
    END_STRUCT
    END_TYPE
    

    It should be possible to link an instance of this struct to the variable.

    Note that using BIT access can be a bit slower than using bit masks:

    However, bit access takes significantly longer. Therefore, you should only use the data type BIT if you want to define the data in a specified format.

    Toni Kucic did a speed comparison and found BIT access (13.5 ns) to be around a factor 5 slower than bit masks (2.8 ns). Full results:

    codesys timing of bit access versus dot access

    BIT datatypes do have the advantage that they are much more memory efficient:

    A BIT element requires 1 bit of memory space, and you can use it to address individual bits of a structure or function block using its name. BIT elements, which are declared sequentially, are consolidated to bytes. This allows you to optimize memory usage compared to BOOL types, which each occupy at least 8 bits.