How to make a serial object throw a timeout error?
6 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Walter Roberson
on 6 Oct 2015
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 Comments
Walter Roberson
on 6 Oct 2015
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.
See Also
Categories
Find more on Interactive Control and Callbacks in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!