How to make a serial object throw a timeout error?
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
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 个评论
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 Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!