Real time serial data graphing

63 views (last 30 days)
Ghufran Aldawood
Ghufran Aldawood on 31 Jan 2021
Commented: Walter Roberson on 1 Feb 2021
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:
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)

Answers (1)

Walter Roberson
Walter Roberson on 31 Jan 2021
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 Comments
Ghufran Aldawood
Ghufran Aldawood on 31 Jan 2021
Thank you for the explanation! I tried to use animatedline instead of line but I am still getting the same result.
Walter Roberson
Walter Roberson on 1 Feb 2021
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.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!