【发布时间】:2018-03-29 07:31:13
【问题描述】:
大家好,我是 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;
【问题讨论】: