MATLAB串口通信例子
(一) 直接读取
首先,我们来试试编写一个.m程序,直接读取串口数据。更多技术细节在程序中的注释中说明。
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 函数功能: 串口接收数据程序
% 将接收到的数据显示在命令行,每次仅读取一个字节
% 需要用虚拟串口 VSPD 虚拟一对串口,这里虚拟连接的串口是 COM1和COM2
% 用UartAssist(串口调试助手)设置为COM2,作为发送数据端
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ReadWriteSerial
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
obj1=instrfind('Type','serial','Port','COM1','Tag','');
if isempty(obj1)
obj1=serial('COM1');
else
fclose(obj1);
obj1=obj1(1);
end
% 串口的一些设置
set(obj1,'BaudRate',9600,'FlowControl','none','Timeout',0.1);
set(obj1,'Inputbuffersize',512,'Outputbuffersize',...
512,'parity','none','databits',8,'stopbits',1);
fopen(obj1);
while(1)
if obj1.BytesAvailable
data=fread(obj1,1); % 按照每次读取一个字节
string=setstr(data); % 将ASCII码转换为字符
string % 显示在命令行
end
end
fclose(obj1);
delete(obj1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
(二) GUI界面读写串口数据
在命令行窗口输入guide命令或者在菜单栏中File->New->GUI,探出以下界面
然后我们选择创建一个新的GUI界面,我们创建以下控件元素,注意,有几个很重要空间的Tag属性的修改,比如打开串口为btnOpen,关闭按钮为btnClose,发送按钮Tag为btnSend,清楚按钮为btnClear,选择串口的下拉框为selectCom,波特率的下拉框为baudRate,接收数据的编辑框为editRecv,发送数据的编辑框为editSend,左边最大的那个是坐标轴,Ta