Standard Functions Reference
IEC 61131-3 defines a comprehensive library of standard functions for type conversion, mathematical operations, string manipulation, and date/time handling essential for industrial automation applications.
🚀 Enhance Your Development Experience
Get syntax highlighting, IntelliSense, and debugging support for Structured Text:
Install VS Code Extension →Type Conversion Functions
Type Conversion Functions
VAR
// Source values
BoolVal : BOOL := TRUE;
IntVal : INT := 42;
DIntVal : DINT := 123456;
RealVal : REAL := 25.75;
StringVal : STRING := '3.14159';
// Conversion results
ConvertedInt : INT;
ConvertedReal : REAL;
ConvertedString : STRING;
ConvertedBool : BOOL;
END_VAR
// Boolean conversions
ConvertedInt := BOOL_TO_INT(BoolVal); // TRUE → 1, FALSE → 0
ConvertedReal := BOOL_TO_REAL(BoolVal); // TRUE → 1.0, FALSE → 0.0
ConvertedString := BOOL_TO_STRING(BoolVal); // TRUE → 'TRUE', FALSE → 'FALSE'
// Integer conversions
ConvertedBool := INT_TO_BOOL(IntVal); // 0 → FALSE, ≠0 → TRUE
ConvertedReal := INT_TO_REAL(IntVal); // 42 → 42.0
ConvertedString := INT_TO_STRING(IntVal); // 42 → '42'
// Real conversions
ConvertedInt := REAL_TO_INT(RealVal); // 25.75 → 25 (truncated)
ConvertedString := REAL_TO_STRING(RealVal); // 25.75 → '25.75'
// String conversions (with error handling)
ConvertedReal := STRING_TO_REAL(StringVal); // '3.14159' → 3.14159
ConvertedInt := STRING_TO_INT('100'); // '100' → 100
ConvertedBool := STRING_TO_BOOL('TRUE'); // 'TRUE' → TRUE
// Extended type conversions
ConvertedLReal := DINT_TO_LREAL(DIntVal); // 32-bit to 64-bit real
ConvertedWord := INT_TO_WORD(IntVal); // Reinterpret as bit string⚠️ Conversion Safety Guidelines
- • Always validate string-to-number conversions for invalid input
- • Check for overflow when converting to smaller data types
- • Real-to-integer conversion truncates (doesn't round)
- • Use exception handling for string conversion errors
- • Consider locale settings for decimal point formatting
Mathematical Functions
Mathematical Functions
VAR
InputValue : REAL := -15.7;
Angle : REAL := 30.0; // Degrees
AngleRad : REAL; // Radians
// Results
AbsResult : REAL;
SqrtResult : REAL;
TrigResults : REAL;
LogResults : REAL;
RoundResults : INT;
END_VAR
// Basic mathematical functions
AbsResult := ABS(InputValue); // |-15.7| = 15.7
SqrtResult := SQRT(25.0); // √25 = 5.0
// Trigonometric functions (angles in radians)
AngleRad := Angle * 3.14159 / 180.0; // Convert degrees to radians
TrigResults := SIN(AngleRad); // sin(30°) = 0.5
TrigResults := COS(AngleRad); // cos(30°) = 0.866
TrigResults := TAN(AngleRad); // tan(30°) = 0.577
// Inverse trigonometric functions
TrigResults := ASIN(0.5); // arcsin(0.5) = 0.524 rad (30°)
TrigResults := ACOS(0.866); // arccos(0.866) = 0.524 rad (30°)
TrigResults := ATAN(1.0); // arctan(1.0) = 0.785 rad (45°)
// Logarithmic and exponential functions
LogResults := LN(2.71828); // Natural log: ln(e) = 1.0
LogResults := LOG(100.0); // Base-10 log: log₁₀(100) = 2.0
LogResults := EXP(1.0); // Exponential: e¹ = 2.71828
// Rounding functions
RoundResults := TRUNC(15.7); // Truncate: 15.7 → 15
RoundResults := ROUND(15.7); // Round: 15.7 → 16
RoundResults := CEIL(15.1); // Ceiling: 15.1 → 16
RoundResults := FLOOR(15.9); // Floor: 15.9 → 15
// Power function
LogResults := EXPT(2.0, 3.0); // 2³ = 8.0
// Modulo operation
RoundResults := MOD(17, 5); // 17 mod 5 = 2Basic Math Functions
- • ABS(x): Absolute value
- • SQRT(x): Square root
- • EXPT(x,y): x raised to power y
- • MOD(x,y): x modulo y
Trigonometric Functions
- • SIN/COS/TAN: Basic trig functions
- • ASIN/ACOS/ATAN: Inverse functions
- • Note: All angles in radians
- • π ≈ 3.14159265359
String Functions
String Manipulation Functions
VAR
SourceString : STRING := 'Hello World Programming';
SubString : STRING := 'World';
NewString : STRING;
Position : INT;
StringLength : INT;
FirstName : STRING := 'John';
LastName : STRING := 'Smith';
FullName : STRING;
DataString : STRING := 'Temperature: 25.5°C';
ExtractedValue : STRING;
END_VAR
// String length
StringLength := LEN(SourceString); // Returns 21
// Extract substrings
NewString := LEFT(SourceString, 5); // 'Hello'
NewString := RIGHT(SourceString, 11); // 'Programming'
NewString := MID(SourceString, 7, 5); // 'World' (start at pos 7, length 5)
// String concatenation
FullName := CONCAT(FirstName, ' ', LastName); // 'John Smith'
// Alternative syntax for multiple strings
FullName := CONCAT(CONCAT(FirstName, ' '), LastName);
// String search
Position := FIND(SourceString, SubString); // Returns 7 (1-based index)
Position := FIND(SourceString, 'XYZ'); // Returns 0 (not found)
// String insertion
NewString := INSERT(SourceString, ' Beautiful', 6);
// Result: 'Hello Beautiful World Programming'
// String deletion
NewString := DELETE(SourceString, 6, 6); // Remove 6 chars from pos 6
// Result: 'Hello Programming'
// String replacement
NewString := REPLACE(SourceString, 'World', 'Universe', 1);
// Result: 'Hello Universe Programming'
// Practical example: Extract numeric value from string
Position := FIND(DataString, ': '); // Find ': ' position
IF Position > 0 THEN
ExtractedValue := MID(DataString, Position + 2, 4); // Extract '25.5'
END_IF;
// String comparison (case-sensitive)
IF SourceString = 'Hello World Programming' THEN
// Strings match exactly
END_IF;String Analysis Functions
- • LEN(str): String length
- • FIND(str, sub): Find substring position
- • LEFT(str, n): First n characters
- • RIGHT(str, n): Last n characters
- • MID(str, pos, len): Substring
String Modification Functions
- • CONCAT(str1, str2): Join strings
- • INSERT(str, sub, pos): Insert substring
- • DELETE(str, pos, len): Remove characters
- • REPLACE(str, old, new, n): Replace substring
Date and Time Functions
Date and Time Functions
VAR
// Time values
Duration1 : TIME := T#5h30m;
Duration2 : TIME := T#2h15m;
TotalTime : TIME;
RemainingTime : TIME;
// Date values
StartDate : DATE := D#2024-01-15;
EndDate : DATE := D#2024-06-15;
ProjectDuration : TIME;
// Date and time combination
StartDateTime : DATE_AND_TIME := DT#2024-06-15-08:30:00;
EndDateTime : DATE_AND_TIME;
// Time of day
StartTime : TIME_OF_DAY := TOD#08:30:00;
EndTime : TIME_OF_DAY := TOD#17:00:00;
WorkingHours : TIME;
END_VAR
// Time arithmetic
TotalTime := ADD_TIME(Duration1, Duration2); // T#7h45m
RemainingTime := SUB_TIME(Duration1, Duration2); // T#3h15m
// Date arithmetic (if supported by implementation)
ProjectDuration := SUB_DATE(EndDate, StartDate); // Difference in days
EndDate := ADD_TIME_TO_DATE(StartDate, T#150d); // Add 150 days
// Combining date and time
EndDateTime := CONCAT_DATE_TOD(EndDate, EndTime);
// Result: DT#2024-06-15-17:00:00
// Extract components
VAR
CurrentYear : INT;
CurrentMonth : INT;
CurrentDay : INT;
CurrentHour : INT;
CurrentMinute : INT;
END_VAR
// Extract date/time components (implementation-specific)
CurrentYear := YEAR(StartDateTime); // 2024
CurrentMonth := MONTH(StartDateTime); // 6
CurrentDay := DAY(StartDateTime); // 15
CurrentHour := HOUR(StartDateTime); // 8
CurrentMinute := MINUTE(StartDateTime); // 30
// Time comparison
IF Duration1 > Duration2 THEN
// Duration1 is longer
END_IF;
// Working time calculation
WorkingHours := SUB_TOD(EndTime, StartTime); // T#8h30m
// Practical example: Shift timing
VAR
ShiftStart : TIME_OF_DAY := TOD#06:00:00;
ShiftEnd : TIME_OF_DAY := TOD#14:00:00;
CurrentTime : TIME_OF_DAY;
InShift : BOOL;
END_VAR
CurrentTime := GetCurrentTOD(); // System function
InShift := (CurrentTime >= ShiftStart) AND (CurrentTime <= ShiftEnd);Date/Time Function Categories
Arithmetic Functions:
- • ADD_TIME: Add time durations
- • SUB_TIME: Subtract time durations
- • ADD_TIME_TO_DATE: Add time to date
- • SUB_DATE: Subtract dates
Combination Functions:
- • CONCAT_DATE_TOD: Combine date and time
- • SPLIT_DT: Split date/time
- • Various extractors: YEAR, MONTH, DAY, etc.
Practical Application Examples
Practical Applications of Standard Functions
// Process monitoring with data logging
FUNCTION_BLOCK ProcessMonitor
VAR_INPUT
ProcessValue : REAL;
Setpoint : REAL;
ProcessName : STRING;
END_VAR
VAR_OUTPUT
LogMessage : STRING;
AlarmStatus : BOOL;
END_VAR
VAR
Deviation : REAL;
DeviationPercent : REAL;
TimeStamp : STRING;
ValueString : STRING;
END_VAR
// Calculate process deviation
Deviation := ProcessValue - Setpoint;
DeviationPercent := ABS(Deviation / Setpoint) * 100.0;
// Convert values to strings for logging
ValueString := REAL_TO_STRING(ProcessValue);
TimeStamp := DT_TO_STRING(GetCurrentDateTime());
// Build log message
LogMessage := CONCAT(TimeStamp, ': ');
LogMessage := CONCAT(LogMessage, ProcessName);
LogMessage := CONCAT(LogMessage, ' = ');
LogMessage := CONCAT(LogMessage, ValueString);
// Alarm check
AlarmStatus := DeviationPercent > 10.0;
IF AlarmStatus THEN
LogMessage := CONCAT(LogMessage, ' [ALARM]');
END_IF;
END_FUNCTION_BLOCK
// Recipe calculation system
FUNCTION CalculateIngredientAmount : REAL
VAR_INPUT
RecipeString : STRING; // Format: "Ingredient:Percentage"
BatchSize : REAL;
END_VAR
VAR
ColonPos : INT;
PercentString : STRING;
PercentValue : REAL;
END_VAR
// Parse recipe string
ColonPos := FIND(RecipeString, ':');
IF ColonPos > 0 THEN
PercentString := RIGHT(RecipeString, LEN(RecipeString) - ColonPos);
PercentValue := STRING_TO_REAL(PercentString);
CalculateIngredientAmount := BatchSize * PercentValue / 100.0;
ELSE
CalculateIngredientAmount := 0.0; // Error in format
END_IF;
END_FUNCTION🎯 Function Selection Guidelines
- • Type Conversion: Always validate inputs and handle errors gracefully
- • Mathematical: Consider precision requirements and valid input ranges
- • String Functions: Be aware of 1-based indexing and string length limits
- • Date/Time: Understand timezone handling and system clock synchronization
- • Performance: Cache results of expensive calculations when possible
- • Portability: Some advanced functions may be implementation-specific
