Matlab和Arduino的连接(四):在matlab中串口通信发送相关信息至arduino(记录用)

作用效果:利用matlab的串口将信息发送到arduino端,并根据信息内容执行相应的程序。例如,matlab发送字符‘ssP’,arduino收到P时开始执行(相当于截止字符),提取字符串“ssP”的第一位,如果kk=第一位==‘s’,则开始闪烁灯。

matlab代码

clear;clc;
delete(instrfind({'Port'},{'COM6'}));%断开,释放串口对象占用空间
global s;%建立全局变量s
s = serial('COM6','BaudRate',9600,'DataBits',8);%设定相关的串口参数
fopen(s);
set(s,'BytesAvailableFcnMode','Terminator');
set(s,'Terminator','H');                    %设立中断,当串口检测到字符H时触发中断
s.BytesAvailableFcn =@ReceiveCallback; %中断触发后处理回调的事
for k=1:1:3
    fprintf(s,'lsH');
    pause(0.3);%时间间隔不宜过小
end
function ReceiveCallback(obj,event) %执行回调的函数
global s;
a = fscanf(s);
disp(a);
I = 'I Received';
disp(I);
end

arduino代码

char function_1;
String Indata;
String kk;
void setup() {
 Serial.begin(9600);
 pinMode(13,OUTPUT);
}

void loop() {
if(Serial.available()>0){
  function_1 = Serial.read();
  Indata +=function_1;
  //Serial.print("fggk");
  if(function_1 == 'H'){
    //Serial.print("jgf");
    //Serial.print(Indata);
    delay(20);
    kk = Indata.substring(0,1);//调取字符串的第一个字符
    Serial.print(kk);
    Serial.print("H");

    if(kk =="s")
    {
      for(int i=0;i<5;i++){
      //Serial.print(kk);
      digitalWrite(13,HIGH);
      delay(500);
      digitalWrite(13,LOW);
      delay(500);
      Indata = "";
      }
      }
      if(kk=="l"){
        digitalWrite(13,HIGH);
        delay(4000);
        }
        if(kk=="o"){
         digitalWrite(13,LOW);
         delay(4000);
         digitalWrite(13,HIGH);
         delay(4000);
         Indata="";
          }
    }
  }
}

matlab利用GUI发送串口信息:代码
在这里插入图片描述
Matlab GUI的全部的代码

%%%%利用matlab的GUI控制步进电机的运转方向,角度
function varargout = GUI_steppermotor(varargin)
% GUI_STEPPERMOTOR MATLAB code for GUI_steppermotor.fig
%      GUI_STEPPERMOTOR, by itself, creates a new GUI_STEPPERMOTOR or raises the existing
%      singleton*.
%
%      H = GUI_STEPPERMOTOR returns the handle to a new GUI_STEPPERMOTOR or the handle to
%      the existing singleton*.
%
%      GUI_STEPPERMOTOR('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in GUI_STEPPERMOTOR.M with the given input arguments.
%
%      GUI_STEPPERMOTOR('Property','Value',...) creates a new GUI_STEPPERMOTOR or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before GUI_steppermotor_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to GUI_steppermotor_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

% Edit the above text to modify the response to help GUI_steppermotor

% Last Modified by GUIDE v2.5 17-Apr-2021 13:42:05

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @GUI_steppermotor_OpeningFcn, ...
                   'gui_OutputFcn',  @GUI_steppermotor_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before GUI_steppermotor is made visible.
function GUI_steppermotor_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 GUI_steppermotor (see VARARGIN)

% Choose default command line output for GUI_steppermotor
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes GUI_steppermotor wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = GUI_steppermotor_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)

% Get default command line output from handles structure
varargout{1} = handles.output;


function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1


% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% delete(instrfind({'Port'},{'COM6'}));
% puerto_serial = serial('COM6');%查找通信接口对象并断开。
% puerto.serial.BaudRate = 9600;%设置波特率
% warning('off','MATLAB:serial:fscanf:unsuccessfulRead');%关闭警告信息
% fopen(puerto_serial);%打开串口'TimeOut',10
%fprintf('ff');
delete(instrfind({'Port'},{'COM6'}));
val_1 = get(handles.popupmenu1,'value');
angle_1 = num2str(handles.edit1.String);
switch(val_1)
    case 2
        dir_1 = 's';
    case 3
        dir_1 = 'l';
end

delete(instrfind({'Port'},{'COM6'}));%断开,释放串口对象占用空间
global s;%建立全局变量s
s = serial('COM6','BaudRate',9600,'DataBits',8);%设定相关的串口参数
fopen(s);
set(s,'BytesAvailableFcnMode','Terminator');
set(s,'Terminator','H');                    %设立中断,当串口检测到字符H时触发中断
s.BytesAvailableFcn =@ReceiveCallback; %中断触发后处理回调的事
HH = [dir_1,angle_1,'H'];
disp(HH);
for k=1:1:3
    fprintf(s,HH);
    pause(0.3);%时间间隔不宜过小
end```
  • 6
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: MatlabArduino可以通过串口通信进行数据交互。具体步骤如下: 1. 在Arduino IDE编写程序,将需要输的数据通过Serial.print()函数发送到串口。 2. 在Matlab使用serial函数创建一个串口对象,设置串口号、波特率等参数。 3. 使用fopen函数打开串口,使用fscanf函数读取串口数据。 4. 在Matlab对读取到的数据进行处理,例如绘制图表、进行计算等。 5. 使用fclose函数关闭串口。 需要注意的是,MatlabArduino的串口参数需要保持一致,例如波特率、数据位、停止位等。同时,需要在Arduino程序添加延时函数,以确保数据能够被完整地输到Matlab。 ### 回答2: Matlabarduino串口通信是一种常见的应用,在很多控制和测量系统都有广泛的应用。Matlab作为一种高级的数据处理软件,有着强大的计算和数据处理能力,而arduino则是一种开源的微控制器,有着丰富的硬件接口和良好的易用性。两者结合起来,可以快速实现复杂的控制和测量系统,嵌入式系统开发过程很常见的应用。 首先,在Matlab需要安装支持串口通信的工具箱,例如Instrument Control Toolbox,这个工具箱有专门的函数和工具,方便用户进行串口通信的设置和调试。而在arduino,也需要利用串口库函数,在代码进行设置和使用。 其次,在设置串口通信时,需要设置波特率、数据位、停止位和校验位等参数。波特率就是数据输速率,一般设为9600。数据位是指每个数据字节所包含的二进制数的位数,一般为8位。停止位是指在数据帧结尾处增加的一个非数据位,用于标识数据帧的结束,一般为1位。校验位是在数据输过程用于检测数据输的正确性,一般不使用。 最后,在Matlab可以使用serial函数来创建串口对象,并调用write和read函数实现数据发送和接收;而在arduino,可以利用Serial.print和Serial.read函数向Matlab发送和接收数据。通过在两者之间实现数据的交互,可以实现数据输和控制的功能,这对于嵌入式系统的开发来说,是非常重要的。例如在实现机器人控制Matlab可以发送控制命令,arduino可以接收并执行命令,实现智能控制系统的应用。 总之,Matlabarduino串口通信的应用非常广泛,在各种控制和测量系统都有着重要的作用。在实现串口通信时,需要注意设置参数、调试代码以及数据输方式等,才能实现良好的系统运行效果。相信随着科技的不断发展和应用的不断拓展,Matlabarduino串口通信的应用也将更加广泛和深入。 ### 回答3: MATLABArduino是两种常用的工具,它们各自具有不同的特点和应用场景。然而,在某些情况下,我们需要将这两种工具结合起来,使它们相互协作,以实现特定的功能需求。在这种情况下,串口通信就成为了一个重要的技术手段。 MATLABArduino通过串口通信可以实现双向数据输,也就是说,我们可以在MATLABArduino发送指令,从而控制Arduino完成一些特定的任务;同样地,Arduino也可以将数据输给MATLAB,以便我们对数据进行分析处理。 要实现MATLABArduino串口通信,我们首先需要完成以下几个步骤: 1. 设置Arduino串口通信参数。这包括波特率、数据位、校验位、停止位等。 2. 编写Arduino程序,接收MATLAB发送的指令,并执行相应的操作。在Arduino程序,我们需要使用Serial类来读取串口数据。 3. 在MATLAB,我们可以使用serial函数来创建一个串口对象,该对象包含了一些串口的配置参数,如串口号、波特率、数据位等。 4. 在MATLAB,我们可以使用fopen函数打开串口,并使用fprintf函数向Arduino发送指令。在这里,我们需要注意指令的格式,以便Arduino可以正确地解析和执行。 5. 在MATLAB,我们可以使用fscanf函数读取Arduino发送数据,并进行相应的处理和分析。 综上所述,MATLABArduino串口通信是一种非常有用的技术手段,它可以使这两种工具相互协作,为我们的科学研究和实验提供了更加便利和高效的方式。如果你需要使用MATLABArduino进行串口通信,请记得注意一些常见的问题,如协议格式、波特率选择、发送和接收缓冲区的大小等,从而避免出现不必要的错误和问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值