Twincat and Structured Text - OOP Basics

Welcome to Part 2 of the TwinCAT and Structured Text.
In this part, we’ll take a look at the Object-Oriented Programming (OOP) features in Structured Text.

OOP allows you to structure your code around objects and data, making your logic modular and easier to manage.


Classes

A CLASS is like a blueprint for objects. It can contain variables, methods and properties.
Classes in Structured Text are Function Blocks


FUNCTION_BLOCK FB_Motor
VAR
    bRunning:   BOOL;
    nSpeed:     INT;
END_VAR

METHOD Start : BOOL
VAR_INPUT
    nTargetSpeed:   INT;
END_VAR
    bRunning:= TRUE;
    nSpeed:= nTargetSpeed;
    Start:= bRunning;
END_METHOD

Instantiation

You can create an instance of the class(Function Block):


VAR
    myMotor:        FB_Motor;
END_VAR

myMotor.Start(1500);

EXTENDS – Inheritance

You can create new classes based on existing ones.


FUNCTION_BLOCK FB_AdvancedMotor EXTENDS FB_Motor
VAR_INPUT
    bOverload:      BOOL;
END_VAR

    SUPER^();

    IF bOverload THEN
        bRunning:= FALSE;
        nSpeed:= 0;
    END_IF

This new class FB_AdvancedMotor inherits everything from FB_Motor and adds new functionality.


Interfaces

Interfaces define a contract. Classes that implement an interface must define its methods.


INTERFACE IMotorControl
    METHOD Start : BOOL
    METHOD Stop : BOOL
    PROPERTY Running : BOOL
END_INTERFACE

Now implement this interface in a class:


FUNCTION_BLOCK FB_Motor IMPLEMENTS IMotorControl
VAR
    bRunning : BOOL;
END_VAR

METHOD Start : BOOL
    bRunning:= TRUE;
    Start:= bRunning;
END_METHOD

METHOD Stop : BOOL
    bRunning:= FALSE;
    Stop:= NOT bRunning;
END_METHOD

Properties

Properties allow controlled access to variables.


FUNCTION_BLOCK FB_Sensor
VAR
    fValue: REAL;
END_VAR

PROPERTY Value: REAL
GET
    Value:= fValue;
SET
    fValue:= Value;
END_PROPERTY

Use it like this:


VAR
    mySensor:           FB_Sensor;
    fTemp:              REAL;
END_VAR

mySensor.Value:= 22.5; // SET
fTemp:= mySensor.Value; // GET

Summary

Object-oriented ST is especially helpful in large automation projects to keep your logic clean and modular.


More to come in Part 3