How to close a serialport? 2019b
22 次查看(过去 30 天)
显示 更早的评论
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);
0 个评论
回答(2 个)
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.
0 个评论
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
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!