Search code examples
uniontwincatcodesys

union bit mapping of BOOL and WORD


I'm tryng to map some bit in a single word , but I see for the compile the size of bool is equal to an byte. When I see the code in execution every BOOL is 8 bit size. How can I specify a bit field in struct or union? That is my code:

TYPE FAULT_CODE:
STRUCT 
fault1,falut2,fault3: BOOL;

END_STRUCT
END_TYPE

TYPE U_fault :
UNION
    faultCode: FAULT_CODE;
    in: WORD;
END_UNION
END_TYPE

enter image description here


Solution

  • Answer

    The ST datatype that you are looking for is the BIT

    • BOOL: 8 Bit
    • BIT: 1 Bit

    You can only use the data type BIT for individual variables within structures or function blocks. The possible values are TRUE (1) and FALSE (0).

    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. 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.


    Example

    TYPE st_Flags :
    STRUCT
        Bit1  : BIT;
        Bit2  : BIT;
        Bit3  : BIT;
        Bit4  : BIT;
        Bit5  : BIT;
        Bit6  : BIT;
        Bit7  : BIT;
        Bit8  : BIT;
    END_STRUCT
    END_TYPE
    
    TYPE u_Error :
    UNION
        _Byte   : BYTE;
        _Flag   : st_Flags;
    END_UNION
    END_TYPE