如何在M文件S-函数调用串口。

我尝试过在初始化子函数中创建串口,然后打开,在输出子函数中发送数据,在结束子函数中关闭串口。
但是在保证串口可用的前提下,运行仿真后就失败,提示串口不可用。
最后无奈将上述对串口的所有操作都改在输出子函数中完成,仿真可以正确执行,只是速度特别慢,代码如下
function sys=mdlOutputs(t,x,u)
global receivedate;
s=serial('COM5');
s.BaudRate=115200;
s.Parity='None';
s.DataBits = 8;
s.StopBits = 1;
s.InputBufferSize =512;
set(s,'timeout',0.1);
s.ReadAsyncMode ='continuous';
s.BytesAvailableFcnMode = 'terminator';
s.BytesAvailableFcn =@callbackrs232; %调用回调函数
fopen(s);
ustr=num2str(u);
fprintf(s,ustr,'async');%串口输出u
sys = receivedate;
pause(0.1);
fclose(s);
delete(s);
clear s;
请问有没有更合适的方法实现对串口的操作,第一种方法哪里不对

Answers (1)

dowihi
dowihi on 30 Nov 2022

0 votes

data store memory, data store read, data store write三个模块。
memory的初始值设置为0, 根据方程更新后使用write写进去, 读取的时候使用read读取。
参考helper文档查看怎么使用。

Categories

Find more on 作用域变量和生成名称 in Help Center and File Exchange

Tags

Asked:

on 30 Nov 2022

Answered:

on 30 Nov 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!