首页 > 解决方案 > 使用 MATLAB 绘制实时数据

问题描述

我正在尝试绘制从传感器获取的实时数据。我希望图表在检测到新数据时始终更新。这是我当前的代码。我无法显示该行。

提前致谢。

代码:

clear all;
S = serialport('COM5',115200);
temp =[];
accx=[];
accy=[];
accz=[];
i = 0;
while true
  if S.NumBytesAvailable > 0
     data = readline(S); 
     temp = [str2double(split(data,','))]; 
     accx = [accx;temp(1)];
     accy = [accy;temp(2)];
     accz = [accz;temp(3)];
     plot(i,temp(1))
     i=i+1;
 end
end

图形:

在此处输入图像描述

标签: matlabplotgraph

解决方案


*可能对解决问题有用,也可能没用

鉴于您可以在 for 循环中成功检索样本/值。这是一个游乐场脚本,它将每次迭代时检索到的值添加到绘图中。这个 Playground 脚本在 while 循环中的每个循环上添加一个值。该hold on术语用于将现有绘图和新值保持在相同的当前轴上,gca。如果您在每次迭代中检索多个值,则此脚本可能需要稍作修改。在这里,随着样本数量的增加,我滑动 x 轴,这不是必需的,但确实给人一种示波器类型的感觉。

绘图片段:

绘图片段


在命令窗口中用鼠标光标按命令Ctrl+可用于终止脚本。C

游乐场脚本:

clf;
%Initializing animated line plot%
Animated_Plot = animatedline;
Sample_Index = 1;

while true 
    %Retrieve sample (temp) value%
    temp = sin(0.2*Sample_Index);
    
    %Add points to the plot%
    hold on
    addpoints(Animated_Plot, Sample_Index, temp);
    drawnow
    
    %Window is the number of samples on screen/figure at a time%
    Window = 50;
    Sample_Chunk = floor(Sample_Index/Window);
    Maximum_Amplitude = 1;
    Minimum_Amplitude = -1.5;
    axis([Sample_Chunk*Window Sample_Chunk*Window+Window Minimum_Amplitude Maximum_Amplitude]);
    title("Plotting 50 Samples at a Time");
    xlabel("Sample Index"); ylabel("Amplitude");
    Sample_Index = Sample_Index + 1;
    grid on
end

完整脚本:

完整的脚本可能会遵循这样的内容。我还没有通过读取 COM 端口对此进行测试:

clear all;
S = serialport('COM5',115200);
temp =[];
accx=[];
accy=[];
accz=[];

clf;
%Initializing animated line plot%
Animated_Plot = animatedline;
Sample_Index = 1;

while true 
  if S.NumBytesAvailable > 0
    
    data = readline(S); 
    temp = [str2double(split(data,','))]; 
    accx = [accx;temp(1)];
    accy = [accy;temp(2)];
    accz = [accz;temp(3)];

    %Add points to the plot%
    hold on
    addpoints(Animated_Plot, Sample_Index, temp(1));
    drawnow
    
    %Window is the number of samples on screen/figure at a time%
    Window = 50;
    Sample_Chunk = floor(Sample_Index/Window);
    Maximum_Amplitude = 1;
    Minimum_Amplitude = -1.5;
    axis([Sample_Chunk*Window Sample_Chunk*Window+Window Minimum_Amplitude Maximum_Amplitude]);
    title("Plotting 50 Samples at a Time");
    xlabel("Sample Index"); ylabel("Amplitude");
    Sample_Index = Sample_Index + 1;
    grid on
  end
end

使用 MATLAB R2019b 运行


推荐阅读