How to close a serialport? 2019b

14 views (last 30 days)
Sergey Yakubson
Sergey Yakubson on 5 Nov 2019
Edited: Pedro Inácio on 5 Jan 2023
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);

Answers (2)

Charles Tritt
Charles Tritt on 6 Feb 2020
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 on 5 Jan 2023
Edited: Pedro Inácio on 5 Jan 2023
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

Community Treasure Hunt

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

Start Hunting!