clc close all; t=[0]; m=[0;0;0;0] p = plot(t,m) buf = []; x=0; legend('acc_x','acc_y','acc_z','dong') grid on; set(gcf,'unit','normalized','position',[0.2,0.2,0.64,0.7]); delete(instrfindall('Type','serial'));%清理串口 object = serial('com7','BaudRate',115200);%配置串口 fopen(object); state = 0; Len = 0; Lenf = 0; % for i=1:shuliang while true data=fread(object,1);%读取数据 buf = [buf data]; switch state case 0 if length(buf)>=5 if buf(1)==170 && buf(2)==187 && buf(3)==204 Len = buf(4); Lenf = 255 - buf(5); if Len==Lenf state = 1; else buf(1) = []; end else buf(1) = []; end end case 1 if length(buf)>=Len ver = 0; for i=1:(Len-1) ver = ver + buf(i); end ver = mod(ver,256); % disp(ver); % disp(buf(Len)); disp(buf); if ver==buf(Len) % buf = buf(Len:end); buf = [] else buf(1) = []; end state = 0; end otherwise state = 0; end % t=[t i]; % drawnow % if i>250 % x=x+1; % end % axis([x x+250 -10 10]); end fclose(object); delete(object); clear object;