Safety Function Block#
The PLCOpen organization has defined a set of standard function blocks (FBs) for safety-related functionality. The function block specifications are given as state diagrams. The example presented here implements the equivalent function block.

According to the PLCopen specification, this function block converts two equivalent SAFEBOOL inputs into one SAFEBOOL output with discrepancy time monitoring. If one channel signal changes from TRUE to FALSE, the output immediately switches off (FALSE) for safety reasons.
Discrepancy time monitoring: The discrepancy time is the maximum period during which both inputs may have different states without the function block detecting an error. Discrepancy time monitoring starts when the status of an input changes. The function block detects an error when both inputs do not have the same status once the discrepancy time has elapsed.
The machine presented below is a sample realization of the state diagram specified in the PLCopen document. In contrast to the original PLCopen specification, all states that set the READY output to TRUE are substates of the superstate called ACTIVE. As soon as the ENABLE input becomes inactive, the ACTIVE state is left and IDLE is entered. Using substates reduces the number of required transitions in the diagram significantly.

The class diagram below shows how the sample implementation is designed. The class io_interface provides a hardware abstraction layer for the inputs and outputs required by the function block. The timer class provides general timer functions. Please note that it is only suitable for testing the state machine.
Classes are implemented as C source/header files. The class diagram shows two comments using the action and header keywords, which are supported by the code generator. C code in the “action comment” is copied into the generated C file just before the state-chart code. The listed C code reads and stores the function block inputs in local variables for faster processing. These variables, as well as required headers, are defined in the other comment. Code following the header keyword is copied to the beginning of the generated C file.

The attached example implementation shows how the generated code can be used. The inputs come from a test vector. The code is built with Cygwin and GCC, but it can also be compiled on Linux or macOS, for example. main is the entry point and initializes everything. A number of test cases are implemented and can be uncommented as needed.
Generated files: