我现在正在尝试建立Arduino和Matlab之间的串行通信。脚本非常简单:
Matlab 向 Arduino 发送一个名为
i
的数字;Arduino收到这个
i
,然后将其发送回Matlab;
重复步骤1&2 10次,即Matlab发送1,2,...,10到Arduino,然后从Arduino接收1,2,...,10。然而,Matlab只返回3,4,...,10,而第一个i=1和i=2丢失了(我现在已经使inputbuffersize=200,仍然不对)。
这是来自 Matlab 的代码:
clc,clear;
s=serial('COM16','BaudRate',9600);
s.InputBufferSize = 200;
fopen(s);
a=10;
rx = zeros(1, a); % rx is used to store the data send back by Arduino
ry = zeros(1, a); % ry is just helping me to see what happens in Serial
for i = 1:1:a
fwrite(s, i); % Start to write the value "i" through serial to Arduino
pause(0.5) % if no pause, the result is worse than now
ry(i) = s.BytesAvailable; % check how many data are there in the Buffer
if s.BytesAvailable>0
rx(i) = fread(s, s.BytesAvailable); % Record the data send by Arduino
end
end
fclose(s);
以及 Arduino 代码:
char ibyte;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available()>0)
{
ibyte=Serial.read();
Serial.write(ibyte);
}
}
我的引用链接是:http://robocv.blogspot.com/2012/01/serial-communication-between-arduino.html
最佳答案
当您打开串行连接时,Arduino 会自行重置,引导加载程序会等待潜在的草图上传。这会在草图实际运行之前增加一些延迟。
打开串行连接后添加暂停。
fopen(s);
pause(3);
还有其他选项:
通过向 PC 发送一些内容,让 Arduino 宣布其启动时间。例如,您等待 Arduino 发送
S
。我不确定 MATLAB 是否可以实现这一点,但如果您禁用串口的 DTR 引脚,Arduino 将不会自动重置。
直接用编程器烧写代码,这样就没有 Bootstrap 在启动时等待。但这也会阻止您通过 USB 上传草图。
A hardware solution to prevent auto reset.但这会阻止在草图上传期间进行必要的重新启动,因此您必须手动安排重置时间。
关于matlab - Arduino 和 Matlab 之间的串行通信丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51728813/