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.