基于S-Function的Joystick Input

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

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:
 *    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值