Bit Access to Variables

You can reference single bits in integer variables. For this, you append the variable with a dot and the index of the addressed bit. You can define the bit index with any constant. Indexing is 0-based.

Syntax:

<variable name>.<bit index>

Example:

a : INT;
b : BOOL;
...
a.2 := b;

The program sets the third bit of the variable a to the value of variable b.

If the index is greater than the bit width of the variable, then CODESYS issues the following error: index <n> outside of the valid range for variable <var>.

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

If the variable type is permitted, then CODESYS issues the following error message: Prohibited data type <type> for direct indexing”.

You must not assign bit access to any VAR_IN_OUT variables.

Bit access to a variable by using a global constant

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

Example: Bit access to an integer variable

Declaration in a global variable list: The variable enable defined which bit the program accesses.

VAR_GLOBAL CONSTANT
 enable:int := 2;
END_VAR

Declaration in block:

VAR
 xxx : int;
END_VAR

Bit access:

xxx.enable := true; (* -> the third bit in variable xxx will be set TRUE  *)

Bit access to BIT data types

BIT is a special data type that you can use only in structures.

Example: Bit access to BIT data types

Declaration of the structure:

TYPE ControllerData :
STRUCT
 Status_OperationEnabled : BIT;
 Status_SwitchOnActive : BIT;
 Status_EnableOperation : BIT;
 Status_Error : BIT;
 Status_VoltageEnabled : BIT;
 Status_QuickStop : BIT;
 Status_SwitchOnLocked : BIT;
 Status_Warning : BIT;
END_STRUCT
END_TYPE

Declaration in block:

VAR
 ControllerDrive1 : ControllerData;
END_VAR

Bit access:

ControllerDrive1.OperationEnabled := TRUE;

See also