Bit Access to Variables

It is possible to address individual bits in integer variables. To this end append a dot and the index of the bits to be addressed to the variable. Any constant can be used as the bit index. Indexing is 0-based.

Syntax: <variable name>.<bit index>

Sample:

nVarA : INT;
bVarB : BOOL;
nVarA.2 := bVarB;

The program sets the third bit of the variables nVarA to the value of the variable bVarB.

If the index is larger than the bit width of the variable, TwinCAT outputs the following error: Index <n> outside of the valid range for variable <Name>.

You can use bit addressing with the following types of variable: SINT, INT, DINT, USINT, UINT, UDINT, BYTE, WORD, DWORD.

64-bit types are also supported (LINT, ULINT, LWORD)

If the type of variable is not allowed, TwinCAT outputs the following error message: Invalid data type <type> for direct indexing.

You may not assign a bit access to any VAR_IN_OUT variable.

Bit access to a variable based on a global constant

You can use a global constant, which defines the bit number, for bit access to a variable or a structure variable.

Example: Bit access to an integer variable

Declaration in a global variable list. Variable nEnable defines which bit the program accesses.

VAR_GLOBAL CONSTANT
    nEnable : INT := 2;
END_VAR

Declaration in function block:

VAR
    nVar : INT;
END_VAR

Bit access:

nVar.nEnable := TRUE; (* -> the third bit in variable nVar will be set TRUE *)
Bit Access to Variables 1:

Accessibility of the variable defined by the bit number

Note that the variable defined by the bit number (nEnable in the sample above), must be accessible directly via the variable name, without preceding namespace.
Bit access is therefore permitted if the variable was declared in the local scope (same layer as nVar) or in the global scope on a GVL without the attribute 'qualified_only', for example.
If the variable is declared in a GVL with the attribute 'qualified_only', access to nEnable is only possible through specification of a global variable list name (GVL.nEnable). Such an access to a global variable cannot be used for bit access (not possible: nVar.GVL.nEnable := TRUE;).

Bit access to BIT data types

BIT is a special data type, which can only be used in structures.

Example: Bit access to BIT data types

Declaration of the structure:

TYPE ST_ControllerData :
STRUCT
    nStatus_OperationEnabled : BIT;
    nStatus_SwitchOnActive   : BIT;
    nStatus_EnableOperation  : BIT;
    nStatus_Error            : BIT;
    nStatus_VoltageEnabled   : BIT;
    nStatus_QuickStop        : BIT;
    nStatus_SwitchOnLocked   : BIT;
    nStatus_Warning          : BIT;
END_STRUCT
END_TYPE 

Declaration in function block:

VAR
    stControllerDrive1 : ST_ControllerData;
END_VAR

Bit access:

stControllerDrive1.nStatus_OperationEnabled := TRUE;

See also: