Twincat and Structured Text

Getting in a new programming language can be difficult somethimes.
I will try to get you an short overview, to get started.

Variables

Variables are containers for storing data values.


VAR
    // Internal logic variable (no hardware link)
    bState:     BOOL;  
    // Flexible input (auto-assigned by TwinCAT)
    bSensor     AT %I*: BOOL;  // e.g., connected to a sensor  
    // Flexible output (auto-assigned by TwinCAT)
    nSetValue   AT %Q*: UINT;  // e.g., drives an actuator  
    // Optional: Directly addressed example
    // bEmergencyStop AT %IX5.3: BOOL;  // Input bit 5.3
END_VAR

Attributes

Variables can have some custom attributes,
which can help to debug code in online mode.
There are many more in the twincat documentation.


VAR
    {attribute 'hide'} 
    bHide:     BOOL;   // will be hidden
    {attribute 'displaymode':='hex'} 
    nValue     AT %I*: UINT;    // displayed as hex value
    {attribute 'TcDisplayScale' := '0-10'}
    nSetValue   AT %Q*: UINT;   // 0-10  
END_VAR

Datatypes

Variables must have a specified data type.

Data TypeSizeDescription
BOOL1 byteLogical value: TRUE or FALSE
BYTE1 byteUnsigned 8-bit integer (0 to 255)
INT2 bytesSigned 16-bit integer (-32,768 to 32,767)
UINT2 bytesUnsigned 16-bit integer (0 to 65,535)
DINT4 bytesSigned 32-bit integer
UDINT4 bytesUnsigned 32-bit integer
LINT8 bytesSigned 64-bit integer
ULINT8 bytesUnsigned 64-bit integer
REAL4 bytes32-bit floating point (single precision)
LREAL8 bytes64-bit floating point (double precision)
STRING1 bytesASCII string null-terminated
WSTRING2 bytesWide-character string UTF-16

Structs

A STRUCT is define a group of variables


TYPE MotorData :
STRUCT
    speed:          REAL;
    current:        REAL;
    isRunning:      BOOL;
END_STRUCT
END_TYPE

Operators

How operators look like

Logical Operators

OperatorNameDescription
ANDANDonly if both inputs are TRUE
ORORTRUE if at least one input is TRUE
NOTNOTInverts the input
XORXORTRUE if inputs are different

Bitwise Operators

OperatorNameDescription
ANDANDPerforms bitwise AND
ORORPerforms bitwise OR
XORXORPerforms bitwise XOR
NOTNOTInverts all bits
SHLShift LeftShifts bits left
SHRShift RightShifts bits right

Comparison Operators

OperatorNameDescription
=EqualChecks if two values are equal.
<>Not EqualChecks if two values are different.
>Greater ThanLeft operand is greater than
<Less ThanLeft operand is smaller than
>=Greater EqualLeft operand is greater than or equal
<=Less EqualLeft operand is smaller than or equal

If Statement

IF statement is used to test a condition and to execute the subsequent instructions


VAR
    bExecute:           BOOL;
    bCondition:         BOOL;
END_VAR

    // Simple IF statement
    IF bExecute THEN
        // Code executes only if bExecute is TRUE
    END_IF

    // IF-ELSE structure
    IF bExecute THEN
        // Runs when bExecute is TRUE
    ELSE
        // Runs when bExecute is FALSE
    END_IF

    // IF-ELSIF-ELSE structure (multiple conditions)
    IF bExecute THEN
        // Executes if bExecute is TRUE
    ELSIF bCondition THEN
        // Executes if bCondition is TRUE (bExecute is FALSE)
    ELSE
        // Executes if neither bExecute nor bCondition is TRUE
    END_IF

Switch Statement

CASE instruction is used to group multiple conditional instructions


VAR
    nSwitch:            INT;
END_VAR

    CASE nSwitch OF
        0: 
            // Code block for case x
        1: 
            // Code block for case y
    ELSE
        // Default code block (when no cases match)
    END_CASE

Loops

For Loop

FOR loop is used to execute instructions with a specific number of retries


VAR
    nIndex:             INT;
    aData:              ARRAY [0..9] OF REAL:= [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
END_VAR

    // mimimal example
    FOR nIndex := 0 TO 9 DO // with step width FOR nIndex := 0 TO 9 BY 1 DO
        // Output the current value of nIndex
        ADSLOGSTR(ADSLOG_MSGTYPE_HINT, 'Log Message: %s',  LREAL_TO_FMTSTR( aData[nIndex], 2, TRUE ));
    END_FOR

Exit a for loop early and return to the program flow


FOR nCounter:= 0 TO 10 DO
    IF nCounter >= 5 THEN
        EXIT;
    END_IF
END_FOR

While Loop

WHILE loop is used to execute instructions repeatedly until the termination condition applies


VAR
    nIndex : INT := 0; // Initialize index
END_VAR

    WHILE nIndex < 5 DO
        ADSLOGSTR(ADSLOG_MSGTYPE_HINT, 'Log Message: %s', INT_TO_STRING(nIndex));
        nIndex := nIndex + 1; // Increment index
    END_WHILE

Exit a while loop


WHILE nIndex < 5 DO
    IF nIndex >= 1000 then
         EXIT;   
    END_IF
    nIndex := nIndex + 1; // Increment index
END_WHILE

More will follow in part 2