我一直在尝试使用 Matlab 中的代码写入串行端口。但是,我首先尝试的所有操作都会导致错误消息,然后导致 Matlab 认为端口不可访问。
我使用的matlab代码如下:
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
出现的错误信息是
Error using serial/fprintf (line 144)
Error: An error occurred during writing.
Error in test (line 14)
fprintf(mbed, input);
我的主要问题是,从我可以在网上找到的所有内容看来,fprintf 命令应该可以工作。我也试过这条线
fwrite(mbed, input);
它提出了基本相同的错误消息。
一旦我尝试过这个,我收到的下一条错误消息是:
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
我似乎只能通过保存我的程序然后打开完全相同的程序来解决这个问题。尝试时,mbed 肯定连接到正确的 COM 端口。
我的问题是我的 fprintf 线哪里出错了?这是与串行端口或 mbed 通信的正确方法吗?