How to close a serialport? 2019b

조회 수: 22 (최근 30일)
Sergey Yakubson
Sergey Yakubson 2019년 11월 5일
편집: Pedro Inácio 2023년 1월 5일
When is used serial i can open and close port by fopen/fclose
How to close port with serialport?
Code:
serialportlist("all")
serialportlist("available")
serial_com_6 = serialport("COM6", 115200,"Timeout",5);
Error using serialport (line 116)
Unable to connect to the serialport device at port 'COM6'. Verify that a device is connected to the port, the port is not in use, and all serialport input arguments and
parameter values are supported by the device.
Error in IR (line 4)
serial_com_6 = serialport("COM6", 115200,"Timeout",5);

답변 (2개)

Charles Tritt
Charles Tritt 2020년 2월 6일
I had the same question. I can't find this documented any place, but did some experiments. I found that simply clearing the serialport object from the workspace made the port available outside of Matlab.

Pedro Inácio
Pedro Inácio 2023년 1월 5일
편집: Pedro Inácio 2023년 1월 5일
Using your code example, I provide a simple example on how to open and close the serial connection.
Starting by inspecting the serial ports conditions:
>> availableSerialObj = serialportlist("available");
>> disp(availableSerialObj);
COM6
>> allSerialObj = serialportlist("all");
>> disp(allSerialObj);
COM6
Serial port COM6 is available. Initiate serial port COM6:
>> serialObj = serialport("COM6",11500,"Timeout",5);
Inspect for the serial ports conditions:
>> availableSerialObj = serialportlist("available");
>> disp(availableSerialObj);
>> allSerialObj = serialportlist("all");
>> disp(allSerialObj);
COM6
COM6 is open, and as you reported, a re-call to the serialport function triggers an error:
>> try
>> serialObj = serialport("COM6",11500,"Timeout",5);
>> displayAllProperties(serialObj)
>> catch err
>> disp(err.getReport());
>> end
Catching the error report on the MATLAB console:
Error using serialport (line 116) Unable to connect to the serialport device at port 'COM6'. Verify that a device is connected to the port, the port is not in use, and all serialport input arguments and parameter values are supported by the device. See related documentation for troubleshooting steps.
To close and re-open the serial object you must clear the variable using the clearvars function.
>> clearvars('serialObj');
Now you can repeat the same code sequence above:
>> availableSerialObj = serialportlist("available");
>> disp(availableSerialObj);
COM6
>> allSerialObj = serialportlist("all");
>> disp(allSerialObj);
COM6
>> serialObj = serialport("COM6",11500,"Timeout",5);
>> availableSerialObj = serialportlist("available");
>> disp(availableSerialObj);
>> allSerialObj = serialportlist("all");
>> disp(allSerialObj);
COM6

카테고리

Help CenterFile Exchange에서 Serial and USB Communication에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by