フィルターのクリア

How to find unclosed serialport objects

4 ビュー (過去 30 日間)
Connor Olsen
Connor Olsen 2021 年 9 月 4 日
回答済み: Samay Sagar 2024 年 4 月 26 日
When trying to create a Serialport object on a port that has already has an open Serialport on it, I get the following error:
Error using serialport (line xx)
Unable to connect to the serialport device at port 'COMX'. 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.
If I open the serial port using the serial() function instead, there is a function that exists (instrfind) to retrieve all open ports, and can then be closed before attempting to reopen them. As far as I can tell, there is no function for the Serialport object that does the same thing. I can view which ports are on the computer, and which ones are available, but that doesn't enable me to close them without keeping track of the Serialport object when first created. I've looked at the documentation to help transition code from the serial class to serialport class, but so far I've found nothing.

回答 (1 件)

Samay Sagar
Samay Sagar 2024 年 4 月 26 日
In transitioning from MATLAB's “serial” to “serialport” interface, a common challenge arises in managing open serial connections. Unlike the “serial” function, which allowed for identification and management of open ports through “instrfind”, the “serialport” interface requires to keep track of open and closed ports. When you open a serial port, store the “serialport” object in a variable or a data structure that allows you to easily access it later. Before attempting to open a new connection to the same port, you can check this structure and close the existing connection if necessary.
if exist('mySerialPort', 'var')% Check if the port is already open and close it
delete(mySerialPort);
clear mySerialPort;
end
% Open the serial port
mySerialPort = serialport("COMX", 9600);
Starting from MATLAB version R2024a, the function “serialportfind” can be used to find any open connection.
For more information about “serialport” and “serialportfind”, refer the following documentation:

カテゴリ

Help Center および File ExchangeSerial and USB Communication についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by