필터 지우기
필터 지우기

fopen status for serial objects

조회 수: 45 (최근 30일)
C3145
C3145 2020년 6월 18일
댓글: C3145 2020년 6월 18일
Using R2016a, I'd like to nicely deal with fopen(serial) errors rather than the command window barf at me.
Normal syntax for fopen() includes [fileID,errmsg] = fopen(___)
But the serial version of the command using an object doesn't appear to return anything unless it errors.
>> obj1 = instrfind('Type', 'serial', 'Port', port, 'Tag', '');
>> set(obj1, 'BaudRate', 115200, 'Timeout', 1, 'Terminator','LF');
>> fopen(obj1)
>>
Note that fopen just happened without saying it worked.
Now, I'll open a TeraTerm session to COM5 and try again...
>> fopen(obj1)
Error using serial/fopen (line 72)
Open failed: Cannot connect to the COM5 port. Possible reasons are another
application is connected to the port or the port does not exist.
As expected. But... how do I deal with these messages programmatically?
>> [fileID,errmsg] = fopen(obj1)
Error using serial/fopen
Too many output arguments.
Nope. Argggg.
Thoughts/Comments/Flames?

채택된 답변

Geoff Hayes
Geoff Hayes 2020년 6월 18일
Could you use a try catch block to try to open the serial object and then, if there is an error, take the appropriate action given the exception?
obj1 = instrfind('Type', 'serial', 'Port', port, 'Tag', '');
set(obj1, 'BaudRate', 115200, 'Timeout', 1, 'Terminator','LF');
try
fopen(obj1);
catch ME
fprintf('Could not open serial object because of %s\n', ME.identifier);
if strcmp(ME.identifier,'<some error identifier>')
fprintf('Handling exception for %s\n', ME.identifier);
% perform the appropriate action
else
fprintf('Unhandled exception for %s\n', ME.identifier);
end
end
The '<some error identifier>' would be the error (or errors) that you are interested in.
  댓글 수: 1
C3145
C3145 2020년 6월 18일
Perfect. Thank you.
I'm a bit new to this and will dig into the docs on try/catch.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by