1
votes

I'm doing a project where I need to read and write serial data between MATLAB and Arduino. But MATLAB do not always successfully read data. I set baudrate 9600 and my serial setup is like this:

 delete(instrfind({'port'},{comPort})); %%delete if COM4 is setup for any ther usesr
 obj=serial(comPort);
 set(obj,'DataBits',8);
 set(obj,'StopBits',1);
 set(obj,'BaudRate',9600);
 set(obj,'Parity','none');
 set(obj,'InputBufferSize', 1024);

MATLAB sends data perfectly and Arduino read it perfectly too. But problem occurs when I wanna wait to read a data from arduino to MATLAB. Arduino sends data through this statements:

 Serial.println("azyb");
 Serial.flush();
  if (Serial.available()>0)  // to clear the buffer
       Serial.read();`

And code statement in MATLAB is:

 while(1)
    Arduino.ReadAsyncMode = 'continuous';
  %  readasync(Arduino);
    buf=Arduino.BytesAvailable;
    if buf>0
       bufData=bufData+fgets(Arduino);
       bufFlag=strfind(bufData,'azyb');
       if isempty(bufFlag)==0   %%means 'azyb' is found in buffer
           flushoutput(Arduino);
           break;
       end
    end
end

I'm not sure but most probably there is something I miss in this code. What could I do wrong?

FYI: interestingly this sometimes work but most of the time do not work. Specially when we only use Arduino but total circuit is not powered up, generally it worked and when total circuit is powered up , it never works.

2
Would you like this question of yours migrated to Arduino.SE, or to StackOverflow?Nick Alexeev
Better StackOverflow then Arduino.SE as I think main problem is in matlabAnklon

2 Answers

1
votes

Below is a function that I call in a loop to handle my data. The key parts for you will be the handling of buffer underflows in case of a timeout. You can increase this time via timeout. My experience is that MATLAB is amazing flakey with serial communication.

function result=ser_read(serial_handle)
timeout = 1000;
for i=1:timeout
   if(serial_handle.BytesAvailable~=0)
   break;
   end
end

if(serial_handle.BytesAvailable~=0)
result = fread(serial_handle,serial_handle.BytesAvailable,'uint8');
else
   fprintf('error, attempted read with no bytes available.');
   result=0;
   return;
end

end
0
votes

The problem is the synchronization most likely. You are telling Matlab to read the buffer as soon as it's length exceeds 3. But what if there is one character (say 'b') left from the previous transfer already whenever the Arduino is sending another 4? The first characters in the buffer will be then 'bazy', and won't match the expected string. You will need to think about some synchronization method for your protocol in order to avoid these phenomena.