Real time serial data graphing
58 ビュー (過去 30 日間)
古いコメントを表示
Hello all,
I have this code to plot serial data coming in from my serial port and updating the graph in real time:
s = serialport("COM3",1200);
voltage = 0;
time1 = now;
liH=line(NaN,NaN)
while 1 % infinite loop
time2 = now;
x=[time1 time2];
data = readline(s);
data2 = str2double(data);
voltage2 = data2;
V = [voltage voltage2];
set(liH,'XData',[get(liH,'XData') x]);
set(liH,'YData',[get(liH,'YData') V]);
line(x,V);
datetick('x','HH:MM:SS')
%pause(0.5);
voltage=voltage2;
time1=time2;
end
I am getting some of the data streaming in but a lot of it is still missing - what I am getting now:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/504818/image.jpeg)
I have a simple code that sreams the data correctly but it is not a live stream and this is how the data should look:
s = serialport("COM3",1200);
data = read(s,100,"uint8")
x = (1:1:100);
figure(1)
plot(x,data)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/504823/image.jpeg)
0 件のコメント
回答 (1 件)
Walter Roberson
2021 年 1 月 31 日
I suggest you switch to using animatedline() to update your graphics.
At present, you are pulling out the old data for the line object, appending one new sample to it, and writing the data back. The first time you do that you are working with a vector of length 1, the second a vector of length 2, and so on. So the time involved to get to point N is 1+2+3+...+N which is N*(N+1)/2 and that adds up.
animatedline pre-initializes a buffer (usually of length 1000) and has a count of how many samples are in the buffer, and when the buffer gets full, it gets written as a whole into the list of complete buffers. In this way, the only need for expansion is in the writing of complete buffers; I do not recall at the moment how it keeps track of those efficiently.
2 件のコメント
Walter Roberson
2021 年 2 月 1 日
Is it possible that there is more than one number per line in places? Those would show up as nan in your plotting because str2double() of more than one value on a line would result in nan.
参考
カテゴリ
Help Center および File Exchange で Environmental Models についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!