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.
The matlab code that I am using is as follows:
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
The error message that appears is
Error using serial/fprintf (line 144)
Error: An error occurred during writing.
Error in test (line 14)
fprintf(mbed, input);
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
fwrite(mbed, input);
which comes up with essentially the same error message.
Once I have tried this once the next error message that I receive is:
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
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.
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?