How to make a serial object throw a timeout error?

조회 수: 6 (최근 30일)
Emanuel Blei
Emanuel Blei 2015년 10월 6일
댓글: Walter Roberson 2015년 10월 6일
Hello, For those more knowledgeable in Matlab. My question is very simple: How do I manage to make Matlab throw a simple timeout error for a serial object rather than just give the usual timeout warning?
Example code:
s = serial('COM1'); % Please note there is no instrument connected on 'COM1'
s.BytesAvailableFcnMode = 'terminator';
s.Timeout = 2
s.ErrorFcn = @instrcallback;
fopen(s)
record(s)
fprintf(s,'#1?','async')
out = fscanf(s)
fclose(s)
delete(s)
clear s
There is no instrument connected to COM1 and therefore I do not expect any messages. The communication-mode is set to asynchronous as required to receive an error message and instrcallback is the callback function set in ErrorFcn.
What I would expect to happen is that a timeout occurs (that happens) and that an error message is send from the built-in instrcallback function. But it seems that ErrorFcn is never called and therefore never calls instrcallback.
Further information: The reason I would like to have an error function is that I want to use a try-catch statement to handle exceptions in serial communication.
Many thanks,
Emanuel

답변 (1개)

Walter Roberson
Walter Roberson 2015년 10월 6일
A try/catch is not going to be in scope of a callback, not unless the try/catch is in the callback itself. Callbacks are executed as-if from the command line, since the function that created them might have returned. All functions might have returned -- the user might be sitting at the command prompt.
  댓글 수: 2
Emanuel Blei
Emanuel Blei 2015년 10월 6일
Dear Walter,
Thank you for your answer.
I think I might not have been clear about this. The callback is only used to produce the error message. There is no try-catch construct inside the callback but is meant to react to the error message produced by the callback.
Kind regards,
Emanuel
Walter Roberson
Walter Roberson 2015년 10월 6일
You indicated earlier "The reason I would like to have an error function is that I want to use a try-catch statement to handle exceptions in serial communication." but there is not going to be a try-catch in effect at the time of the timeout.
ErrorFcn is specifically documented as gaining control on a TimeOut so that should work... in theory... provided you get past the fopen() of course.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Interactive Control and Callbacks에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by