I am now trying to establish the serial communication between Arduino and Matlab. The script is very simple:
Matlab send a number named as i
to Arduino;
Arduino receive this i
, then send it back to Matlab;
Repeat step 1&2 for 10 times, i.e., Matlab sends 1,2,...,10 to Arduino, then receive the 1,2,...,10 from Arduino. However, Matlab only get back 3,4,...,10, while the first i=1 and i=2 are lost (I have already made the inputbuffersize=200 now, still not right).
Hereby is the code from 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);
And the Arduino Code:
char ibyte;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available()>0)
{
ibyte=Serial.read();
Serial.write(ibyte);
}
}
My reference link is: http://robocv.blogspot.com/2012/01/serial-communication-between-arduino.html
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…