简体   繁体   English

Matlab串行通讯:fprintf行为不一致

[英]Matlab serial communication: fprintf inconsistent behaviour

I am writing a script to talk to an arduino. 我正在写一个脚本来与arduino聊天。 The arduino listens for communication on the serial port and acts according to the command received. arduino侦听串行端口上的通信,并根据收到的命令进行操作。

If I work in the Matlab command prompt, everything works as expected: I send the commands: 如果我在Matlab命令提示符下工作,那么一切都会按预期进行:我发送以下命令:

s = serial('COM4','BaudRate',9600, 'Terminator', 'LF/CR');
fopen(s);
fprintf(s, '%s','start');
pause(10;
fprintf(s, '%s','stop');
fclose(s);

and the arduino reacts by enabling a pump for 10 seconds before switching it off. 并且arduino会通过关闭泵10秒钟来做出反应。

If I use the same exact code from a script, nothing happens. 如果我使用脚本中的相同代码,则什么也不会发生。 The problem seems to reside in the fprintf because if I open the serial communication from the script (and leave it open), I can send the start/stop commands from the prompt and it works. 问题似乎出在fprintf上,因为如果我从脚本打开串行通信(并保持打开状态),则可以从提示符发送开始/停止命令,并且该命令可以正常工作。

I have tried adding a line terminator to the script 我尝试将行终止符添加到脚本中

fprintf(s, '%s \n','start');

but this again does nothing (although it works fine from command prompt). 但这又什么也不做(尽管在命令提示符下工作正常)。

Has anyone experience the same issue? 有人遇到过同样的问题吗?

It turns out the source of the problem is the very long time taken by the fopen function to work. 事实证明,问题的根源是fopen函数需要很长时间才能工作。 I had previously tried to add a 1 second pause after it, but seeing no improvement I had removed it. 我之前曾尝试在其后添加1秒钟的暂停,但是没有看到任何改善,因此我将其删除。 Now I just tried adding even more time (currently 3 seconds) and the script executes correctly. 现在,我只是尝试添加更多时间(当前为3秒),并且脚本可以正确执行。

To summarize: if you are having the same issue, add a 总结一下:如果您遇到相同的问题,请添加一个

pause(3)

between the fopen and any other serial port command, and the script should work fine. 在fopen和任何其他串行端口命令之间,脚本应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM