Sporadic timeout error in serial communication ruins program. How do I ignore it and retry?

3 views (last 30 days)
Hello,
So the problem that I'm having is when writing values to an external device using a serial port. The serial port is set up as follows:
handles.s = serial('COM1');
handles.s.BaudRate = 115200;
handles.s.DataBits = 8;
handles.s.StopBits = 1;
handles.s.Parity = 'NONE';
handles.s.InputBufferSize = (1024*100);
handles.s.Timeout = 3;
fopen(handles.s);
And this code works most of the time. I output values in a loop that uses the function show below to grab them from a GUI and output through the serial port:
function setValue(i, num, hObject, handles, negative)
string = strcat('Setting values (',num2str(i),')');
set(handles.status,'String',string);
fwrite(handles.s,255);
fwrite(handles.s,num);
if(negative == 0)
fwrite(handles.s,floor(str2double(get(hObject,'String'))/256));
fwrite(handles.s,mod(str2double(get(hObject,'String')),256));
else
fwrite(handles.s,floor(-str2double(get(hObject,'String'))/256));
fwrite(handles.s,mod(-str2double(get(hObject,'String')),256));
end
pause(.01);
The problem is that sometimes, unpredictably, the values will stop writing because of a timeout error. This requires me to shut down matlab and my hardware components, restart the machinery, and then reconnect matlab. If matlab could just try writing the value again, I could program my hardware components to ignore bad data and accept the new values... but matlab refuses to work after there has been a timeout error unless it is restarted.
I have read while searching for a solution that there may be "handshake pins" that need to be provided a steady voltage for serial communication to work properly... perhaps this is the solution? If so, where are these magical pins?
Thanks,
Erich

Answers (1)

Erich Glück
Erich Glück on 19 Oct 2011
Turns out I was just writing values too quickly which due to internal shenanigans sporadically overflowed the output buffer resulting in a timeout. This was fixed by replacing the pause(.01) with pause(.1).. slower transmit of data but at least it's reliable.
Erich
  1 Comment
Akshay Datar
Akshay Datar on 7 Sep 2016
Thanks Erich, I had same problem of timeout error and needed to restart matlab everytime. But by setting pause(0.1),problem is solved.

Sign in to comment.

Categories

Find more on Instrument Control Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!