汽车嵌入式开发中,基于MBD的上层算法开发非常普及。在实际工程中会有这样的需求:做算法的工程师想调用底层接口或者将自定义功能的算法封装成模块,方便模型搭建时使用。
这里有两点需要实现:自定义一个库、在自定义库中创建自定义模块(C MEX S-Function)。
1、切换matlab自定义工作路径
2、创建Library模型
3、编写slblocks.m
function blkStruct = slblocks
% This function specifies that the library should appear
% in the Library Browser
% and be cached in the browser repository
Browser.Library = 'Lotus_SupportPacket';
% 'Lotus_SupportPacket' is the name of the library
Browser.Name = 'Lotus_CMEX_SFunction';
% 'Lotus_CMEX_SFunction' is the library name that appears
% in the Library Browser
blkStruct.Browser = Browser;
4、编写sl_customization.m文件
function sl_customization(cm)
cm.LibraryBrowserCustomizer.applyOrder( {'Lotus_SupportPacket', -2} );
end
5、创建一个空白模型,检查Library在Simulink下的显示
(1)创建Blank Model,如下所示:
这一步也可以使用命令方式设置,命令如下所示,即将自定义库在Simulink Library列表中显示。
set_param(gcs,'EnableLBRepository','on');
1、源文件准备
typedef unsigned char uint8;
extern uint8 ComM_GetCurrentComMode(uint8 u1,uint8* u2);
#include "ComM.h"
uint8 ComM_GetCurrentComMode(uint8 User,uint8* ComMode){
return 0;
}
2、创建lct对应的M脚本(lct_CMEXSFunction.m)
注意:def1.OutputFcnSpec语句中有两个输入,分别使用了u1和u2来表示输入的参数,使用y1来标识输出的参数。即用y来表示输出,用u来表示输入,P表示参数,这三个参数的书写形式固定不变,即不能使用其他参数表示。
clc;
def1=legacy_code('initialize');
def1.SFunctionName = 'ComM_GetCurrentComMode';
def1.OutputFcnSpec = 'uint8 y1 = ComM_GetCurrentComMode(uint8 u1,uint8 u2[1])';
def1.HeaderFiles = {'ComM.h'};
def1.SourceFiles = {'ComM.c'};
legacy_code('sfcn_cmex_generate',def1);
legacy_code('compile',def1);
legacy_code('generate_for_sim', def1);
legacy_code('slblock_generate', def1);
3、运行lct_CMEXSFunction.m文件
(2)将自定义模块拖曳到Lotus_SupportPacket模型库,并保存,如下所示:
1、创建模型:LotusModel.slx
在自定义库中将自定义的C MEX S-Function拖曳到模型中,如下所示:
2、配置模型生成代码
(1)在“Model Settings”中完成模型必要配置并保存,如下所示:
联系客服