uart-20200730A.m 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. clc
  2. close all;
  3. t=[0];
  4. m=[0;0;0;0]
  5. p = plot(t,m)
  6. buf = [];
  7. x=0;
  8. legend('acc_x','acc_y','acc_z','dong')
  9. grid on;
  10. set(gcf,'unit','normalized','position',[0.2,0.2,0.64,0.7]);
  11. delete(instrfindall('Type','serial'));%清理串口
  12. object = serial('com7','BaudRate',115200);%配置串口
  13. fopen(object);
  14. state = 0;
  15. Len = 0;
  16. Lenf = 0;
  17. % for i=1:shuliang
  18. while true
  19. data=fread(object,1);%读取数据
  20. buf = [buf data];
  21. switch state
  22. case 0
  23. if length(buf)>=5
  24. if buf(1)==170 && buf(2)==187 && buf(3)==204
  25. Len = buf(4);
  26. Lenf = 255 - buf(5);
  27. if Len==Lenf
  28. state = 1;
  29. else
  30. buf(1) = [];
  31. end
  32. else
  33. buf(1) = [];
  34. end
  35. end
  36. case 1
  37. if length(buf)>=Len
  38. ver = 0;
  39. for i=1:(Len-1)
  40. ver = ver + buf(i);
  41. end
  42. ver = mod(ver,256);
  43. % disp(ver);
  44. % disp(buf(Len));
  45. disp(buf);
  46. if ver==buf(Len)
  47. % buf = buf(Len:end);
  48. buf = []
  49. else
  50. buf(1) = [];
  51. end
  52. state = 0;
  53. end
  54. otherwise
  55. state = 0;
  56. end
  57. % t=[t i];
  58. % drawnow
  59. % if i>250
  60. % x=x+1;
  61. % end
  62. % axis([x x+250 -10 10]);
  63. end
  64. fclose(object);
  65. delete(object);
  66. clear object;