在这里遇到问题后,我需要一些帮助来使用 MATLAB Function 块编写函数。我在以下链接中看到有人用该块或 s-function 解决了它:http: //www.mathworks.co.uk/matlabcentral/newsreader/view_thread/317910
http://www.physicsforums.com/showthread.php?t=595813
http://www.mathworks.de/matlabcentral/newsreader/view_thread/250266
所以我尝试了这个:
function y = fcn(u)
coder.extrinsic('only3')
coder.extrinsic('serial', 'fopen','fread')
coder.extrinsic('set')
persistent s a
y = (zeros(2,1));
s = serial('COM12');
set(s,'Terminator','', 'InputBufferSize', 1024);
a = char('000'); % a-initialization for mxArray problems
a = only3(get(s,'status')); %to check if port is already opened calling custom function
if strncmp(a,'clo',3)==true
fopen(s)
else
fclose(s)
end
y = fread(s,[2 1],'uint8'); % I have to read some data from serial. This command works fine in the matlab command window.
only3
我创建的函数在哪里。它从字符串中获取前 3 个字符,我需要它来比较'status'
答案的三个字符:
function let = only3(string)
let = string(1:3);
我这样做是为了知道通信是否已经打开。但 simulink 以窗口形式返回错误:
Call to MATLAB function aborted: Open failed: Port: COM12 is not available. No ports are available.
我认为它会在第一次迭代中打开端口后尝试打开端口。
编辑:我用这个改变我的代码:
function y = fcn(u)
coder.extrinsic('only3')
coder.extrinsic('strncmp') %like Phil say
coder.extrinsic('serial', 'fopen','fread')
coder.extrinsic('get')
persistent s a b
y = (zeros(2,1));
%%部分取自 Phil 的建议:
if isempty(s)
% only do this the first time
s = serial('COM12','Terminator','', 'InputBufferSize', 1024);
a = '000';
b = false; %without this returns mxArray error.
end
a = only3(get(s,'status'));
b = strncmp(a,'clo',3);
if b == true
fopen(s)
else
fclose(s)
end
y = fread(s,[2 1],'uint8');
它作为错误返回:
Unsuccessful read: OBJ must be connected to the hardware with FOPEN. Block MATLAB Function (#24) While executing: State During Action
突出y
表达。
更新编辑: 我用以下代码解决了它:
function y = fcn(u)
coder.extrinsic('only3')
coder.extrinsic('strncmp')
coder.extrinsic('serial', 'fopen','fread')
coder.extrinsic('get')
persistent s a b
y = uint8(zeros(2,1)); %signal is an uint8
if isempty(s)
% only do this the first time
s = serial('COM12','Terminator','', 'InputBufferSize', 1024);
a = '000';
b = false;
a = only3(get(s,'status'));
b = strncmp(a,'clo',3);
switch double(b)
case 1
fopen(s);
otherwise
fclose(s);
end
end
y = uint8(fread(s,[2 1],'uint8'));
但是,正如我在下面评论的那样,每次我停止模拟时,我都必须重新启动 Matlab,因为它不会关闭通信。我这样说是因为如果我重新尝试开始模拟,它会返回“我的第一个错误”:
Call to MATLAB function aborted: Open failed: Port: COM12 is not available. No ports are available.
我不知道为什么。在 M 代码 Level-1 S-Function 中,运行fclose(s)
每个模拟都会停止类似mdlTerminate
功能的东西。一些建议?