How can you close a busy/unavailable serial port object that was created with "serialport" if a script crashes without properly closing it?
29 次查看(过去 30 天)
显示 更早的评论
I use MATLAB to connect to Arduino boards through the serial port interface, and I'm currently working on transitioning my code from using the serial() function to using the serialport() function that was introduced in version R2019b. The issue that I'm running into is that I can't find a way to close an existing serialport connection if I don't have access to the instrument object in the workspace, like when a script crashes without properly closing out the serialport object.
In pre-R2019b version, you could fetch serial() object handles from outside the workspace using the instrfind() function. So, for example:
serialcon = serial('COM1','baudrate',115200);
fopen(serialcon);
...and then let's say some dumb code mistake crashed my script. I could recover and reset the serial port, to make it available again, like this:
serialcon = instrfind('port','COM1');
fclose(serialcon);
delete(serialcon);
But instrfind() only works for serial() objects and not for the new serialport() objects. Is there a new function that can pull up open serialport() handles so that I can close them? Because I'm getting a little tired of restarting MATLAB every time my scripts throw an error.
1 个评论
Seth Fraden
2023-10-16
I have the same problem and can't find a solution except to reboot my computer!
回答(1 个)
Sachin Lodhi
2024-4-29
编辑:Sachin Lodhi
2024-4-29
Hellow Andrew, I understand that you are trying to close a busy serial port object after Matlab has crashed without properly closing the port.
Since there is no direct function like "instrfind" for "serialport" objects, if you lose track of an object or need to find which ports are currently in use, consider the following workaround:
1) List Available Serial Ports: Use the "serialportlist" function to get a list of all available serial ports. This can help identify which ports are likely open.
availablePorts = serialportlist("available")
2) Try-Catch When Opening: Attempt to open a suspected port within a "try-catch" block. If the port is already in use, Matlab will throw an error, from which you can deduce that the port is open but not properly closed in the previous session.
try
spTest = serialport("COM3", 115200);
% If successful, the port was not previously open, close it now.
delete(spTest);
catch ME
disp("Port COM3 is likely already open or unavailable.");
end
This approach requires you to manage "serialport" objects more actively but avoids the need to restart Matlab to close stuck serial connections.
I also recommend you to please refer to the following documentation for more information on "serialportlist":
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!