Simulink S-Function
S-Function是system-function的缩写。S-Function就是用MATLAB所提供的模块不能完全满足用户,而提供给用户自己编写程序来满足自己要求模型的接口,这样提供了扩充和灵活性。
S-Function可以用M、C/C++、Ada、Fortran 语言以MEX(Matlab Executable,MATLAB可执行文件,在Windows系统中就是其为DLL)文件的形式编写。
通过S-Function,用户可以将自己的模块加入Simulink模型中。从而可以实现用户自定义的算法或者与硬件设备交互等。
本文将使用C Mex的S-Function进行Joystick的输入解析。
Windows平台的S-Function
Windows平台的S-Function在MathWorks官网上有几个版本:
1.Per Hillerborg (2022). sfun_joystick.zip (https://www.mathworks.com/matlabcentral/fileexchange/47141-sfun_joystick-zip), MATLAB Central File Exchange
2.Johannes Soikkeli (2022). S-Function for reading joystick values on Simulink (https://www.mathworks.com/matlabcentral/fileexchange/111265-s-function-for-reading-joystick-values-on-simulink), MATLAB Central File Exchange.
其中2参考了1,函数很简单,读者可参考链接。
本文要在这个S-Function上适配Linux平台,为什么呢?因为项目要在linux平台上用。
代码
有了Windows源码,Linux部分更简单了。
直接上代码吧,这里略去一部分。
#include "simstruc.h"
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#elif __linux__
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/joystick.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#endif
#ifdef _WIN32
JOYINFOEX joy; // Struct into which joystick state is returned.
MMRESULT rc; // Return code of function.
#e/lif __linux__
int joystick_fd;
//int *axis = NULL;
//char *button = NULL;
#endif
/* Error handling
* --------------
*
* You should use the following technique to report errors encountered within
* an S-function:
*
* ssSetErrorStatus(S,"Error encountered due to ...");
* return;
*
* Note that the 2nd argument to ssSetErrorStatus must be persistent memory.
* It cannot be a local variable. For example the following will cause
* unpredictable errors:
*
* mdlOutputs()
* {
* char msg[256]; {ILLEGAL: to fix use "static char msg[256];"}
* sprintf(msg,"Error due to %s", string);
* ssSetErrorStatus(S,msg);
* return;
* }
*
*/
/*====================*
* S-function methods *
*====================*/
/* Function: mdlInitializeSizes ===============================================
* Abstract:
*

本文介绍如何使用Simulink的S-Function实现Joystick输入解析,并展示了在Windows和Linux平台上的代码实现细节。
最低0.47元/天 解锁文章
269

被折叠的 条评论
为什么被折叠?



