写作时间:2020-09-27
目录:
无
正文
创建虚拟串口,查看是否发送成功
代码:
1)创建串口部分
%%创建串口以及判断串口状态
% Value changed function: Button_seiCom
function Button_seiComValueChanged(app, event)
value = app.Button_seiCom.Value;
switch value
case 1
%串口创建
delete(instrfindall);%销系统之前已经打开的串口资源
try
seriComName=app.EditField_seiComName.Value;
app.sObject=serial(seriComName);%创建串口
catch
StrArrayNew={'error:该串口可能被别的应用占用或串口命名错误!'};
logRefresh_func(app,StrArrayNew);
return;
end
set(app.sObject,'BaudRate',115200); %设置波特率
set(app.sObject,'inputBufferSize',1024) %设置输入缓冲区域为1K
set(app.sObject,'outputBufferSize',1024) %设置输出缓冲区域为1K
set(app.sObject,'Timeout',0.5);%设置一次写入或者读入操作完成最大时间为0.5s时间单位为秒。
set(app.sObject,'Terminator','LF');%串口触发字符"换行符”
if app.sObject.Status == "closed"
% 打开串口
try
fopen(app.sObject);
catch
StrArrayNew={'error:该串口可能被别的应用占用或串口命名错误'};
logRefresh_func(app,StrArrayNew);
return
end
if(app.sObject.Status == "open")
app.Lamp_seriComStatus.Color="green";
StrArrayNew={'msg:串口打开成功'};
logRefresh_func(app,StrArrayNew);
else
app.Lamp_seriComStatus.Color="red";
StrArrayNew={'error:串口打开失败'};
logRefresh_func(app,StrArrayNew);
end
else
app.Lamp_seriComStatus.Color="yellow";
StrArrayNew={'error:串口被占用'};
logRefresh_func(app,StrArrayNew);
end
case 0
%断开串口
delete(instrfindall);
app.sObject=[];
app.Lamp_seriComStatus.Color="red";
StrArrayNew={'msg:串口已断开'};
logRefresh_func(app,StrArrayNew);
end
end
2)串口发送部分
function ButtonPushed(app, event)
%%串口发送模块
%检查端口是否在线--串口
if isempty(app.sObject)
StrArrayNew={'串口未连接 '};
logRefresh_func(app,StrArrayNew);
return
end
%按照空格键将字符串拆分
%将1*1的字符串数组拆分成1*n的字符串数组
C=strsplit(app.EditField.Value);
nn=length(C);
dataSend=zeros(1,nn);
for ii=1:nn
dataSend(ii)=hex2dec(C(ii));
end
%开始发送
fwrite(app.sObject,dataSend,'uint8'); % 以二进制形式向obj写入数据dataSend
%发送完成,日志显示
StrArrayNew={'发送成功'};
logRefresh_func(app,StrArrayNew);
end
THE END~