C.2 Example of a FUNCTION_BLOCK 325
C.2 Example of a FUNCTION_BLOCK
The function block
DivWithRem
calculates the result of dividing two integers and
returns both the division result and the remainder. "Division by zero" is indicated
by an output flag.
FUNCTION_BLOCK DivWithRem (* division with remainder *)
(* beginning of declaration part *)
VAR_INPUT (* input parameter *)
Dividend : INT; (* integer to be divided *)
Divisor : INT; (* integral divisor *)
END_VAR
VAR_OUTPUT RETAIN (* retentive output parameters *)
Quotient : INT; (* result of the division *)
DivRem : INT; (* remainder after division *)
DivError : BOOL; (* flag for division by zero *)
END_VAR
(* beginning of instruction part *)
LD 0 (* load zero *)
EQ Divisor (* divisor equal to zero? *)
JMPC Error (* catch error condition*)
LD Dividend (* load dividend, divisor not equal to zero *)
DIV Divisor (* carry out division *)
ST Quotient (* store integral division result *)
MUL Divisor (* multiply division result by divisor *)
ST DivRem (* store interim result *)
LD Dividend (* load dividend *)
SUB DivRem (* subtract interim result *)
ST DivRem (* yields "remainder" of the division as an integer*)
LD FALSE (* load logical "0“ for error flag *)
ST DivError (* reset error flag *)
JMP End (* ready, jump to end *)
Error: (* handling routine for error "division by zero" *)
LD 0 (* zero, since outputs are invalid in event of error *)
ST Quotient (* reset Result *)
ST DivRem (* reset Remainder *)
LD TRUE (* load logical "1“ for error flag *)
ST DivError (* set error flag *)
End:
RET
(* end of FB *)
END_FUNCTION_BLOCK
Example C.4. Example of the declaration of a function block in IL
The FB
DivWithRem
in Example C.4 performs integer division with remainder on
the two input parameters
Dividend
and
Divisor
. In the case of division by zero, the
error output
DivError
is set and the other two outputs are set in a defined manner to
zero since they are invalid. The outputs are retentive, i.e. they are retained within
the FB instance from which
DivWithRem
was called.