Matlab-Arduino实时绘图

时间:2017-02-27 18:33:45

标签: matlab arduino serial-communication

我正在尝试将数据从我的arduino发送到matlab并使用GUI。即使没有按下按钮,我也想连续读取数据。为此,我必须使用fscanf函数,但我不知道在哪里放它。肯定有一个while循环等待应该放置此函数的事件(例如按下的按钮)。我只是一个初学者,所以这对你来说可能是一个愚蠢的问题。 提前谢谢!

function varargout = UltraPlot(varargin)

global a;
global k;
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
               'gui_Singleton',  gui_Singleton, ...
               'gui_OpeningFcn', @UltraPlot_OpeningFcn, ...
               'gui_OutputFcn',  @UltraPlot_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
disp('Ultraplot');


function UltraPlot_OpeningFcn(hObject, eventdata, handles, varargin)

global a;
global k;
a = serial('COM3');
fopen(a);
handles.output = hObject;


guidata(hObject, handles);


disp('Opening');


function varargout = UltraPlot_OutputFcn(hObject, eventdata, handles) 

varargout{1} = handles.output;
global a;
global k;
disp('varargout');

function Start_Callback(hObject, eventdata, handles)

global a;
global k;
fprintf(a,'%d',1);
disp('Button pressed');

1 个答案:

答案 0 :(得分:2)

您必须将Matlab设置为在while循环中等待来自Arduino的任何数据,请检查以下示例代码:

clear;clc;
S=serial('com18'); % Create an S Object
data=0;
set(S,'inputbuffersize',4096,'timeout',20); % Set serial communication     parameter
fopen(S); % Open serial communcation

   while (1)
        if s.bytesavailable>0 % If data from Arduino is available
          data=fscanf(S);
          data = str2num(data);
          % Do whatever you want with data here...
        end
     data=0;
   end