通过串口

时间:2018-03-29 07:31:13

标签: matlab arduino

大家好我是matlab的新手。我想通过串口读取arduino的数据输出。数据以特定时间间隔输出,逗号/空格分隔变量。我如何读取数据并在Matlab上绘制变量?

串口是这样的:

1.1 3.2

1.2 3.1

1.3 3.3 ...

感谢您的帮助。

这是我只读取一个变量的数据而没有任何空格的代码。如何修改它以读取多个变量的数据?

close all; 
clear all;
clc; 
fclose('all'); 
delete(instrfindall);

%User Defined Properties 
s = serial('COM5', 'baudrate', 9600);
plotTitle='HCSR04';
xLabel='Time (s)';
yLabel='Distance (cm)';
plotGrid = 'on';                
delay = .01;

%Define Function Variables
time = 0;
distance = 0;
count = 0;

%Set up Plot
plotGraph = plot(time,distance);             
title(plotTitle,'FontSize',25);
xlabel(xLabel,'FontSize',15);
ylabel(yLabel,'FontSize',15);
grid(plotGrid);

fopen(s);
tic

while ishandle(plotGraph)
        dist = str2num(fscanf(s))
        count = count + 1;    
        time(count) = toc;
        distance(count) = dist;
        set(plotGraph,'XData',time,'YData',distance);
        axis([time(count)-10 time(count) 0 10]);
        pause(delay);
end
fclose(s);
clear all;
close all;

我试过这个,但似乎没有用。

close all; 
clear all;
clc; 
fclose('all'); 
delete(instrfindall);

%User Defined Properties 
s = serial('COM3', 'baudrate', 9600);
plotTitle='Sensor Test';
xLabel='Time (s)';
yLabel='Distance (cm)';
plotGrid = 'on';                
delay = .01;

%Define Function Variables
time = 0;
distance1 = 0;
distance2 = 0;
count = 0;

%Set up Plot
plotGraph(1) = plot(time,distance1);
plotGraph(2) = plot(time,distance2);
title(plotTitle,'FontSize',25);
xlabel(xLabel,'FontSize',15);
ylabel(yLabel,'FontSize',15);
grid(plotGrid);

fopen(s);
tic

while ishandle(plotGraph)
        str = fscanf(s);
        dist = textscan(str,'%f %f');
        count = count + 1;    
        time(count) = toc;
        dist1(count) = dist(1);
        dist2(count) = dist(2);
        set(plotGraph(1),'XData',time,'YData',dist1);
        set(plotGraph(2),'XData',time,'YData',dist2); 
        axis([time(count)-10 time(count) 0 10]);
        pause(delay);
end
fclose(s);
clear all;
close all;

1 个答案:

答案 0 :(得分:0)

您需要更改从arduino获取数据的位置。代码中的这一行:

dist = str2num(fscanf(s))

它从串行对象s获取数据。您可以将其更改为:

str = fscanf(s);
dist = textscan(str,'%f %f');

现在您将dist作为变量,其中包含两个数字。要将它们放在两个单独的变量中,您可以这样做:

distance1(count) = dist(1);
distance2(count) = dist(2);

要将它们放入绘图中,您现在需要两行,因此距离变量以

开头
distance = [0 0];

要将它们放入图表中,请使用

set(plotGraph(1),'XData',time,'YData',distance1);
set(plotGraph(2),'XData',time,'YData',distance2);