EmbeddedRelated.com
Code Snippets

Matlab code to plot values from port in real time

March 12, 2013 Coded in Matlab
clc
clear all
close all
s1 = serial('COM26', 'BaudRate', 57600);
set(s1,'Terminator',35);
    fopen(s1);
V=[];
val='';
time=200;
count=0;
f=0;
 %   **********************************************************************
 %    Read Serial values
tic
tt=toc;
while(tt<time)
    val=fscanf(s1);
    tt=toc;
  
%########################################################################
 A=[];
 B=[];
 C=[];
 b=[];
 x=[];
 j=1;
 

     if(j<numel(val))
         while(val(j)~='$')
             a=val(j);
             b=[b,a];
             j=j+1;
         end
         A=[A,str2num(b)];
         j=j+1;
         b=[];
         while(val(j)~='*')
             a=val(j);
             b=[b,a];
             j=j+1;
         end
         B=[B,str2num(b)];
         j=j+1;
         b=[];
         while(val(j)~='#')
             a=val(j);
             b=[b,a];
             j=j+1;
         end
         C=[C,str2num(b)];
         i=j;
         b=[];
         f=f+i;
     end
     
x=[x,round(toc)];
if(~(isempty(A)&&isempty(B)&&isempty(C)))
    subplot(1,2,1)
    plot(x,A,'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',5);
    hold on % if u want this in different graph remove hold on and add "figure" command before each graph;
    plot(x,B,'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',5);
    grid on;
    subplot(1,2,2)
    plot(x,(B/(A+B))*100,'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','m','MarkerSize',5);
    hold on
    plot(x,C,'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','b','MarkerSize',5);
    grid on;
    pause(.01);
end

end
hold off
fclose(s1);