0

我一直在尝试使用 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 通信的正确方法吗?

4

2 回答 2

1

该问题已通过将以下内容添加到最初尝试编写代码的行来解决:

旧线:

fprintf(mbed,input);

新队 :

fprintf(mbed, '1', 'async');

我不知道为什么这解决了它,但它已经解决了。这可能对未来尝试写入 mbed 的人很有用。

于 2015-10-20T11:32:30.037 回答
1

串口写入失败的方式并不多:

  • 如果串行端口消失(例如通过拔下 USB-> 串行适配器)
  • 如果内核写入缓冲区已满(您以比流出端口更快的速度写入大量数据)
  • 如果由于流量控制,数据根本没有流出端口,并且超时时间已过

您需要检查您的流量控制选项,如果您的设备不支持 RTS/CTS,但您的代码启用了硬件握手,则通信将失败。

于 2015-10-19T18:10:38.130 回答