Simulink Customize send component to ONLY receive event/message from external c/c++ code
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi,
currently, there is a Send Component in the example, responsible to send sine wave data to a receiver component. my problem is that, this process is being done in a somehow "Scheduled" manner and even when I changed sine wave with a Constant block, it also sends the message in every time step. My goal is to create a project that messages ONLY can be sent from an external c/c++ code to the send component "Not every time step and only whenever my c/c++ code decides to send".
thanks
0 Kommentare
Antworten (1)
Shubham
am 10 Sep. 2024
Hi Jafar,
It seems that you want to modify your Simulink model to ensure a message is sent only when triggered by external C/C++ code. To achieve this, follow these steps:
1. Create the external C/C++ code.
#include "mex.h"
#include <stdbool.h>
/* External function to determine if a message should be sent */
bool shouldSendMessage() {
static int counter = 0;
counter++;
return (counter % 5 == 0);
}
/* Gateway function for the MEX file */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if (nrhs != 0) {
mexErrMsgIdAndTxt("MyToolbox:shouldSendMessage:nrhs", "No input required.");
}
if (nlhs != 1) {
mexErrMsgIdAndTxt("MyToolbox:shouldSendMessage:nlhs", "One output required.");
}
bool result = shouldSendMessage();
plhs[0] = mxCreateLogicalScalar(result);
}
2. Implement the "S-function" to interface with the external C/C++ code.
#define S_FUNCTION_NAME my_sfunction
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include "mex.h"
static void mdlInitializeSizes(SimStruct *S) {
ssSetNumSFcnParams(S, 0);
if (!ssSetNumInputPorts(S, 0)) return;
if (!ssSetNumOutputPorts(S, 1)) return;
ssSetOutputPortWidth(S, 0, 1);
ssSetNumSampleTimes(S, 1);
}
static void mdlInitializeSampleTimes(SimStruct *S) {
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}
static void mdlOutputs(SimStruct *S, int_T tid) {
real_T *y = ssGetOutputPortRealSignal(S, 0);
mxArray *lhs[1];
mexCallMATLAB(1, lhs, 0, NULL, "external_code");
y[0] = mxGetScalar(lhs[0]);
mxDestroyArray(lhs[0]);
}
static void mdlTerminate(SimStruct *S) {}
#ifdef MATLAB_MEX_FILE
#include "simulink.c"
#else
#include "cg_sfun.h"
#endif
3. Compile the external C/C++ code and the "S-function" as a MEX file.
4. Connect the output of the "S-Function" block to the input of the "Send Component" in your Simulink model.
5. Run the Simulink model.
The "S-Function" block will call "shouldSendMessage" at each simulation step, sending a message only when "shouldSendMessage" returns true (every 5th step in this example).
For more information on "S-function", refer to the following MathWorks documentation link:
Hope this helps.
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!