title: Reading data from Arduino in Matlab through serial port
body: <p>Hi guys I am new to matlab. I would like to read data output from arduino through serial port. The data is output at certain time interval with comma/ space separating the variables. How I read the data and plot the variable on Matlab?</p>
  
  <p>The serial port is like this:</p>
  
  <p>1.1 3.2</p>
  
  <p>1.2 3.1</p>
  
  <p>1.3 3.3
  ...</p>
  
  <p>Thanks for your help.</p>
  
  <hr>
  
  <p>This is the code I got for reading data of only one variable without any space. How to modify that to read data of more than one variable?</p>
  
  <pre><code>close all; 
  clear all;
  clc; 
  fclose('all'); 
  delete(instrfindall);
  
  %User Defined Properties 
  s = serial('COM5', 'baudrate', 9600);
  plotTitle='HCSR04';
  xLabel='Time (s)';
  yLabel='Distance (cm)';
  plotGrid = 'on';                
  delay = .01;
  
  %Define Function Variables
  time = 0;
  distance = 0;
  count = 0;
  
  %Set up Plot
  plotGraph = plot(time,distance);             
  title(plotTitle,'FontSize',25);
  xlabel(xLabel,'FontSize',15);
  ylabel(yLabel,'FontSize',15);
  grid(plotGrid);
  
  fopen(s);
  tic
  
  while ishandle(plotGraph)
          dist = str2num(fscanf(s))
          count = count + 1;    
          time(count) = toc;
          distance(count) = dist;
          set(plotGraph,'XData',time,'YData',distance);
          axis([time(count)-10 time(count) 0 10]);
          pause(delay);
  end
  fclose(s);
  clear all;
  close all;
  </code></pre>
  
  <hr>
  
  <p>I tried this one but seems not working.</p>
  
  <pre><code>close all; 
  clear all;
  clc; 
  fclose('all'); 
  delete(instrfindall);
  
  %User Defined Properties 
  s = serial('COM3', 'baudrate', 9600);
  plotTitle='Sensor Test';
  xLabel='Time (s)';
  yLabel='Distance (cm)';
  plotGrid = 'on';                
  delay = .01;
  
  %Define Function Variables
  time = 0;
  distance1 = 0;
  distance2 = 0;
  count = 0;
  
  %Set up Plot
  plotGraph(1) = plot(time,distance1);
  plotGraph(2) = plot(time,distance2);
  title(plotTitle,'FontSize',25);
  xlabel(xLabel,'FontSize',15);
  ylabel(yLabel,'FontSize',15);
  grid(plotGrid);
  
  fopen(s);
  tic
  
  while ishandle(plotGraph)
          str = fscanf(s);
          dist = textscan(str,'%f %f');
          count = count + 1;    
          time(count) = toc;
          dist1(count) = dist(1);
          dist2(count) = dist(2);
          set(plotGraph(1),'XData',time,'YData',dist1);
          set(plotGraph(2),'XData',time,'YData',dist2); 
          axis([time(count)-10 time(count) 0 10]);
          pause(delay);
  end
  fclose(s);
  clear all;
  close all;
  </code></pre>