Control Structures
Control structures enable conditional logic and loops for responsive automation programs.
🚀 Enhance Your Development Experience
Get syntax highlighting, IntelliSense, and debugging support for Structured Text:
Install VS Code Extension →IF Statement
// Simple IF statement IF Temperature > 80.0 THEN CoolingFan := TRUE; OverheatAlarm := TRUE; END_IF; // IF-ELSE statement IF StartButton THEN MotorRunning := TRUE; ELSE MotorRunning := FALSE; END_IF; // IF-ELSIF-ELSE statement IF Temperature > 90.0 THEN EmergencyShutdown := TRUE; AlarmLevel := 3; ELSIF Temperature > 75.0 THEN CoolingFan := TRUE; AlarmLevel := 1; ELSE CoolingFan := FALSE; AlarmLevel := 0; END_IF;
CASE Statement
CASE ErrorCode OF 0: // No error ErrorMessage := 'System OK'; AlarmActive := FALSE; 1..10: // Minor errors ErrorMessage := 'Minor fault'; AlarmActive := TRUE; AutoRestart := TRUE; 11..50: // Major errors ErrorMessage := 'Major fault'; AlarmActive := TRUE; AutoRestart := FALSE; ELSE ErrorMessage := 'Unknown error'; AlarmActive := TRUE; END_CASE;
FOR Loop
VAR I : INT; SensorValues : ARRAY[1..10] OF REAL; Sum : REAL := 0.0; END_VAR // Basic FOR loop FOR I := 1 TO 10 DO Sum := Sum + SensorValues[I]; END_FOR; // FOR loop with step FOR I := 1 TO 10 BY 2 DO // Steps: 1, 3, 5, 7, 9 ProcessSensor(SensorValues[I]); END_FOR; // Countdown loop FOR I := 10 TO 1 BY -1 DO ShutdownSequence[I] := TRUE; END_FOR;
WHILE Loop
VAR Position : REAL; Target : REAL := 100.0; Speed : REAL := 5.0; END_VAR // WHILE loop - condition checked before execution WHILE Position < Target DO Position := Position + Speed; MoveMotor(Speed); // Safety check IF Position > 120.0 THEN EXIT; // Exit loop immediately END_IF; END_WHILE; // Process items until queue empty WHILE NOT QueueEmpty DO Item := GetNextItem(); ProcessItem(Item); END_WHILE;
REPEAT Loop
VAR Position : REAL; Attempts : INT := 0; MaxAttempts : INT := 5; END_VAR // REPEAT loop - condition checked after execution REPEAT Position := ReadPosition(); Attempts := Attempts + 1; IF Attempts > MaxAttempts THEN EXIT; // Safety exit END_IF; UNTIL Position > Target END_REPEAT; // Retry logic REPEAT Success := TryOperation(); RetryCount := RetryCount + 1; UNTIL Success OR (RetryCount >= 3) END_REPEAT;
Loop Control
// EXIT - immediately exit the loop FOR I := 1 TO 100 DO IF ErrorCondition THEN EXIT; // Jump out of loop END_IF; ProcessStep(I); END_FOR; // CONTINUE - skip to next iteration FOR I := 1 TO 10 DO IF SensorValues[I] < 0 THEN CONTINUE; // Skip negative values END_IF; ValidSum := ValidSum + SensorValues[I]; END_FOR; // RETURN - exit function/program IF CriticalError THEN RETURN; // Exit immediately END_IF;