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 Center および File ExchangeInteractive Control and Callbacks についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by