Hi,
I'm interfacing an Arduino Due with Matlab and currently I'm trying to measure the serial communication latency.
I'm sending integers from 1:100 from matlab to arduino and then reading them back, basically doing a roundtrip.
Yet, the first couple of packets I receive back from arduino is always 0, unless I introduce a delay of 50ms between serial.read and serial.println in arduino code.
The values I read back on matlab goes like this:
0 0 0 1 2 3 4 5
I've tried to put a delay just for the first couple packets, 5 to be exact. It worked sometimes and didn't in other cases. I've tried to put a boot-up delay on arduino, as I read arduino restarts itself when matlab interacts with it.
I've already searched the forum and the web, but couldn't resolve the issue completely yet.
Hopefully someone would point out my mistake. I included the code below.
Thank you in advance.
-Eric
--arduino--
int ibyte;
int initBit = 1;
void setup()
{
Serial.begin(115200);
delay(3000); //arduino boot delay
}
void loop()
{
if(Serial.available()>0)
{
ibyte=Serial.read(); //read serial
//misses first 2 or 4 packets unless I introduce a delay
//delay(50);
Serial.println(ibyte); //write serial
}
}
--matlab--
clear all
close all
%%
numInt = 100; % number of integers to send arduino
numRepeat = 100; % repeat
%initialize the 2D array to observe packets sent back from arduino
rx = zeros(numInt,numRepeat);
%% serial communication
s1=serial('COM5','BaudRate',115200);
s1.ReadAsyncMode = 'continuous';
fopen(s1);
%give time to arduino to boot-up
pause(3)
%% timer
% Start asynchronous reading
readasync(s1);
tstart=tic; %start timer
for jj=1:numRepeat
for i = 1:numInt
%wait for idle
while(strcmp(get(s1,'TransferStatus'),'idle')<1)
end
fwrite(s1, i, 'uint8', 'async'); %send to arduino
%wait for if bytes available
while(s1.BytesAvailable<=0)
end
rx(i,jj) = fscanf(s1, '%d'); %read back from arduino
end
end
telapsed=toc(tstart); %end timer
%%
% Give arduino some time
pause(3);
stopasync(s1);
% Close and delete serial comm.
pause(1);
fclose(s1);
delete(instrfindall);
clear s1;
%% calculate serial comm latency in milli-seconds
serialLatency=1000*telapsed/(numInt*numRepeat);
disp(serialLatency);
%% plot the received values
disp('making plot..')
plot(1:(numInt),rx(:,end));