フィルターのクリア

How to close a serialport? 2019b

7 ビュー (過去 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 Center および File ExchangeSerial and USB Communication についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by