我现在正在尝试建立Arduino和Matlab之间的串行通信。脚本非常简单:Matlab将一个名为i的数字发送给Arduino;
Arduino接收到这个i,然后将其发送回Matlab;
重复步骤1&2 10次,即Matlab向Arduino发送1,2,…,10,然后从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代码:
^{pr2}$