Bit Access to Variables
With an index access you can address individual bits in integer variables. You can use a structure variable or a function block instance to address individual bits symbolically.
Index access to bits in integer variables
It is possible to address individual bits in integer variables. To do this, append the index of the bit to be addressed to the variable, separated by a dot. The bit index can be specified by any constant. Indexing is 0-based.
Syntax:
<integer variable name> . <index>
<integer data typ> = BYTE | WORD | DWORD | LWORD | SINT | USINT | INT | UINT | DINT | UDINT | LINT | ULINT
If the type of the variable is not allowed, TwinCAT issues the following error message: Invalid data type <type> for direct indexing. If the index is larger than the bit width of the variable, TwinCAT issues the following error: Index <n> out of valid range for variable <name>.
Sample index access:
In the program the third bit of the variable nVarA
is set to the value of the variable nVarB
.
PROGRAM MAIN
VAR
nVarA : WORD := 16#FFFF;
bVarB : BOOL := 0;
END_VAR
// Index access in an integer variable
nVarA.2 := bVarB;
Result: nVarA = 2#1111_1111_1111_1011 = 16#FFFB
Sample constant as index:
The constant cEnable
acts as an index to access the third bit of the variable nVar
.
// GVL declaration
VAR_GLOBAL CONSTANT
cEnable : USINT := 2;
END_VAR
PROGRAM MAIN
VAR
nVar : INT := 0;
END_VAR
// Constant as index
nVar.cEnable := TRUE; // Third bit in nVar is set TRUE
Result: nVar = 4
Accessibility of the variable defined by the bit number Note that the variable defining the bit number (in the sample above |
Symbolic bit access in structure variables
With the data type BIT
you can designate individual bits with a name and combine them into a structure. The bit is then addressed with the component name.
Sample
Type 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 and write access to a bit:
PROGRAM MAIN
VAR
stControllerDrive1 : ST_ControllerData;
END_VAR
// Symbolic bit access to nStatus_ EnableOperation
stControllerDrive1.nStatus_EnableOperation := TRUE;
Symbolic bit access in function block instances
In function blocks you can declare variables for individual bits.
Sample
Type declaration of the structure:
FUNCTION_BLOCK FB_Controller
VAR_INPUT
nSwitchOnActive : BIT;
nEnableOperation : BIT;
nVoltageEnabled : BIT;
nQuickStop : BIT;
nSwitchOnLocked : BIT;
END_VAR
VAR_OUTPUT
nOperationEnabled : BIT;
nError : BIT;
nWarning : BIT;
END_VAR
VAR
END_VAR
PROGRAM MAIN
VAR
fbController : FB_Controller;
END_VAR
// Symbolic bit access to nSwitchOnActive
fbController(nSwitchOnActive:= TRUE);
See also: