Learn BECKHOFF-TWINCAT with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
1
Simple Output Toggle (Structured Text)
IF Input_Signal THEN
DO_Toggle := NOT DO_Toggle
END_IF
Toggles a digital output whenever an input signal is TRUE.
2
Motor Start Logic
IF Start_Button AND NOT Stop_Button THEN
Motor_Running := TRUE
ELSE
Motor_Running := FALSE
END_IF
Starts the motor when Start is pressed and Stop is not active.
3
Analog Scaling Function
Scaled_Value := (AI_Raw - 0) * (100.0 - 0.0) / (27648 - 0)
Scales a raw analog input to engineering units.
4
Timer Example (TON)
TON_1(IN := Enable_Signal, PT := T#5S)
IF TON_1.Q THEN
Output_Signal := TRUE
END_IF
Runs a TON timer when input is true and sets an output.
5
Rising Edge Detection
R_TRIG_1(CLK := Input_Flag)
IF R_TRIG_1.Q THEN
Pulse_Output := TRUE
END_IF
Detects rising edges of a boolean input.
6
Basic PID Control Assignment
PID_1.PV := Tank_Level
PID_1.SP := Level_Setpoint
Controller_Output := PID_1.CV
Assigns process variables into a PID block.
7
Fault Latching Logic
IF Fault_Signal THEN
Fault_Latched := TRUE
END_IF
IF Reset_Button THEN
Fault_Latched := FALSE
END_IF
Latches a fault until reset is pressed.
8
Counter Up Logic
CTU_1(CU := Pulse_In, R := Reset_Counter, PV := 100)
Pulse_Count := CTU_1.CV
Counts the number of pulses received.
9
Mode Selection (Auto/Manual)
IF Mode_Select = 1 THEN
Auto_Mode := TRUE
Manual_Mode := FALSE
ELSE
Auto_Mode := FALSE
Manual_Mode := TRUE
END_IF
Switches control mode based on selector input.
10
Emergency Stop Logic
IF EStop_Active THEN
All_Outputs := FALSE
END_IF
Turns off all outputs when E-Stop is active.