serial data & real time plot

5 views (last 30 days)
vishwash saxena
vishwash saxena on 6 Mar 2011
i want to get a serial data and plot its value against the time...
here is the code
obj = serial('COM1') %creating the object
set(obj,'BaudRate',9600) %setting baudrate
fopen(obj); %open port
set(obj,'terminator','cr') %providing the terminator
a1=0; % a variable for y axis
time1=now; % time is in x axis
while 2>1 % infinite loop
time2=now;
x=[time1 time2];
ip_data = fscanf(obj) ;
a2= str2num(ip_data) ;
a=[a1 a2];
line(x,a);
datetick('x','HH:MM') %change the axis
pause(0.5);
a1=a2;
time1=time2;
end
is it correct???

Answers (1)

Paulo Silva
Paulo Silva on 6 Mar 2011
while 2>1 % infinite loop
you can do it better
while 1 %same as while 2>1
Now for the plotting, first create a line (before the loop) with NaN values, liH=line(NaN,NaN) and inside the loop set the lines values.
set(liH,'XData',[get(liH,'XData') x]);
set(liH,'YData',[get(liH,'YData') a]);
If it gets too slow please consider the preallocation of XData and YData, fill it with NaN values and when the loop gets to the end of the preallocated data do something to "reset" it, if your script only runs for a short while you don't have to do it.
  2 Comments
Walter Roberson
Walter Roberson on 6 Mar 2011
Myself I prefer
while true
Paulo Silva
Paulo Silva on 6 Mar 2011
while ~~~~~~~~~~~~~false

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!