我一直在尝试使用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通信的正确方法吗?
答案 0 :(得分:1)
串口写入失败的方法并不多:
您需要检查流控制选项,如果您的设备不支持RTS / CTS,但您的代码启用了硬件握手,则通信将失败。
答案 1 :(得分:1)
通过在尝试最初编写代码的行中添加以下内容来解决此问题:
旧行:
fprintf(mbed,input);
新行:
fprintf(mbed, '1', 'async');
我不知道为什么会修复它,但它有。这可能对将来尝试写入mbed的人有用。