7 years, 5 months ago.

Serial interfacing to MATLAB: port fails after a write

I've adapted the code in the online example to send a character 'u' to a mbed as a trigger to release data. The Matlab .m file fails after the fprintf. The code works fine with a Tera Term terminal and The Matlab code below works fine when I code out the 'u' trigger. I know the 'u' is sent as the LED1 lights.

I must be missing something simple, but I can't think what!! Can you help?

The code on the mbed is: ----------

  1. include "mbed.h" Serial pc(USBTX, USBRX); DigitalOut myled(LED1);

AnalogIn x(p15);

int main() {

char c = pc.getc(); if(c == 'u') { myled = 1; while(1) { pc.printf("%d\n", x.read()); wait(0.1); } } } ----------

MATLAB code: ----------------- function mbedread()

TIMEOUT = 5; %time to wait for data before aborting n = 2; %size of n x n array to be addressed

try %create serial object to represent connection to mbed mbed = serial('COM5', ... 'BaudRate', 9600, ... 'Parity', 'none', ... 'DataBits', 8, ... 'StopBits', 1); %change depending on mbed configuration

set(mbed,'Timeout',TIMEOUT); %adjust timeout to ensure fast response when mbed disconnected

fopen(mbed); %open serial connection


fprintf (mbed, '%s', 'u'); %send a 'u' to mbed to release data

for column = 1:1:n %read in n column values into an array for row = 1:1:n %read in n row values into an array

values(row,column) = fscanf(mbed, '%d'); %get values into vector

end end

fclose(mbed); %close connection (this should never be reached when using while(1), but included for completeness) values catch %in case of error or mbed being disconnected disp('Failed!'); fclose(mbed); %close connection to prevent COM port being lokced open end --------------------

Question relating to:

1 Answer

7 years, 5 months ago.

Please use code tags (<<code>><</code>>) around your code, now it is not readable.

Anyway, yeah it happens, no we don't have a real solution for it (hopefully one day mbed devs get around to looking at it), yes we have workarounds: http://mbed.org/forum/helloworld/topic/3568/

TL;DR there is two options: downgrade to matlab 2009 or earlier (after that they improved serial handling, not much of an improvement imo), or put every printf statement inside a 'try' block, since they work fine, only after sending is complete they throw an exception.

Accepted Answer