Matlab串口函数.docx
- 文档编号:15771608
- 上传时间:2023-07-07
- 格式:DOCX
- 页数:12
- 大小:67.06KB
Matlab串口函数.docx
《Matlab串口函数.docx》由会员分享,可在线阅读,更多相关《Matlab串口函数.docx(12页珍藏版)》请在冰点文库上搜索。
Matlab串口函数
Matlab串口函数
2009-09-2521:
22
Matlab是数学计算的强大工具,它以矩阵作为数据操作的基本单位,广泛应用在以矩阵运算为主要工作方式的数理统计、自动控制、数字信号处理、动态系统仿真等领域。
Matlab便捷灵活、操作简单、处理功能强大,因而利用Matlab对采
集到的ABS试验数据进行分析处理是非常合适的,关键问题是如何将数据从ECU传到计算机。
Matlab支持面向对象技术,用一个对象将计算机串口封装起来,只要创建串口对象,对串口对象操作就是对串口操作,非常方便。
使用serial函数就可创建串口对象,串口对象有很多属性[4],通过定义串口对象的属性,能定义串口的通信模式,从串口对象属性也能了解串口的状态。
要想通过串口传输数据,必须先用fopen函数打开串口;数据传输结束后要用fclose。
函数关闭串口。
表1列出了常用的与串口操作有关的函数。
表1Matlab串口函数介绍
_____________________________________________________
函数 说明
_____________________________________________________
serial创建一个串口对象,格式:
s=serial('coml')
fopen打开串口对象,格式:
fopen(s)
fread读取串口数据,格式:
fread(s)
fclose关闭串口对象,格式:
fclose(s)
free 解除Matlab对串口对象的控制,使
serial其他程序能对该串口进行读写操作
delete删除对象s,格式:
delete(s)
clear从工作空间中删除对象s,格式:
clear(s)
___________________________________________________
当建立了一个串口对象后,可以利用Matlab对其参数进行设置,包括对波特率、同步或异步读取方式、读取或写数据的等待时间等。
本文以波特率的设置为例来说明串口参数的设置方法。
波特率的设置,一般有两种方法:
(1)在创建串口对象时设定波特率:
s=serial(`coml','baudrate','9600');
(2)用set命令:
set(s,'baudrate','9600')。
matlab串口编程
2009年06月10日星期三下午11:
43
functionserialdwj
%本程序使用的是虚拟串口软件VSPD虚拟的COM2和COM3来测试的
%使用COM1也可以使用已经经过测试了
%如果要使用请使用COM1口就可以与下位机通信了
obj1=instrfind('Type','serial','Port','COM3','Tag','');
%COM2为测试串口
obj2=instrfind('Type','serial','Port','COM2','Tag','');
ifisempty(obj1)
obj1=serial('COM3');
%新建测试串口
obj2=serial('COM2');
else
fclose(obj1);
obj1=obj1
(1);
%打开串口
fclose(obj2);
obj2=obj2
(1);
end
set(obj1,'BaudRate',9600,'FlowControl','none','Timeout',0.1)
set(obj1,'Inputbuffersize',512,'Outputbuffersize',512,'parity','none','databits',8,'stopbits',1);
%COM2的属性设置
set(obj2,'BaudRate',9600,'FlowControl','none','Timeout',0.1)
set(obj2,'Inputbuffersize',512,'Outputbuffersize',512,'parity','none','databits',8,'stopbits',1);
fopen(obj1);
%打开串口
fopen(obj2);
k=1;
datas=zeros([1,100]);
while(k<101)
ifobj1.BytesAvailable
datas(1,k)=fread(obj1,1);
end
k=k+1;
plot(datas);
%向测试串口中写一个数据数据在COM3中就可以接受到该数据
fwrite(obj2,round(255*rand
(1)));
pause
(1);
end
fclose(obj1);
delete(obj1);
%删除测试串口
fclose(obj2);
delete(obj2);
end
%现在使用的m文件来显示的
%到后来有机会就使用gui界面来显示
MATLAB接收串口数据GUI界面
2009-09-1912:
42
工作流程:
AD7818采样模拟信号,12bits输出,串口将数据发送给PC。
串口发送波特率57600Bd,数据位8位,停止位一位。
每个数据分两次发送,高四位补零。
设计GUI界面接收串口数据并显示波形。
GUI界面如下:
功能描述:
1.选择串口,点击START,即等待串口发送数据,数据缓存4000bytes。
接收缓存区满后绘图,同时显示最大电压值和波形功率值。
2.File菜单下有ImportData和ExportData功能,可将电压数据保存到txt文件中,同时可读取txt中的数据并显示相关波形。
3.Image菜单下有OpenImage和SaveImage功能,可将波形保存成图片格式,同时可打开图片显示在绘图窗口。
Matlab源代码:
functionvarargout=serial1(varargin)
%SERIAL1M-fileforserial1.fig
% SERIAL1,byitself,createsanewSERIAL1orraisestheexisting
% singleton*.
%
% H=SERIAL1returnsthehandletoanewSERIAL1orthehandleto
% theexistingsingleton*.
%
% SERIAL1('CALLBACK',hObject,eventData,handles,...)callsthelocal
% functionnamedCALLBACKinSERIAL1.Mwiththegiveninputarguments.
%
% SERIAL1('Property','Value',...)createsanewSERIAL1orraisesthe
% existingsingleton*.Startingfromtheleft,propertyvaluepairsare
% appliedtotheGUIbeforeserial1_OpeningFcngetscalled.An
% unrecognizedpropertynameorinvalidvaluemakespropertyapplication
% stop.Allinputsarepassedtoserial1_OpeningFcnviavarargin.
%
% *SeeGUIOptionsonGUIDE'sToolsmenu.Choose"GUIallowsonlyone
% instancetorun(singleton)".
%
%Seealso:
GUIDE,GUIDATA,GUIHANDLES
%Edittheabovetexttomodifytheresponsetohelpserial1
%LastModifiedbyGUIDEv2.518-Sep-200913:
30:
08
%Begininitializationcode-DONOTEDIT
gui_Singleton=1;
gui_State=struct('gui_Name', mfilename,...
'gui_Singleton',gui_Singleton,...
'gui_OpeningFcn',@serial1_OpeningFcn,...
'gui_OutputFcn',@serial1_OutputFcn,...
'gui_LayoutFcn',[],...
'gui_Callback', []);
ifnargin&&ischar(varargin{1})
gui_State.gui_Callback=str2func(varargin{1});
end
ifnargout
[varargout{1:
nargout}]=gui_mainfcn(gui_State,varargin{:
});
else
gui_mainfcn(gui_State,varargin{:
});
end
%Endinitializationcode-DONOTEDIT
%globalsselected_comselected_baudselected_databitsselected_stopbitsselected_parityselected_flowctrl
%---Executesjustbeforeserial1ismadevisible.
functionserial1_OpeningFcn(hObject,eventdata,handles,varargin)
%Thisfunctionhasnooutputargs,seeOutputFcn.
%hObject handletofigure
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
%varargin commandlineargumentstoserial1(seeVARARGIN)
globals;
handles.mycom=s;
%Choosedefaultcommandlineoutputforserial1
handles.output=hObject;
%Updatehandlesstructure
guidata(hObject,handles);
%UIWAITmakesserial1waitforuserresponse(seeUIRESUME)
%uiwait(handles.figure1);
%---Outputsfromthisfunctionarereturnedtothecommandline.
functionvarargout=serial1_OutputFcn(hObject,eventdata,handles)
%varargoutcellarrayforreturningoutputargs(seeVARARGOUT);
%hObject handletofigure
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
%Getdefaultcommandlineoutputfromhandlesstructure
varargout{1}=handles.output;
%---Executesonselectionchangeinlistbox1.
functionlistbox1_Callback(hObject,eventdata,handles)
%hObject handletolistbox1(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
%Hints:
contents=get(hObject,'String')returnslistbox1contentsascellarray
% contents{get(hObject,'Value')}returnsselecteditemfromlistbox1
%---Executesduringobjectcreation,aftersettingallproperties.
functionlistbox1_CreateFcn(hObject,eventdata,handles)
%hObject handletolistbox1(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles empty-handlesnotcreateduntilafterallCreateFcnscalled
%Hint:
listboxcontrolsusuallyhaveawhitebackgroundonWindows.
% SeeISPCandCOMPUTER.
ifispc&&isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%---Executesonbuttonpressinpushbutton_start.
functionpushbutton_start_Callback(hObject,eventdata,handles)
%hObject handletopushbutton_start(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
globalvoltage;
power=0;
fopen(handles.mycom);
[data,count]=fread(handles.mycom);
fclose(handles.mycom);
fori=1:
1:
(count/2)
data_12bits(i)=data(2*i)*256+data(2*i-1);
voltage(i)=data_12bits(i)*5/4095;
time(i)=0.05*i;
power=power+(voltage(i)^2)*(time(i)*0.001)/900;
end
set(findobj(gcf,'Tag','edit_power'),'String',num2str(power));
set(handles.edit_voltage,'String',num2str(max(voltage)));
plot(handles.axes_waveform,time,voltage);
set(handles.text_time,'Visible','on');
set(handles.text_voltage,'Visible','on');
set(handles.pushbutton_clearfig,'Enable','on');
deletehandles.mycom;
%---Executesonselectionchangeinpopupmenu_com.
functionpopupmenu_com_Callback(hObject,eventdata,handles)
%hObject handletopopupmenu_com(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
%Hints:
contents=get(hObject,'String')returnspopupmenu_comcontentsascellarray
% contents{get(hObject,'Value')}returnsselecteditemfrompopupmenu_com
val=get(hObject,'Value');
switchval
case1
s=serial('COM1');
case2
s=serial('COM2');
case3
s=serial('COM3');
case4
s=serial('COM4');
case5
s=serial('COM5');
case6
s=serial('COM6');
end
set(s,'baudrate',57600,'databits',8,'stopbits',1,'parity','none','flowcontrol','none','InputBufferSize',4000);
set(handles.pushbutton_start,'Enable','On');
handles.mycom=s;
guidata(hObject,handles);
%---Executesduringobjectcreation,aftersettingallproperties.
functionpopupmenu_com_CreateFcn(hObject,eventdata,handles)
%hObject handletopopupmenu_com(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles empty-handlesnotcreateduntilafterallCreateFcnscalled
%Hint:
popupmenucontrolsusuallyhaveawhitebackgroundonWindows.
% SeeISPCandCOMPUTER.
ifispc&&isequal(get(hObject,'BackgroundColor'),get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%---IfEnable=='on',executesonmousepressin5pixelborder.
%---Otherwise,executesonmousepressin5pixelborderoroverpopupmenu_com.
functionpopupmenu_com_ButtonDownFcn(hObject,eventdata,handles)
%hObject handletopopupmenu_com(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
%--------------------------------------------------------------------
functionfile_Callback(hObject,eventdata,handles)
%hObject handletofile(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles structurewithhandlesanduserdata(seeGUIDATA)
%--------------------------------------------------------------------
functionimage_Callback(hObject,eventdata,handles)
%hObject handletoimage(seeGCBO)
%eventdatareserved-tobedefinedinafutureversionofMATLAB
%handles struc
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Matlab 串口 函数