title: Trouble writing to a serial port between Matlab and C using an mbed
body: <p>I have been trying to write to a serial port using code in Matlab. However everything that I try first results in an error message and then causes Matlab to think that the port is inaccessible.</p>
  
  <p>The matlab code that I am using is as follows:</p>
  
  <pre><code>function test()
  
  TIMEOUT = 5;    %time to wait for data before aborting
  XPOINTS = 50;   %number of points along x axis
  
  %create serial object to represent connection to mbed
  mbed = serial('COM18','BaudRate', 9600, 'DataBits', 8);   %change depending on mbed configuration
  
  %set(mbed,'Timeout',TIMEOUT);        %adjust timeout to ensure fast response when mbed disconnected
  
  fopen(mbed);        %open serial connection
  input = 1;
  fprintf(mbed, input);
  x=0;
  while (x == 0)        
      values = fscanf(mbed, '%d');  
      disp(values);       
  end
  
  fclose(mbed);
  
  end
  </code></pre>
  
  <p>The error message that appears is </p>
  
  <pre><code>Error using serial/fprintf (line 144)
  Error: An error occurred during writing.
  
  Error in test (line 14)
  fprintf(mbed, input);
  </code></pre>
  
  <p>My main problem is that from all that I can find online it seems to say that the fprintf command should work. I have also tried the line</p>
  
  <pre><code>fwrite(mbed, input);
  </code></pre>
  
  <p>which comes up with essentially the same error message.</p>
  
  <p>Once I have tried this once the next error message that I receive is:</p>
  
  <pre><code>Error using serial/fopen (line 72)
  Open failed: Port: COM18 is not available. Available ports: COM1.
  Use INSTRFIND to determine if other instrument objects are connected to the requested device.
  
  Error in test (line 12)
  fopen(mbed);        %open serial connection
  </code></pre>
  
  <p>Which I can only seem to fix by saving my program and then opening the exact same one. The mbed is definitely connected to the right com port at the time of the attempt.</p>
  
  <p>My question is where am I going wrong with the fprintf line? Is that the correct way to communicate with a serial port or an mbed?</p>