Matlab串口函数
在MATLAB中使用串口

在MATLAB中使用串口首先,你需要了解有关串口的一些基本概念,例如波特率和数据位。
然后你需要确保你的计算机上有一个可用的串口。
接下来,你需要打开串口连接。
使用`serial`函数创建一个串口对象,如下所示:```matlabs = serial('COM1', 'BaudRate', 9600);```此代码将创建一个串口对象`s`,并指定使用COM1串口号,波特率为9600。
使用`fopen`函数打开串口连接:```matlabfopen(s);```现在你已经打开了一个串口连接。
接下来,你可以发送和接收数据。
使用`fwrite`函数向串口发送数据,例如:```matlabdata = 'Hello';fwrite(s, data);```此代码将向串口s发送字符串"Hello"。
使用`fread`函数从串口接收数据,例如:```matlabreceived = fread(s);```此代码将从串口s接收数据,并将其存储在变量`received`中。
最后,当你完成使用串口时,使用`fclose`函数关闭串口连接:```matlabfclose(s);```这是一个最简单的串口通信的示例。
当然,你还可以进行更多的配置,例如设置校验位或停止位等。
例如,如果你需要设置串口的数据位为8、停止位为1和没有校验位,可以使用以下代码:```matlabs = serial('COM1', 'BaudRate', 9600, 'DataBits', 8,'StopBits', 1, 'Parity', 'none');```。
MATLAB串口通信

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%本程序主要实现串口控制三轴转台进行自动标定,%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%查找串口对象,若串口一开始被占用,需要加上这段程序释放串口,若串口没有被占用,则不需要这段程序scoms = instrfind;%%尝试停止、关闭删除串口对象stopasync(scoms);fclose(scoms); %关闭串口delete(scoms); %释放串口%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%clear all;clc;%%%%%串口配置通道1global s;s = serial('COM13'); %设置串口号s.baudrate = 57600; %设置波特率s.parity = 'none'; %校验位s.stopbits = 1; %停止位s.databits = 7; %数据位s.timeout = 2; %一次读/写的时间最长为0.5ss.InputBufferSize = 1024; %输入缓冲区s.OutputBufferSize = 1024; %输出缓冲区% s.BytesAvailableFcnMode = 'byte'; %中断触发事件为'bytes-available event' % s.BytesAvailableFcnCount = 8; %接收缓冲区每收到n个字节时,触发回调函数% s.BytesAvailableFcn = {'cmd_rec_callback', handles};%得到回调函数句柄fopen(s); %%%%打开串口fclose(s);%%%%%串口配置通道2global s2;s2 = serial('COM15'); %设置串口号s2.baudrate = 460800; %设置波特率s2.parity = 'none'; %校验位s2.stopbits = 1; %停止位s2.databits = 8; %数据位s2.timeout = 2; %一次读/写的时间最长为0.5ss2.InputBufferSize = 1024; %输入缓冲区s2.OutputBufferSize = 1024; %输出缓冲区% s.BytesAvailableFcnMode = 'byte'; %中断触发事件为'bytes-available event' % s.BytesAvailableFcnCount = 8; %接收缓冲区每收到n个字节时,触发回调函数% s.BytesAvailableFcn = {'cmd_rec_callback', handles};%得到回调函数句柄fopen(s2); %%%%打开串口fclose(s2);% InitPos(1)=InitPos(1)+0.3% Pos1=num2str(InitPos(1)');% Pos1=['Q010',Pos1(1,:),'$'];% A=[0 0 0 0 0 0 0 0 0 0 0];% fwrite(s2,A,'uint8')% AA=fread(s2,11,'uint8')%%%%%%%定义变量,存放星点位置PosX=zeros(41,51);PosY=zeros(41,51);AllX=zeros(30,2091);AllY=zeros(30,2091);n=1;InitPos=[0.3 0.0000 93.4253];Flag=0;MouseX=1354;MouseY=376;LeftC=1;global filename4;global filename5;filename4=['D:\1-3\*.bmp' ];filename5=['D:\1-3\'];%%%%%%%三轴转台,自动标定for j=1:41fopen(s);for i=1:51%%%%%%%%%%%控制鼠标左键,采集图像PressMouse(MouseX,MouseY,LeftC);PressMouse(MouseX,MouseY,LeftC);pause(5); %等待整数秒%%%%%%%%%%%%%读取转台位置坐标,进行反馈控制fopen(s2);[Flag]=ReadCoor(s2,InitPos);fclose(s2);while (Flag==1)%%%%%%%%%%%%%删除上次存储的点的图片filename6=dir(filename4); %显示xxx目录下的文件和文件夹[~,index] = sortrows({filename6.date}.'); %index变址向量,重新排序前的地址filename6 = filename6(index);clear indexpath=[filename5]; %查看或者改变路径for k=(length(filename6)-29): length(filename6)A=[path filename6(k).name];delete(A);end%%%%%%%%%%%%%向内轴发定位命令,位置:12.3456?;ASC码:Q01012.3456$ ;16进制数:51H 30H 30H 31H 31H 32H 2EH 33H 34H 35H 36H 24HPos1=num2str(InitPos(1)');Pos1=['Q010',Pos1(1,:),'$'];fwrite(s,Pos1,'char')pause(2);%%%%%%%%%%%%%向中轴发定位命令,位置:12.3456?;ASC码:Q01112.3456$ ;16进制数:51H 30H 31H 31H 31H 32H 2EH 33H 34H 35H 36H 24HPos2=num2str(InitPos(2)');Pos2=['Q011',Pos2(1,:),'$'];fwrite(s,Pos2,'char');pause(2);%%%%%%%%%%%%%向外轴发定位命令,位置:12.3456?;ASC码:Q01212.3456$ ;16进制数:51H 30H 32H 31H 31H 32H 2EH 33H 34H 35H 36H 24HPos3=num2str(InitPos(3)');Pos3=['Q012',Pos3(1,:),'$'];fwrite(s,Pos2,'char');fclose(s);pause(2);%%%%%%%%%%%控制鼠标左键,采集图像PressMouse(MouseX,MouseY,LeftC);PressMouse(MouseX,MouseY,LeftC);pause(5); %等待整数秒% B=[0 12 34 56 0 0 0 0 0 0 0];% fwrite(s2,B,'uint8')fopen(s2);[Flag]=ReadCoor(s2,InitPos);fclose(s2);end%%%%%%%%%%中轴坐标位置一次-0.3°InitPos(2)=InitPos(2)-0.3;%%%%%%%%串口给转台发送命令,设定增量模式,中框增量-0.3°,ASC码:Q02 1 -0.3$ 16进制数:51 30 32 31 2D 30 2E 33 24fwrite(s,'Q021-0.3$','char');pause(3); %等待整数秒end%%%%%%%%%每个点找一张图存到新建文件夹filename=['D:\',num2str(j)]new_folder = filename; % new_folder 保存要创建的文件夹,是绝对路径+文件夹名称mkdir(new_folder); % mkdir()函数创建文件夹filename=dir(filename5);[~,index] = sortrows({filename.date}.'); %index变址向量,重新排序前的地址filename = filename(index);clear indexfor r=1:51k=30*(r-1)+1;path=[filename5];A0=imread([path filename(k).name]);imshow(A0);B=['D:\j\',num2str(r),'.bmp'];imwrite(A0,B,'bmp');endfwrite(s,'Q02115$','char');pause(5);%%%%%%%%%%计算星点坐标[x,y,x0,y0]=SigleStarPointCalibration(j, filename4 ,filename5);PosX(j,:)=x;PosY(j,:)=y;AllX(:,n*51-50)=x0;AllY(:,n*51-50)=y0;n=n+1;%%%%%%%%%%中轴坐标位置回到初始位置InitPos(2)=InitPos(2)+15.3;%%%%%%%%%%内轴坐标位置增量+0.3°InitPos(1)=InitPos(1)+0.3;if (InitPos(1)>360)InitPos(1)=InitPos(1)-360;end%%%%%%%%串口给转台发送命令,增量模式,内框增量-0.3°,ASC码:Q01 0 0.3$ 16进制数:51 30 32 30 30 2E 33 24fwrite(s,'Q0200.3$','char');pause(3); %等待整数秒fclose(s);end%%%%%%%关闭串口fclose(s);%查找串口对象scoms = instrfind;% 尝试停止、关闭删除串口对象stopasync(scoms);fclose(scoms); %关闭串口delete(scoms); %释放串口。
matlab之串口通信

matlab之串口通信matlab之串口通信串口通信,一般是指RS232、RS422之间的通信。
matlab中有专门的serial函数来创建串口对象。
设串口ID号为COM1,则创建方法为:复制内容到剪贴板代码:>>scom= serial('com1');创建完串口对象后,一般需要设置串口对象的属性,否则,串口不会相互通信。
复制内容到剪贴板代码:>> get(scom)ByteOrder = littleEndianBytesAvailable = 0BytesAvailableFcn =BytesAvailableFcnCount = 48BytesAvailableFcnMode = terminatorBytesToOutput = 0ErrorFcn =InputBufferSize = 512Name= Serial-COM1ObjectVisibility = onOutputBufferSize = 512OutputEmptyFcn =RecordDetail = compactRecordMode = overwriteRecordName = record.txtRecordStatus = offStatus = closedTag=Timeout = 10TimerFcn =TimerPeriod = 1TransferStatus = idleType= serialUserData = []ValuesReceived = 0ValuesSent = 0SERIAL specific properties:BaudRate= 9600BreakInterruptFcn =DataBits = 8DataTerminalReady = onFlowControl = noneParity = nonePinStatus = [1x1 struct]PinStatusFcn =Port= COM1ReadAsyncMode = continuousRequestToSend = offStopBits = 1Terminator = LF这些属性中,要使串口真正通信,一般要设置这几个属性:BaudRate:波特率;Parity:奇偶校验类型;DataBits:数据位,一般为8,不用设置;StopBits:停止位,一般为1,不用设置;TimerFcn :定时回调函数;TimerPeriod:定时周期;BytesAvailableFcn:字节计数回调函数BytesAvailableFcnCount:字节计数BytesAvailableFcnMode:一般设置为字节模式,即byte串口通信时,数据一般按帧传送,有的数据量比较大,会将帧打包后发送。
MATLAB与51单片机通信

桂电二院科协出品,版权所有,转载不究。
maswell_xiao@
程序的最后用 dat = fread(s)读取单片机给 MATLAB 发送的数据,显然 dat 的数据对应的 ASCALL 码正好是单片机程序里对应的‘has been received’
桂电二院科协出品,版权所有,转载不究。
以上三种格式等价,都可以设置串口 1 的波特率为 4800。
2. fopen 函数,打开串口对象,格式为
fileID = fopen(filename) fileID = fopen(filename, permission) fileID = fopen(filename, permission, machineformat) fileID = fopen(filename, permission, machineformat, encoding) [fileID, message] = fopen(filename, ...) fIDs = fopen('all') [filename, permission, machineformat, encoding] = fopen(fileID)
当使用 serial 函数创建一个串口对象而不用时要用该函数删除对象 s。这个与 fclose 不 同的是,fclose 仅仅是关闭串口对象暂时不用,delete 函数是直接删除,若使用 delete 函数删除对象还想再用时就要用 serial 函数重新创建串口对象用 fopen 打开对象。而 fclose 不用再创建对象。当使用 MATLAB 占用串口时,其他软件不能使用该串口,如串 口小助手。
在串口中可以这样用 clear(s)。clear 函数从工作空间删除变量,并释放系统内存。
LabWindowsCVI串口通信函数

LabWindows/CVI串口通信函数LabWindows/CVI提供的RS-232函数库主要包括以下几类函数:串行口打开/关闭 (Open/Close)函数,串行口输入/输出(Input/Output)函数,串行口控制(Control)函数,串行口状态查询(Status)函数和串行口事件处理(Callbacks)函数。
下面分别予以介绍。
1.串行口打开/关闭函数1)OpenCom函数功能:表示以默认的参数设置方式打开一个串口。
该函数原型为:int OpenCom (int COM_Port,char Device_Name[ ] )其中,参数COM_Port为整型变量,用于指定串口号,有效范围为1~1000;Device_Name[]为字符型数组,是用ASCⅡ码字符串表示的串口名。
2)OpenComConfig函数功能:用来打开一个串行口并进行相关的参数设置。
该函数原型为:int OpenComConfig(int COM_Port,char Device_Name[],long Baud_Rate,int Parity,int Data_Bits,int Stop_Bits,int Input_Queue_Size,int Output_Queue_Size)其中,参数COM_Port为整型变量,用于指定串口号,有效范围为1~1000;Device_Name[]为字符型数组,是用ASCⅡ码字符串表示的串口名。
例如,以“COM1”来代替端口1,如果输入值为NULL或一个空字符串,则以COM_Port号作为指定端口号。
Baud_Rate为长整型变量,用来设置串行口的传输速率,标准的传输速率有110、300、600、1200、2400、4800、9600、19200b/s等;默认值为9600。
Parity为整型变量,用来指定奇偶校验模式。
0表示无奇偶校验,1表示奇校验,2表示偶校验;Data_Bits为整型变量,用来指定每帧信息中数据位的个数,可选5、6、7、8;Stop_Bits为整型变量,用来指定每帧信息中停止位的个数,可选1、1.5或2;Input_Queue_Size为整型变量,用来指定串行口输入队列的大小;Output_Queue_Size为整型变量,用来指定串行口输出队列的大小。
Matlab中的串口通信与硬件控制

Matlab中的串口通信与硬件控制在科学与工程领域,与硬件设备的通信和控制是一个非常重要的环节。
例如,根据传感器的读数来控制机器人的运动、通过串口与测量仪器进行数据交互等等。
Matlab作为一种功能强大的数学软件,提供了强大的串口通信与硬件控制功能,能够帮助工程师和科学家们简化开发流程并降低开发难度。
一、串口通信基础串口通信是一种实现设备之间数据传输的常见方式。
在Matlab中,我们可以通过Serial对象来实现与串口设备的通信。
首先,需要了解一下串口通信的基本概念。
1. 波特率(Baud Rate)波特率是指每秒传输的比特数。
它决定了数据传输的速率。
在串口通信中,发送端和接收端的波特率必须保持一致,否则数据会出现错误。
2. 数据位(Data Bits)数据位是指每个字符中实际的数据位数。
常见的数据位数有5位、6位、7位和8位。
一般来说,数据位较多可以提供更高的数据传输精度。
3. 校验位(Parity Bit)校验位是一种用于检测数据传输错误的方法。
它可以用于检验数据位中有效数据的奇偶性,常见的校验位有None、Even和Odd三种模式。
4. 停止位(Stop Bit)停止位是指每个字符的结束位数。
常见的停止位有1位和2位,通常使用1位即可。
二、Matlab中的串口通信Matlab提供了Serial对象来实现与串口设备的通信。
首先,我们需要创建一个Serial对象,并设置合适的串口参数。
例如,我们可以使用如下代码创建一个Serial对象:```matlabs = serial('COM1'); % 创建一个Serial对象,指定串口为COM1set(s, 'BaudRate', 9600); % 设置波特率为9600set(s, 'DataBits', 8); % 设置数据位为8位set(s, 'Parity', 'None'); % 设置校验位为Noneset(s, 'StopBits', 1); % 设置停止位为1位```接下来,我们可以打开Serial对象并开始串口通信:```matlabfopen(s); % 打开Serial对象```可以使用`fwrite`函数向串口写入数据,使用`fread`函数从串口读取数据。
matlab串口

PC机接收单片机传来数据:
2
scom=serial('COM1'); %串口com1
scom.BaudRate = 9600; %波特率
scom.InputBufferSize = 1024; %输入缓冲区
scom.OutputBufferSize = 1024; %输出缓冲区
scom.BytesAvailableFcn = @instrcallback; %调用回调函数
当缓冲区中的数据达到100 bytes时调用instrcallback回调函数。instrcallback.m在MATLAB7\toolbox\matlab\iofun\@instrument目录下面,尽量不要改动原来的内容,在末尾添加当缓冲区有指定量的数据时需要MATLAB做的工作,比如绘图,数据保存之类的。
比如我要通信串口的波特率为4800:
s=serial('com1');
fopen(s)
s.baudrate=4800;
fwrite(s,[48 59]); %向com1口发送两个数据48和59
fread(s,4); %从串行口读入四个数据
4
val = [170 180 val 85];
scom.ReadAsyncMode = 'continuous'; %异步通信时,连续读串口数据
使用MATLAB进行串口调试的两种方法

使用MATLAB进行串口调试的两种方法方法1:在command window界面下输入tmtool,打开Test & Measurement Tool窗口,在Hardware→Serial下面找到已连接的串口设备(单片机开发板通过USB转串口,对应COM2),在communicate选项卡中对串口进行设置即可。
需要注意的是,程序功能是上位机发送16bit字符串,单片机通过串口接收并回显给上位机,这16bit的字符串是不包含字符串结束标志\n的,因此在sending data下面的data format下拉菜单中,要选择%s而不是%s\n。
为了使接收字符串的时间变短,可以在configure选项卡中将timeout选项设置为1.0。
方法2:直接在command window环境下用matlab提供的函数对串口进行操作,仍然以COM2为例。
在command window环境下依次输入以下代码:
s=serial('COM2') %将串口2赋给s
s.status %查看串口2的状态
fopen(s) %打开串口2
s.status
fprintf(s,'987654321abcdef') %给串口2的发送缓存写入数据987654321abcdef fscanf(s) %从串口2的接收缓存读数据
fclose(s) %关闭串口2
s.status
delete(s)
clear s
每一个语句的执行情况如下图所示:
其中需要注意的是fprintf()函数默认采用%s\n格式,因此在这里只能输入15个字符,系统会在15bit字符串的末尾自动添加字符串结束标志\n,该标志不能在数码管上显示。
matlab函数编程步骤串口编程的一般步骤及相关函数讲解

matlab函数编程步骤串⼝编程的⼀般步骤及相关函数讲解matlab函数编程步骤串⼝编程的⼀般步骤及相关函数讲解⽤Windows API进⾏串⼝编程的⼀般步骤及相关函数讲解------分隔线---------------------------- 虽然使⽤诸如CSerialPort VC串⼝类,MSComm VC 串⼝控件等⾮常⽅便,但有时这些控件并不适合⾃⼰的特殊需求,所以有必要了解⼀下基于Windows API的串⼝编程⽅法,下⾯介绍⼀下API串⼝编程的⼀般步骤及相关串⼝API函数。
串⼝操作⼀般有四步,分别是:1) 打开串⼝2) 配置串⼝3) 读写串⼝4) 关闭串⼝1、打开串⼝在《VC 打开串⼝》⼀⽂中我们已经单独介绍过如果利⽤API打开串⼝的⽅法,打开串⼝是⽤API函数CreateFile来打开或创建的。
该函数的原型为:1HANDLE CreateFile( LPCTSTR lpFileName, 2 DWORD dwDesiredAccess, 3 DWORD dwShareMode, 4 LPSECURITY_ATTRIBUTES lpSecurityAttributes, 5 DWORD dwCreationDistribution,6DWORD dwFlagsAndAttributes, 7HANDLE hT emplateFile); 参数详解:lpFileName:将要打开的串⼝逻辑名,如“COM1”;dwDesiredAccess:指定串⼝访问的类型,可以是读取、写⼊或⼆者并列;dwShareMode:指定共享属性,由于串⼝不能共享,该参数必须置为0;lpSecurityAttributes:引⽤安全性属性结构,缺省值为NULL;dwCreationDistribution:创建标志,对串⼝操作该参数必须置为OPEN_EXISTING;dwFlagsAndAttributes:属性描述,⽤于指定该串⼝是否进⾏异步操作,该值为FILE_FLAG_OVERLAPPED,表⽰使⽤异步的I/O;该值为0,表⽰同步I/O操作;hT emplateFile:对串⼝⽽⾔该参数必须置为NULL;串⼝的操作可以有两种操作⽅式:同步操作⽅式和重叠操作⽅式(也称为异步操作⽅式)。
基于Matlab-GUI的串口通信编程实现

0 引言Matlab是MathWorks公司开发的一种科学计算软件。
Matlab运行稳定、可靠、使用方便,是广大科研人员进行科学研究的得力助手。
Matlab不仅具有强大的科学计算功能,还具有满足一般要求的数据采集以及界面设计开发功能。
Matlab GUI(Graphic User Interface)就是内置于Matlab的进行图形界面开发的模块。
本文利用Matlab GUI设计通过串口进行数据发送和接收的界面,并利用内置于Matlab的串口通信API实现串口数据发送与接收功能。
1 Matlab GUl介绍启动Matlab后,运行guide命令即可以启动Matlab GUI开发工具。
如图1所示。
新建Blank GUI,如图2所示。
在新建Blank GUI界面中,包含了一般的界面元素,如菜单、按钮、坐标轴、控件等。
添加必要的串口通信参数设置按钮。
运行后的界面如图3所示。
2 串口数据发送与接收功能实现2.1 建立串口通信流程的基本步骤Matlab提供了对串口进行打开、关闭、以及串口参数设置等操作的一系列函数。
利用这些函数可以选择串口号、设置串口通信参数(波特率、数据位、停止位、校验位等)、进行中断控制、流控制。
从建立串口通信到结束串口通信的完整流程包括以下几个步骤:(1)为应用程序创建串口对象。
实现该功能的函数为:其中参数port为完整的串口名称,如cornl。
PropertyName为串口通信参数,如baudrate,startbits等。
创建串口对象的过程中,也可以忽略PropertyName。
其函数为:(2)连接打开串口。
实现该功能的函数为:obj即为使用创建串口对象函数的返回值。
在连接打开串口后,可以对串口通信参数进行修改。
(3)设置或者修改串口通信参数。
在能够有效地进行串口通信前,必须设置正确的串口通信参数。
实现该功能的函数为:obj即为使用创建串口对象函数的返回值;PropertyName为串口通信参数,如baudrate,startbits等。
matlab串口读取函数

matlab串口读取函数
在MATLAB中,读取串口数据可以使用`serial`对象和`read`函数。
以下是一个简单的示例,展示如何创建一个串口连接,并从串口读取数据:
1. 首先,确保您已经安装了MATLAB的串口工具箱。
如果没有,您可以使用以下命令安装:
```matlab
install_toolbox(' CommunicationsToolbox', 'SerialPort')
```
2. 创建一个串口连接。
这里,我们设定串口地址为COM1,波特率为9600,数据位为8,停止位为1,奇偶校验位为无:
```matlab
serialPort = serial('COM1', '9600', 8, 'ones', 'No');
```
3. 打开串口:
```matlab
serialPort.Open();
```
4. 从串口读取数据。
假设我们要读取10个字节:
```matlab
data = serialPort.Read(10);
```
5. 关闭串口:
```matlab
serialPort.Close();
```
6. 显示读取到的数据:
```matlab
disp(data);
```
以上就是一个简单的MATLAB读取串口数据的示例。
根据实际需求,您可能需要根据实际情况调整串口参数和读取数据的大小。
在实际应用中,还可能需要处理错误和异常情况。
LabWindowsCVI串口通信函数

L a b W i n d o w s C V I串口通信函数标准化工作室编码[XX968T-XX89628-XJ668-XT689N]L a b W i n d o w s/C V I串口通信函数LabWindows/CVI提供的RS-232函数库主要包括以下几类函数:串行口打开/关闭(Open/Close)函数,串行口输入/输出(Input/Output)函数,串行口控制(Control)函数,串行口状态查询(Status)函数和串行口事件处理(Callbacks)函数。
下面分别予以介绍。
1.串行口打开/关闭函数1)OpenCom函数功能:表示以默认的参数设置方式打开一个串口。
该函数原型为:intOpenCom(intCOM_Port,charDevice_Name[])其中,参数COM_Port为整型变量,用于指定串口号,有效范围为1~1000;Device_Name[]为字符型数组,是用ASCⅡ码字符串表示的串口名。
2)OpenComConfig函数功能:用来打开一个串行口并进行相关的参数设置。
该函数原型为:intOpenComConfig(intCOM_Port,charDevice_Name[],longBaud_Rate,intP arity,intData_Bits,intStop_Bits,intInput_Queue_Size,intOutput_Queue_S ize)其中,参数COM_Port为整型变量,用于指定串口号,有效范围为1~1000;Device_Name[]为字符型数组,是用ASCⅡ码字符串表示的串口名。
例如,以“COM1”来代替端口1,如果输入值为NULL或一个空字符串,则以COM_Port 号作为指定端口号。
Baud_Rate为长整型变量,用来设置串行口的传输速率,标准的传输速率有110、300、600、1200、2400、4800、9600、19200b/s等;默认值为9600。
在MATLAB中使用串口

在MATLAB中使用串口3.2.1MATLAB对RS232的串口通信设计MATLAB是一个跨平台软件,而此处使用的是自主设计的数据采集卡,因此不具备直接访问的能力。
但MATLAB的面向对象技术,已用一个对象把计算机串口封装起来,只要用Serial函数创建串口对象即可[6]。
关键语句为:s=ser ial(‘COM1’,‘BaudRate’,9600)。
MATLAB封装的串口对象支持对串口的异步读写操作,通过对异步读写设置,PC在执行读写串口函数时能立即返回,不必等待串口把数据串输完毕。
当指定数据传输结束时就触发事件,执行事件回调函数,对事件回调函数编程,进行数据处理,这样可以大大提高数据处理的效率。
MEX是MATLAB的可执行程序,是MATLAB调用其它语言编写的程序或算法的接口,在Windows环境下是扩展名为DLL的动态链接库。
对MEX编译器进行配置的方法是:在MATLAB命令窗口中运行mex-setup,选择VC6.0++作为编译器。
用C语言编写端口读、写的操作程序,程序包含有头文件mex.h和m exFunction函数,mexFunction函数中nelhs表示输出变量的个数,plhs包含指向输出变量指针的数组,nrhs表示输入变量的个数,prhs包含指向输入变量指针的数组。
接口编形成的MEX文件与参考文献[7][8]类似,在此不再累述。
3.2.2数据采集与分析(1)数据读取的MATLAB实现主要代码为:%读取通道数及总数据量fid=fopen(‘cardiogram.add’,‘r’);Status=fseek(fid,56,‘bof’);nDataChNum=fread(fid,1,‘long’);status=fseek(fid,204,‘bof’);nAllDataLength=fread(fid,1,‘long’);%按通道数循环读出各通道起始地址status=fseek(fid,76,‘bof’);%for i="1:"nDataChNumpChannelAdr(i)=fread(fid,1,‘long’)end%按通道数循环读出各通道数据for i="1:nDataChNum"status=fseek(fid,pChannelAdr(i)+360,‘bof’)nSegNum=fread(fid,1,‘log’)status=fseek(fid,pChannelAdr(i)+160*nSegNum+1024,‘bof’);data=fread(fid,nAllDataLength,‘short’);endsta=fclose(fid);(2)数据处理与图形绘制利用MATLAB的图形用户接口,通过编程可以很方便地构建数据采集与分析的用户交互界面。
matlab 串口协议解析

matlab 串口协议解析Matlab 是一种功能强大的数值计算和数据可视化工具,它还提供了与外部设备进行通信的功能。
其中,串口通信是一种常见的通信方式,它通过串行通信接口(Serial Port)将计算机与外部设备连接起来。
本文将介绍如何使用Matlab 进行串口协议解析,包括如何配置串口参数、如何发送和接收数据以及如何解析接收到的数据。
需要在 Matlab 中配置串口参数。
可以通过 `serial` 函数创建一个串口对象,并使用 `set` 函数设置串口的各项参数,如波特率、数据位、停止位等。
波特率是串口通信中用于衡量数据传输速率的重要参数,它需要与外部设备的串口参数保持一致。
数据位和停止位则决定了每个数据字节的位数和数据的结束方式。
除此之外,还可以设置奇偶校验位、流控制等参数,以适应不同的通信需求。
配置好串口参数后,可以使用`fopen` 函数打开串口并建立与外部设备的连接。
然后,可以使用`fwrite` 函数向外部设备发送数据。
在发送数据之前,需要将待发送的数据按照协议要求进行封装,以保证数据的可靠传输。
封装的方式可以根据具体的协议要求进行设计,可以是固定长度的数据包,也可以是带有校验位的数据帧。
在封装数据时,需要注意字节顺序和数据类型的转换,以确保数据的正确性和可解析性。
外部设备接收到数据后,可以通过 `fread` 函数从串口缓冲区中读取数据。
读取到的数据是一个字节数组,需要根据协议要求进行解析。
解析过程中,需要注意字节顺序和数据类型的转换,以及数据的截取和组合。
可以使用Matlab 中的位操作函数和类型转换函数,如`bitget`、`bitshift`、`typecast` 等,来处理和转换数据。
解析完成后,可以对接收到的数据进行进一步的处理和分析。
可以根据数据的含义和格式进行特定的操作,如计算数据的平均值、最大值、最小值等;可以将数据可视化,如绘制曲线图、柱状图等;还可以将数据保存到文件中,以备后续分析和处理。
MATLAB串口相关函数

概要serial 创建一个串口对象,格式:s = serial('coml' )fopen 打开串口对象,格式:fope n( s)fread 读取串口数据,格式: fread(s)fclose 关闭串口对象,格式:fclose(s)free 解除Matlab对串口对象的控制,使serial 其他程序能对该串口进行读写操作delete 删除对象s,格式:delete( s)clear 从工作空间中删除对象s,格式:clear(s)fopenOpen file, or obtain information about open filesSyntaxfileID = fopen(filename)fileID = fopen(filename, permission)fileID = fopen(filename, permission, machineformat)fileID = fopen(filename, permission, machineformat, encoding) [fileID, message] = fopen(filename, ...)fIDs = fopen('all')[filename, permission, machineformat, encoding] = fopen(fileID) DescriptionfileID = fopen(filename) opens the file filename for read access, and returns an integer file identifier.fileID = fopen(filename, permission) opens the file with the specified permission.fileID= fopen(filename, permission, machineformat) specifies the order for reading or writing bytes or bits in the file.fileID= fopen(filename, permission, machineformat, encoding) specifies the character encoding scheme associated with the file.[fileID, message] = fopen(filename, ...) opens a file. If the operation fails, message is a system-dependent error message. Otherwise, message is an empty string.fIDs= fopen('all') returns a row vector containing the file identifiers of all open files.[filename, permission, machineformat, encoding] = fopen(fileID) returns the file name, permission, machine format, and encoding that a previous call to fopen used when it opened the specified file. fopen does not read information from the file to determine these output values. An invalid fileID returns empty strings for all output arguments.Input Argumentsfilename String in single quotation marks that specifies thename of the file to open. Can include a full or partialpath.On UNIX systems, if filename begins with '~/' or'~username/', the fopen function expands the path tothe current or specified user's home directory,respectively.If you open a file with read access and fopen cannotfind filename in the current folder, fopen searchesalong the MATLAB search path. Otherwise, fopencreates a file in the current directory.permission String that describes the type of access for the file:read, write, append, or update. Also specifieswhether to open files in binary or text mode.To open files in binary mode, specify one of thefollowing:'r' Open file for reading (default).'w' Open or create new file for writing. Discardexisting contents, if any.'a' Open or create new file for writing. Append datato the end of the file.'r+' Open file for reading and writing.'w+' Open or create new file for reading and writing.Discard existing contents, if any.'a+' Open or create new file for reading and writing.Append data to the end of the file.'A' Append without automatic flushing. (Used withtape drives.)'W' Write without automatic flushing. (Used withtape drives.)To read and write to the same file:∙Open the file in update mode (with a permissionthat includes a plus sign, '+').∙Call fseek or frewind between read and writeoperations. For example, do not call freadfollowed by fwrite, or fwrite followed byfread, unless you call fseek or frewind betweenthem.To open files in text mode, attach the letter 't' tothe permission, such as 'rt' or 'wt+'. For betterperformance, do not use text mode. The followingapplies on Windows systems, in text mode:∙Read operations that encounter a carriagereturn followed by a newline character ('\r\n')remove the carriage return from the input.∙Write operations insert a carriage returnbefore any newline character in the output.This additional processing is unnecessary for mostcases. All MATLAB import functions, and most texteditors (including Microsoft Word and WordPad),recognize both '\r\n' and '\n' as newline sequences.However, when you create files for use in MicrosoftNotepad, end each line with '\r\n'. For an example,see fprintf.machineformat String that specifies the order for reading or writingbytes or bits in the file. Specify machineformat to:∙Read a file created on a different system.∙Read bits in a particular order.∙Create a file for use on a different system.Possible values are:'n' or 'native' The byte ordering that your systemuses (default)'b' or 'ieee-be' Big-endian ordering'l' or 'ieee-le' Little-endian ordering's' or'ieee-be.l64' Big-endian ordering, 64-bit data type'a' or'ieee-le.l64' Little-endian ordering, 64-bit data typeWindows systems use little-endian ordering, and mostUNIX systems use big-endian ordering, for both bytesand bits.encoding String that specifies the character encoding schemeto use for subsequent read and write operations,including fscanf, fprintf, fgetl, fgets, fread, andfwrite.Supported values are:'Big5' 'ISO-8859-1' 'windows-932''EUC-JP' 'ISO-8859-2' 'windows-936''GBK' 'ISO-8859-3' 'windows-949''Macintosh' 'ISO-8859-4' 'windows-950''Shift_JIS' 'ISO-8859-9' 'windows-1250''US-ASCII' 'ISO-8859-13' 'windows-1251''UTF-8' 'ISO-8859-15' 'windows-1252''windows-1253''windows-1254''windows-1257'For a list of additional encoding character sets, see/assignments/character-sets. Ifyou specify a value for encoding that is not in thelist of supported values, MATLAB issues a warning.Specifying other encodings sometimes (but not always)produces correct results.Default: system-dependentOutput ArgumentsfileID An integer that identifies the file for all subsequentlow-level file I/O operations. If fopen cannot openthe file, fileID is -1.MATLAB reserves file identifiers 0, 1, and 2 forstandard input, standard output (the screen), andstandard error, respectively. When fopensuccessfully opens a file, it returns a fileidentifier greater than or equal to 3.message A system-dependent error message when fopen cannotopen the specified file. Otherwise, an empty string.fIDs Row vector containing the identifiers for all openfiles, except the identifiers reserved for standardinput, output, and error. The number of elements inthe vector is equal to the number of open files. filename Name of the file associated with the specified fileID. permission The permission that fopen assigned to the filespecified by fileID.machineformat The value of machineformat that fopen used when itopened the file specified by fileID.encoding The character encoding scheme that fopen associatedwith the file specified by fileID.The value that fopen returns for encoding is astandard character encoding scheme name. It is notalways the same as the encoding argument that you usedin the call to fopen to open the file. ExamplesOpen a file. Pass the file identifier, fid, to other file I/O functions to read data and close the file.fid = fopen('fgetl.m');tline = fgetl(fid);while ischar(tline)disp(tline);tline = fgetl(fid);endfclose(fid);Create a prompt to request the name of a file to open. If fopen cannot open the file, display the relevant error message.fid = -1;msg = '';while fid < 0disp(msg);filename = input('Open file: ', 's');[fid,msg] = fopen(filename);endOpen a file to write Unicode® characters to a file using the Shift-JIS character encoding scheme:fid = fopen('japanese_out.txt', 'w', 'n', 'Shift_JIS');serialCreate serial port objectSyntaxobj = serial('port')obj = serial('port','PropertyName',PropertyValue,...) Descriptionobj = serial('port') creates a serial port object associated with the serial port specified by port. If port does not exist, or if it is in use, you will not be able to connect the serial port object to the device.Port object name will depend upon the platform that the serial port is on. instrhwinfo ('serial') provides a list of available serial ports. This list is an example of serial constructors on different platforms:obj = serial('port','PropertyName',PropertyValue,...) creates a serial port object with the specified property names and property values. If an invalid property name or property value is specified, an error is returned and the serial port object is not created.TipsWhen you create a serial port object, these property values are automatically configured:∙The Type property is given by serial.∙The Name property is given by concatenating Serial with the port specified in the serial function.∙The Port property is given by the port specified in the serial function.You can specify the property names and property values using any format supported by the set function. For example, you can use property name/property value cell array pairs. Additionally, you can specify property names without regard to case, and you can make use of property name completion. For example, the following commands are all valid on a Windows platform.s = serial('COM1','BaudRate',4800);s = serial('COM1','baudrate',4800);s = serial('COM1','BAUD',4800);Refer to Configuring Property Values for a list of serial port object properties that you can use with serial.Before you can communicate with the device, it must be connected to obj with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt a read or write operation while the object is not connected to the device. You can connect only one serial port object to a given serial port.ExamplesThis example creates the serial port object s1 associated with the serial port COM1 on a Windows platform.s1 = serial('COM1');The Type, Name, and Port properties are automatically configured.get(s1,{'Type','Name','Port'})ans ='serial' 'Serial-COM1' 'COM1'To specify properties during object creations2 = serial('COM2','BaudRate',1200,'DataBits',7);freadRead data from binary fileSyntaxA = fread(fileID)A = fread(fileID, sizeA)A = fread(fileID, sizeA, precision)A = fread(fileID, sizeA, precision, skip)A = fread(fileID, sizeA, precision, skip, machineformat)[A, count] = fread(...)DescriptionA = fread(fileID) reads data from a binary file into column vector A and positions the file pointer at the end-of-file marker.A = fread(fileID, sizeA) reads sizeA elements into A and positions the file pointer after the last element read. sizeA can be an integer, or can have the form [m,n].A = fread(fileID, sizeA, precision) interprets values in the file according to the form and size described by the precision. The sizeA parameter is optional.A= fread(fileID, sizeA, precision, skip) skips skip bytes after reading each value. If precision is bit n or ubit n, specify skip in bits. The sizeA parameter is optional.A= fread(fileID, sizeA, precision, skip, machineformat) reads data with the specified machineformat. The sizeA and skip parameters are optional.[A, count] = fread(...) returns the number of elements fread reads into A.Input ArgumentsfileID An integer file identifier obtained from fopen.sizeA Dimensions of the output array A. Specify in one ofthe following forms:inf Column vector with the number of elements inthe file. (default)n Column vector with n elements. If the file hasfewer than n elements, fread pads A with zeros.[m,n] m-by-n matrix, filled in column order. If thefile has fewer than m*n elements, fread padsA with zeros. n can be inf, but m cannot.precision String that specifies the form and size of the valuesto read. Optionally includes the class for the outputmatrix A.Use one of the following forms:'source' Specifies class of input values.Output matrix A is class double.Example: 'int16''source=>output' Specifies classes of input andoutput.Example: 'int8=>char''*source' Output has the same class asinput.Example: '*uint8'For 'bit n' or 'ubit n'precisions, output has thesmallest class that can containthe input.Example: '*ubit18' isequivalent to 'ubit18=>uint32''N*source' OR'N*source=>output' Valid if you specify a skip parameter. Read N values before each skip.Example: '4*int8'The following table shows possible values for source and output.long and ulong are 32 bits on 32-bit systems, and 64bits on 64-bit systems.For most source precisions, if fread reaches the endof the file before reading a complete element, freaddoes not return a value for the final element.However, if source is bit n or ubit n, then freadreturns a partial result for the final element.Default: 'uint8=>double'skip Number of bytes to skip after reading each value. Ifyou specify a precision of bit n or ubit n, specify skipin bits. Use this parameter to read data fromnoncontiguous fields in fixed-length records.Default: 0machineformat String that specifies the order for reading byteswithin the file. For bit n and ubit n precisions,specifies the order for reading bits within a byte.Specify machineformat to read and write to the fileon different systems, or to read parts of a byte ina specific order.Possible values are:'n' or 'native' The byte ordering that your systemuses (default)'b' or 'ieee-be' Big-endian ordering'l' or 'ieee-le' Little-endian ordering's' or'ieee-be.l64' Big-endian ordering, 64-bit data type'a' or'ieee-le.l64' Little-endian ordering, 64-bit data typeWindows systems use little-endian ordering, and mostUNIX systems use big-endian ordering, for both bytesand bits.Output ArgumentsA A column vector, unless you specify sizeA with theform [m,n]. Data in A is class double unless youspecify a different class in the precision argument. count The number of elements that fread successfully reads.ExamplesRead the contents of a file:% Create the filefid = fopen('magic5.bin', 'w');fwrite(fid, magic(5));fclose(fid);% Read the contents back into an arrayfid = fopen('magic5.bin');m5 = fread(fid, [5, 5], '*uint8');fclose(fid);Simulate the type function with fread, to display the contents of a text file:fid = fopen('fread.m');% read the entire file as characters% transpose so that F is a row vectorF = fread(fid, '*char')'fclose(fid);If you do not specify the precision, fread applies the defaultuint8=>double:fid = fopen('fread.m');F_nums = fread(fid, 6)' % read the first 6 bytes('%FREAD')fclose(fid);This code returnsF_nums =37 70 82 69 65 68Read selected rows or columns from a file:% Create a file with values from 1 to 9fid = fopen('nine.bin', 'w');alldata = reshape([1:9],3,3);fwrite(fid, alldata);fclose(fid);% Read the first six values into two columnsfid = fopen('nine.bin');two_cols = fread(fid, [3, 2]);% Return to the beginning of the filefrewind(fid);% Read two values at a time, skip one% Returns six values into two rows% (first two rows of 'alldata')two_rows = fread(fid, [2, 3], '2*uint8', 1);% Close the filefclose(fid);Specify machineformat to read separate digits of binary coded decimal (BCD) values correctly:% Create a file with BCD valuesstr = ['AB'; 'CD'; 'EF'; 'FA'];fid = fopen('bcd.bin', 'w');fwrite(fid, hex2dec(str), 'ubit8');fclose(fid);% If you read one byte at a time,% no need to specify machine formatfid = fopen('bcd.bin');onebyte = fread(fid, 4, '*ubit8');disp('Correct data, read with ubit8:')disp(dec2hex(onebyte))% However, if you read 4 bits on a little-endian% system, your results appear in the wrong order frewind(fid); % return to beginning of filepart_err = fread(fid, 8, '*ubit4');disp('Incorrect data on little-endian systems, ubit4:') disp(dec2hex(part_err))% Specify a big-endian format for correct results frewind(fid);part_corr = fread(fid, 8, '*ubit4', 'ieee-be');disp('Correct result, ubit4:')disp(dec2hex(part_corr))fclose(fid);fcloseClose one or all open filesSyntaxfclose(fileID)fclose('all')status = fclose(...)Descriptionfclose(fileID) closes an open file. fileID is an integer file identifier obtained from fopen.fclose('all') closes all open files.status = fclose(...) returns a status of 0 when the close operation is successful. Otherwise, it returns -1.MATLAB File Help: free Default Topicsfree--- help for xregpointer/free ---free Frees heap which p points tofree(P) releases the memory that P is pointint to. Note that freeptr is called on as a destructor.deleteRemove files or graphics objectsAlternativesAs an alternative to the delete function, use the Current Folder browser. Syntaxdelete('fileName1', 'filename2', ...)delete(h)delete(handle_array)delete fileNameDescriptiondelete('fileName1', 'filename2', ...) deletes the files fileName1, fileName2, and so on, from the disk. fileName is a string and can be an absolute path or a path relative to the current folder. fileName also can include wildcards (*).delete(h) deletes the graphics object with handle h. h can also be a vector or matrix of handles. Delete multiple objects by appending their handles as additional arguments, separated by commas. The function deletes objects without requesting verification, even if when they are windows.delete(handle_array) is a method of the handle class. It removes from memory the handle objects referenced by handle_array.When deleted, any references to the objects in handle_array become invalid. To remove the handle variables, use the clear function.delete fileName is the command syntax. Delete multiple files by appending filenames, separated by spaces. When filenames contain space characters, you must use the functional form.As delete does not ask for confirmation, to avoid accidentally losing files or graphics objects, make sure to specify accurately the items to delete. To move files to a different location when running delete, use the General preference for Deleting files, or the recycle function.The delete function deletes files and graphics objects only. To delete folders, use rmdir.ExamplesDelete all files with a .mat extension in the ../mytests/ folder:delete('../mytests/*.mat')Create a figure and an axes, and then delete the axes:hf = figure, ha = axeshf =1ha =170.0332delete(ha)The axes is deleted, but the figure remain. The axes handle ha remains in the workspace but no longer points to an object.clearRemove items from workspace, freeing up system memorySyntaxclearclear nameclear name1 name2 name3 ...clear global nameclear -regexp expr1 expr2 ...clear global -regexp expr1 expr2 ...clear keywordclear('name1','name2','name3',...)Descriptionclear removes all variables from the workspace, releasing them from system memory.clear name removes just the code file (function or script) or MEX-file function or variable name from your base workspace. If called from a function or script, clear name removes name from the workspace of just that function or script. You can use wildcards (*) to remove items selectively. For example, clear my* removes any variables whose namesbegin with the string my. Clearing removes debugging breakpoints in code files and, when called from within a function with persistent variables, reinitializes the persistent variables. If name is global, clear removes it from the current workspace, but it remains accessible to any functions declaring it global. If name has been locked by mlock, it remains in memory.Use a partial path to distinguish between different overloaded versions of a function. For example, clear polynom/display clears only the display method for polynom objects, leaving any other implementations in memory.clear name1 name2 name3 ... removes name1, name2, and name3 from the workspace.clear global name removes the global variable name. If name is global, clear name removes name from the current workspace, but leaves it accessible to any functions declaring it as global. Use clear global name to remove a global variable completely.clear -regexp expr1 expr2 ... clears all variables that match any of the regular expressions listed. This option only clears variables.clear global -regexp expr1 expr2 ... clears all global variables that match any of the regular expressions listed.clear keyword clears the items indicated by keyword. See the following section, Input Arguments, for a list of keywords and their descriptions.clear('name1','name2','name3',...) is the function form of the syntax. Use this form for variable names and function names stored in strings.If you name a variable all, classes, functions, java, import, or variables, calling clear followed by that name deletes the variable with that name. clear does not interpret the name as a keyword in this context. For example, if the workspace contains variables a, all, b, and ball, clear all deletes the variable all only.You can clear the handle of a figure or other object, but that does not remove the object itself. Use delete to remove objects and files. Deleting an object does not delete the variable, if any, used for storing its handle.On UNIX systems, clear does not affect the amount of memory allocated to the MATLAB process.The clear function does not clear Simulink models. Use close instead. Input Argumentskeyword A name specifying whether to clear variables,classes, or packages or subsets of them, as describedin the following table:ExamplesGiven a workspace containing the following variables Name Size Bytes Classc 3x4 1200 cell arrayframe 1x1 java.awt.Framegbl1 1x1 8 double array (global) gbl2 1x1 8 double array (global) xint 1x1 1 int8 arrayyou can clear a single variable, xint, by typingclear xintTo clear all global variables, typeclear globalwhosName Size Bytes Classc 3x4 1200 cell arrayframe 1x1 java.awt.FrameUsing regular expressions, clear those variables with names that begin with Mon, Tue, or Wed:clear('-regexp', '^Mon|^Tue|^Wed');To clear all compiled regular and MEX-functions from memory, type clear functions. In the following case, clear functions was unable to clear one code file function from memory, testfun, because the function is locked.clear functions % Attempt to clear all functions.inmemans ='testfun' % One code file function remains in memory.mislocked testfunans =1 % This function is locked in memory.munlock testfun% Once you unlock the function from memory, you can clear it.clear functionsinmemans =Empty cell array: 0-by-1Clearing handle graphics handles does not remove the objects themselves, nor does deleting the objects remove variables storing their handles.hf = figure; % Creates figure object, stores handle in variable hf delete(hf) % Removes figure object, but not the variable hfclear hf % Removes hf from the workspace; figure could still exist AlternativesAs an alternative to the clear function, use Edit > Clear Workspace in the MATLAB desktop.。
LabWindowsCVI串口通信函数

LabWindowsCVI串口通信函数LabWindows/CVI串口通信函数LabWindows/CVI提供的RS-232函数库主要包括以下几类函数:串行口打开/关闭(Open/Close)函数,串行口输入/输出(Input/Output)函数,串行口控制(Control)函数,串行口状态查询(Status)函数和串行口事件处理(Callbacks)函数。
下面分别予以介绍。
1.串行口打开/关闭函数1)OpenCom函数功能:表示以默认的参数设置方式打开一个串口。
该函数原型为:int OpenCom (int COM_Port,char Device_Name[ ] )其中,参数COM_Port为整型变量,用于指定串口号,有效范围为1~1000;Device_Name[]为字符型数组,是用ASCⅡ码字符串表示的串口名。
2)OpenComConfig函数功能:用来打开一个串行口并进行相关的参数设置。
该函数原型为:int OpenComConfig(int COM_Port,char Device_Name[],long Baud_Rate,int Parity,int Data_Bits,int Stop_Bits,int Input_Queue_Size,int Output_Queue_Size)其中,参数COM_Port为整型变量,用于指定串口号,有效范围为1~1000;Device_Name[]为字符型数组,是用ASCⅡ码字符串表示的串口名。
例如,以“COM1”来代替端口1,如果输入值为NULL或一个空字符串,则以COM_Port号作为指定端口号。
Baud_Rate为长整型变量,用来设置串行口的传输速率,标准的传输速率有110、300、600、1200、2400、4800、9600、19200b/s等;默认值为9600。
Parity为整型变量,用来指定奇偶校验模式。
0表示无奇偶校验,1表示奇校验,2表示偶校验;Data_Bits为整型变量,用来指定每帧信息中数据位的个数,可选5、6、7、8;Stop_Bits为整型变量,用来指定每帧信息中停止位的个数,可选1、1.5或2;Input_Queue_Size为整型变量,用来指定串行口输入队列的大小;Output_Queue_Size为整型变量,用来指定串行口输出队列的大小。
matlab串口程序

matlab串口程序function serial_communication2_OpeningFcn(hObject, eventdata, handles, varargin) handles.output = hObject;warning('off');javaFrame = get(hObject, 'JavaFrame');javaFrame.setFigureIcon(javax.swing.ImageIcon('icon.jpg'));%% 初始化参数hasData = false; %表征串口是否接收到数据isShow = false; %表征是否正在进行数据显示,即是否正在执行函数dataDisp isStopDisp = false; %表征是否按下了【停止显示】按钮isHexDisp = false; %表征是否勾选了【十六进制显示】isHexSend = false; %表征是否勾选了【十六进制发送】numRec = 0; %接收字符计数numSend = 0; %发送字符计数strRec = ''; %已接收的字符串%% 将上述参数作为应用数据,存入窗口对象内setappdata(hObject, 'hasData', hasData);setappdata(hObject, 'strRec', strRec);setappdata(hObject, 'numRec', numRec);setappdata(hObject, 'numSend', numSend);setappdata(hObject, 'isShow', isShow);setappdata(hObject, 'isStopDisp', isStopDisp);setappdata(hObject, 'isHexDisp', isHexDisp);setappdata(hObject, 'isHexSend', isHexSend);guidata(hObject, handles);function start_serial_Callback(hObject, eventdata, handles) % 【打开/关闭串口】按钮的回调函数% 打开串口,并初始化相关参数%% 若按下【打开串口】按钮,打开串口if get(hObject, 'value')%% 获取串口的端口名com_n = sprintf('com%d', get(/doc/515782715.html,, 'value'));%% 获取波特率rates = [300 600 1200 2400 4800 9600 19200 38400 43000 56000 57600 115200]; baud_rate = rates(get(handles.rate, 'value'));%% 获取校验位设置switch get(handles.jiaoyan, 'value')case 1jiaoyan = 'none';case 2jiaoyan = 'odd';case 3jiaoyan = 'even';end%% 获取数据位个数data_bits = 5 + get(handles.data_bits, 'value');%% 获取停止位个数stop_bits = get(handles.stop_bits, 'value');%% 创建串口对象scom = serial(com_n);%% 配置串口属性,指定其回调函数set(scom, 'BaudRate', baud_rate, 'Parity', jiaoyan, 'DataBits',...data_bits, 'StopBits', stop_bits, 'BytesAvailableFcnCount', 10,...'BytesAvailableFcnMode', 'byte', 'BytesAvailableFcn', {@bytes, handles},... 'TimerPeriod', 0.05, 'timerfcn', {@dataDisp, handles});%% 将串口对象的句柄作为用户数据,存入窗口对象set(handles.figure1, 'UserData', scom);%% 尝试打开串口tryfopen(scom); %打开串口catch % 若串口打开失败,提示“串口不可获得!”msgbox('串口不可获得!');set(hObject, 'value', 0); %弹起本按钮return;end%% 打开串口后,允许串口发送数据,清空接收显示区,点亮串口状态指示灯,%% 并更改本按钮文本为“关闭串口”set(handles.period_send, 'Enable', 'on'); %启用【自动发送】按钮set(handles.manual_send, 'Enable', 'on'); %启用【手动发送】按钮set(handles.xianshi, 'string', ''); %清空接收显示区set(handles.activex1, 'value', 1); %点亮串口状态指示灯set(hObject, 'String', '关闭串口'); %设置本按钮文本为“关闭串口”else %若关闭串口%% 停止并删除定时器t = timerfind;if ~isempty(t)stop(t);delete(t);end%% 停止并删除串口对象scoms = instrfind;stopasync(scoms);fclose(scoms);delete(scoms);%% 禁用【自动发送】和【手动发送】按钮,熄灭串口状态指示灯set(handles.period_send, 'Enable', 'off', 'value', 0); %禁用【自动发送】按钮set(handles.manual_send, 'Enable', 'off'); %禁用【手动发送】按钮set(handles.activex1, 'value', 0); %熄灭串口状态指示灯endfunction dataDisp(obj, event, handles)global value% 串口的TimerFcn回调函数% 串口数据显示%% 获取参数hasData = getappdata(handles.figure1, 'hasData'); %串口是否收到数据strRec = getappdata(handles.figure1, 'strRec'); %串口数据的字符串形式,定时显示该数据numRec = getappdata(handles.figure1, 'numRec'); %串口接收到的数据个数%% 若串口没有接收到数据,先尝试接收串口数据if ~hasDatabytes(obj, event, handles);end%% 若串口有数据,显示串口数据if hasData%% 给数据显示模块加互斥锁%% 在执行显示数据模块时,不接受串口数据,即不执行BytesAvailableFcn回调函数setappdata(handles.figure1, 'isShow', true);%% 若要显示的字符串长度超过10000,清空显示区if length(strRec) > 10000strRec = '';setappdata(handles.figure1, 'strRec', strRec);end%% 显示数据set(handles.xianshi, 'string', strRec);%%value=get(handles.xianshi,'string');value=textscan(value,'%s'); %读取其中的数据value=value{1};%得到数据,存储到value中value=hex2dec(value);% value=cellfun(@str2double,value);%把得到的字符转换成数字figure(1),plot(value)%% 更新接收计数set(handles.rec,'string', numRec);%% 更新hasData标志,表明串口数据已经显示setappdata(handles.figure1, 'hasData', false);%% 给数据显示模块解锁setappdata(handles.figure1, 'isShow', false);endfunction bytes(obj, ~, handles)% 串口的BytesAvailableFcn回调函数% 串口接收数据%% 获取参数strRec = getappdata(handles.figure1, 'strRec'); %获取串口要显示的数据numRec = getappdata(handles.figure1, 'numRec'); %获取串口已接收数据的个数isStopDisp = getappdata(handles.figure1,'isStopDisp'); %是否按下了【停止显示】按钮isHexDisp = getappdata(handles.figure1, 'isHexDisp'); %是否十六进制显示isShow = getappdata(handles.figure1, 'isShow'); %是否正在执行显示数据操作%% 若正在执行数据显示操作,暂不接收串口数据if isShowreturn;end%% 获取串口可获取的数据个数n = get(obj, 'BytesAvailable');%% 若串口有数据,接收所有数据if n%% 更新hasData参数,表明串口有数据需要显示setappdata(handles.figure1, 'hasData', true);%% 读取串口数据a = fread(obj, n, 'uchar');%% 若没有停止显示,将接收到的数据解算出来,准备显示if ~isStopDisp%% 根据进制显示的状态,解析数据为要显示的字符串if ~isHexDispc = char(a');elsestrHex = dec2hex(a')';strHex2 = [strHex; blanks(size(a, 1))];c = strHex2(:)';end%% 更新已接收的数据个数numRec = numRec + size(a, 1);%% 更新要显示的字符串strRec = [strRec c];end%% 更新参数setappdata(handles.figure1, 'numRec', numRec); %更新已接收的数据个数setappdata(handles.figure1, 'strRec', strRec); %更新要显示的字符串endfunction qingkong_Callback(hObject, eventdata, handles)%% 清空要显示的字符串setappdata(handles.figure1, 'strRec', '');%% 清空显示set(handles.xianshi, 'String', '');function stop_disp_Callback(hObject, eventdata, handles)%% 根据【停止显示】按钮的状态,更新isStopDisp参数if get(hObject, 'Value')isStopDisp = true;elseisStopDisp = false;endsetappdata(handles.figure1, 'isStopDisp', isStopDisp);function hex_disp_Callback(hObject, eventdata, handles)%% 根据【十六进制显示】复选框的状态,更新isHexDisp参数if get(hObject, 'Value')isHexDisp = true;elseisHexDisp = false;endsetappdata(handles.figure1, 'isHexDisp', isHexDisp);function manual_send_Callback(hObject, eventdata, handles) scom = get(handles.figure1, 'UserData');numSend = getappdata(handles.figure1, 'numSend');val = get(handles.sends, 'UserData');numSend = numSend + length(val);set(handles.trans, 'string', num2str(numSend));setappdata(handles.figure1, 'numSend', numSend);%% 若要发送的数据不为空,发送数据if ~isempty(val)%% 设置倒计数的初值n = 1000;while n%% 获取串口的传输状态,若串口没有正在写数据,写入数据str = get(scom, 'TransferStatus');if ~(strcmp(str, 'write') || strcmp(str, 'read&write')) fwrite(scom, val, 'uint8', 'async'); %数据写入串口 break;endn = n - 1; %倒计数endendfunction clear_send_Callback(hObject, eventdata, handles) %% 清空发送区set(handles.sends, 'string', '')%% 更新要发送的数据set(handles.sends, 'UserData', []);function checkbox2_Callback(hObject, eventdata, handles) function period_send_Callback(hObject, eventdata, handles) % 【自动发送】按钮的Callback回调函数%% 若按下【自动发送】按钮,启动定时器;否则,停止并删除定时器if get(hObject, 'value')t1 = 0.001 * str2double(get(handles.period1, 'string'));%获取定时器周期t = timer('ExecutionMode','fixedrate', 'Period', t1, 'TimerFcn',...{@manual_send_Callback, handles}); %创建定时器set(handles.period1, 'Enable', 'off'); %禁用设置定时器周期的Edit Text对象set(handles.sends, 'Enable', 'inactive'); %禁用数据发送编辑区start(t); %启动定时器elseset(handles.period1, 'Enable', 'on'); %启用设置定时器周期的Edit Text对象set(handles.sends, 'Enable', 'on'); %启用数据发送编辑区t = timerfind; %查找定时器stop(t); %停止定时器delete(t); %删除定时器endfunction period1_Callback(hObject, eventdata, handles)function period1_CreateFcn(hObject, eventdata, handles)if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white');endfunction clear_count_Callback(hObject, eventdata, handles) %% 计数清零,并更新参数numRec和numSendset([handles.rec, handles.trans], 'string', '0')setappdata(handles.figure1, 'numRec', 0);setappdata(handles.figure1, 'numSend', 0);function copy_data_Callback(hObject, eventdata, handles)%% 设置是否允许复制接收数据显示区内的数据if get(hObject,'value')set(handles.xianshi, 'enable', 'on');elseset(handles.xianshi, 'enable', 'inactive');endfunction figure1_CloseRequestFcn(hObject, eventdata, handles)% 关闭窗口时,检查定时器和串口是否已关闭% 若没有关闭,则先关闭%% 查找定时器t = timerfind;%% 若存在定时器对象,停止并关闭if ~isempty(t)stop(t); %若定时器没有停止,则停止定时器delete(t);end%% 查找串口对象scoms = instrfind;%% 尝试停止、关闭删除串口对象trystopasync(scoms);fclose(scoms);delete(scoms);end%% 关闭窗口delete(hObject);function hex_send_Callback(hObject, eventdata, handles)%% 根据【十六进制发送】复选框的状态,更新isHexSend参数if get(hObject,'value')isHexSend = true;elseisHexSend = false;setappdata(handles.figure1, 'isHexSend', isHexSend);%% 更新要发送的数据sends_Callback(handles.sends, eventdata, handles);function sends_Callback(hObject, eventdata, handles)% 数据发送编辑区的Callback回调函数% 更新要发送的数据%% 获取数据发送编辑区的字符串str = get(hObject, 'string');%% 获取参数isHexSend的值isHexSend = getappdata(handles.figure1, 'isHexSend');if ~isHexSend %若为ASCII值形式发送,直接将字符串转化为对应的数值val = double(str);else %若为十六进制发送,获取要发送的数据n = find(str == ' '); %查找空格n =[0 n length(str)+1]; %空格的索引值%% 每两个相邻空格之间的字符串为数值的十六进制形式,将其转化为数值for i = 1 : length(n)-1temp = str(n(i)+1 : n(i+1)-1); %获得每段数据的长度,为数据转换为十进制做准备 if ~rem(length(temp), 2)b{i} = reshape(temp, 2, [])'; %将每段十六进制字符串转化为单元数组elsebreak;endendval = hex2dec(b)'; %将十六进制字符串转化为十进制数,等待写入串口%% 更新要显示的数据set(hObject, 'UserData', val);% --- Executes on button press in pushbutton3.function pushbutton3_Callback(hObject, eventdata, handles) % hObject handle to pushbutton3 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB% handles structure with handles and user data (see GUIDATA)global valueh_temp=findobj('tag','edit2');outpath=get(h_temp,'String');outpath=[outpath '\'];str_img=strcat('data','.txt');value=get(handles.xianshi,'string');value=textscan(value,'%s'); %读取其中的数据value=value{1};%得到数据,存储到value中value=hex2dec(value);% value=cellfun(@str2double,value);%把得到的字符转换成数字save([outpath str_img],'value','-ascii');。
Matlab串口函数

2009-09-25 21:22Matlab是数学计算的强大工具,它以矩阵作为数据操作的基本单位,广泛应用在以矩阵运算为主要工作方式的数理统计、自动控制、数字信号处理、动态系统仿真等领域。
Matlab 便捷灵活、操作简单、处理功能强大,因而利用Matlab对采集到的ABS试验数据进行分析处理是非常合适的,关键问题是如何将数据从ECU传到计算机。
Matlab支持面向对象技术,用一个对象将计算机串口封装起来,只要创建串口对象,对串口对象操作就是对串口操作,非常方便。
使用serial函数就可创建串口对象,串口对象有很多属性[4],通过定义串口对象的属性,能定义串口的通信模式,从串口对象属性也能了解串口的状态。
要想通过串口传输数据,必须先用fopen函数打开串口;数据传输结束后要用fclose。
函数关闭串口。
表1列出了常用的与串口操作有关的函数。
表1 Matlab串口函数介绍_____________________________________________________函数说明_____________________________________________________serial 创建一个串口对象,格式:s = serial('coml' )fopen 打开串口对象,格式:fope n( s)fread 读取串口数据,格式: fread(s)fclose 关闭串口对象,格式:fclose(s)free 解除Matlab对串口对象的控制,使serial 其他程序能对该串口进行读写操作delete 删除对象s,格式:delete( s)clear 从工作空间中删除对象s,格式:clear(s)___________________________________________________当建立了一个串口对象后,可以利用Matlab对其参数进行设置,包括对波特率、同步或异步读取方式、读取或写数据的等待时间等。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
% % H = SERIAL1 returns the handle to a new SERIAL1 or the handle to % the existing singleton*. % % SERIAL1('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SERIAL1.M with the given input arguments. % % SERIAL1('Property','Value',...) creates a new SERIAL1 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before serial1_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to serial1_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES
% --- Executes just before serial1 is made visible. function serial1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to serial1 (see VARARGIN) global s; handles.mycom = s; % Choose default command line output for serial1 handles.output = hObject;
fopen(obj1); %打开串口 fopen(obj2); k=1; datas=zeros([1,100]); while(k<101)
if obj1.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);
功能描述: 1.选择串口,点击 START,即等待串口发送数据,数据缓存 4000bytes。接收缓存区满后绘 图,同时显示最大电压值和波形功率值。 2.File 菜单下有 Import Data 和 Export Data 功能,可将电压数据保存到 txt 文件中,同时可 读取 txt 中的数据并显示相关波形。 3.Image 菜单下有 Open Image 和 Save Image 功能,可将波形保存成图片格式,同时可打开 图片显示在绘图窗口。 Matlab 源代码: function varargout = serial1(varargin) % SERIAL1 M-file for serial1.fig % SERIAL1, by itself, creates a new SERIAL1 or raises the existing % singleton*.
fopen 打开串口对象,格式:fope n( s)
fread 读取串口数据,格式: fread(s)
fclose 关闭串口对象,格式:fclose(s)
free 解除 Matlab 对串口对象进行读写操作
delete 删除对象 s,格式:delete( s)
机。 Matlab 支持面向对象技术,用一个对象将计算机串口封装起来,只要创建串口对象,对串 口对象操作就是对串口操作,非常方便。使用 serial 函数就可创建串口对象,串口对象有很 多属性[4],通过定义串口对象的属性,能定义串口的通信模式,从串口对象属性也能了解 串口的状态。要想通过串口传输数据,必须先用 fopen 函数打开串口;数据传输结束后要用 fclose。函数关闭串口。表 1 列出了常用的与串口操作有关的函数。
% Update handles structure guidata(hObject, handles);
% UIWAIT makes serial1 wait for user response (see UIRESUME) % uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line. function varargout = serial1_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA)
clear 从工作空间中删除对象 s,格式:clear(s)
___________________________________________________
当建立了一个串口对象后,可以利用 Matlab 对其参数进行设置,包括对波特率、同步或异 步读取方式、读取或写数据的等待时间等。本文以波特率的设置为例来说明串口参数的设置 方法。 波特率的设置,一般有两种方法:(1)在创建串口对象时设定波特率:s= serial(`coml' ,'baudrate','9600'); (2)用 set 命令:set(s,'baudrate','9600')。
if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else gui_mainfcn(gui_State, varargin{:});
end % End initialization code - DO NOT EDIT %global s selected_com selected_baud selected_databits selected_stopbits selected_parity selected_flowctrl
表 1 Matlab 串口函数介绍
_____________________________________________________
函数
说明
_____________________________________________________
serial 创建一个串口对象,格式:s = serial('coml' )
matlab 串口编程 2009 年 06 月 10 日 星期三 下午 11:43
function serialdwj %本程序使用的是虚拟串口软件 VSPD 虚拟的 COM2 和 COM3 来测试的 %使用 COM1 也可以使用 已经经过测试了 %如果要使用 请使用 COM1 口 就可以与下位机通信了 obj1=instrfind('Type','serial','Port','COM3','Tag',''); %COM2 为测试串口 obj2=instrfind('Type','serial','Port','COM2','Tag',''); if isempty(obj1)
delete(obj1); %删除测试串口 fclose(obj2); delete(obj2); end
%现在使用的 m 文件来显示的 %到后来有机会就使用 gui 界面来显示
MATLAB 接收串口数据 GUI 界面 2009-09-19 12:42 工作流程:AD7818 采样模拟信号,12bits 输出,串口将数据发送给 PC。串口发送波特率 57600Bd,数据位 8 位,停止位一位。每个数据分两次发送,高四位补零。设计 GUI 界面接 收串口数据并显示波形。 GUI 界面如下:
Matlab 串口函数 2009-09-25 21:22 Matlab 是数学计算的强大工具,它以矩阵作为数据操作的基本单位,广泛应用在以矩阵运 算为主要工作方式的数理统计、自动控制、数字信号处理、动态系统仿真等领域。Matlab 便捷灵活、操作简单、处理功能强大,因而利用 Matlab 对采 集到的 ABS 试验数据进行分析处理是非常合适的,关键问题是如何将数据从 ECU 传到计算