Start and Terminate Actions Within a C Function Block
This example shows how to use the C Function block to integrate legacy C functions that have start and terminate actions.
In this example, the legacy C functions are defined in fault.h
, and implemented in fault.c
.
To enable calling the C functions from the C Function block, in the model, specify the header file and the source file in the Configuration Parameters > Simulation Target pane. This model opens a log file, writes data to it, and then closes the log file. The openLogFile
function is called in the Start Code section and the closeLogFile
function is called in the Terminate Code section of the C Function block. In the Output Code section, the incAndLogFaultCounter
function is called. The prototype of the legacy functions are:
void* openLogFile()
closeLogFile(void* fid)
incAndLogFaultCounter(void *fid, unsigned int counter, double time)
where, void *fid
is a file pointer, unsigned int counter
is the fault counter, and double time
indicates the time. The maximum value of InputVal
signal can be 255. Each time the signal equals or exceeds a constant value of 250, a fault condition is encountered, and the output code incAndLogFaultCounter
is invoked. The output code increases the fault counter by 1 and appends a new line in slex_CFunction_fault.log
file with time stamp. In the model, the fault signal is represented by FaultVal
signal.
In this example the ports of the C Function block are configured as follows:
The file pointer returned by
openLogFile
function and the fault counter are persistent symbols of the C Function block.The input of the C Function block is mapped to time.
model = 'slexCFunctionStartTerm';
open_system(model);
sim(model);
Use the Scope block to visualize the output. The output compares the InputVal
signal value with the value of FaultVal
signal.
open_system('slexCFunctionStartTerm/Scope')