matlab收发数据,并实时显示波形

PORT = 'COM3';  %端口号
if exist('s', 'var')  %判断上一次打开的端口有没有关闭
    fclose(s);%关闭s
end
s = serial(PORT, 'baudrate', 115200);%设置波特率
fopen(s);%打开s
fprintf(s,'>>AutoOut=1');         % 给串口写入数据
fprintf(s,'>>Hex=0');        

pv = str2double(a);%如果输入时ascii码直接用这个,就可以获得double型变量。

总的程序

功能:接受数据,并实时显示

% PORT = '/dev/tty.wchusbserial148230';
PORT = 'COM3';
if exist('s', 'var')
    fclose(s);
end
s = serial(PORT, 'baudrate', 115200);
fopen(s);
fprintf(s,'>>AutoOut=1');         % 给串口写入数据
fprintf(s,'>>Hex=0');         % 给串口写入数据
%% try obtain points

c=1


%% load dynamic data: 1 point

w = figure;
set(w,'WindowKeyPressFcn',@KeyPressFcn);
global stop;
stop = 0;



for i = 1:c
    subplot(c,1,i);
    h(i) = animatedline;
    ax(i) = gca;
    ax(i).YGrid = 'on';
%     ax(i).YLim = [0 3.3];
end

% ax(1).YLim = [500 1500];
% ax(2).YLim = [0 10];
% ax(3).YLim = [0 10];
 
startTime = datetime('now');
t = startTime;

while 1
    
    if stop == 1
        break;
    end
    
    % Get cufrrent time
    t =  datetime('now') - startTime;    
%     t = t + 1e-6;
    
    v = fscanf(s);
    if isempty(v)
        continue;
    end
    [n1, n2]=size(v);
    if n2 ~= 14
        continue;
    end
    disp(v);
    % Add points to animation
    a=v(1:8);
    pv = str2double(a);
    if v(10)~='m'
        pv=pv*0.001;
    end
    addpoints(h(i),datenum(t),pv);
    ax.XLim = datenum([t-seconds(50) t]);
    datetick('x','keeplimits');
    drawnow


end


猜你喜欢

转载自blog.csdn.net/dss875914213/article/details/86616888
今日推荐