Function

A function is a POU, which yields exactly one data element (which can consist of several elements, such as fields or structures) when it is processed, and whose call in textual languages can occur as an operator in expressions.

When declaring a function do not forget that the function must receive a type. This means, after the function name, you must enter a colon followed by a type.

Example

A correct function declaration can look like this:

FUNCTION Fct: INT

In addition, a result must be assigned to the function. That means that function name is used as an output variable.

A function declaration begins with the keyword FUNCTION. Regard the Recommendations \ on the naming of identifiers.

Example of a function Fct in IL, in which \ three input variables are declared:

The first both input variables get multiplicated and then divided by the third one. The function returns the result of this operation:

Declaration part:

FUNCTION Fct: INT
VAR_INPUT
PAR1:INT;
PAR2:INT;
PAR3:INT;
END_VAR

Implementation part:

LD PAR1
MUL PAR2
DIV PAR3
ST Fct

Calling \ a function:

In ST a function call can be used as operand in an expression.

In SFC a function call can only take place within actions of a step or a transition.

Note

CoDeSys allows using global variables within a function. This intentionally deviates from the IEC61131-3 standard, which prescribes that return value of a function only will be modified by the input parameters. Thus the difference between functions and programs is just, that functions return only one return value and that their parameters and return values are handled over the stack.

Examples for calling the above \ described function Fct:

in IL:

LD 7
Fct 2,4
ST  Ergebnis

in ST:

Ergebnis := Fct(7, 2, 4);

in FUP:

../_images/f1d2555d43757ef30a33139006eab46b1

Attention

If a local variable in a function is declared as RETAIN, this will be without any effect. The variable will not be saved in the Retain area !

Note

- If you define a function in your project with the name CheckBounds, you can use it to check for range overflows in ARRAY

- If you define functions in your project with the names CheckDivByte, CheckDivWord, CheckDivDWord and CheckDivReal, you can use them to check the value of the divisor if you use the operator DIV, for example to avoid a division by 0.

- If you define functions with the names CheckRangeSigned and CheckRangeUnsigned, then range exceeding of variables declared with Subrange types can be intercepted.

All these check function names are reserved for the described usage.