Cannot close connection. MATLAB connection to Due at COM9 exists in your workspace. To create a new connection, clear the existing object.

35 views (last 30 days)
I cannot close the ports of the arduino after a GUIDE GUI program.
All the commands I have tried at the exit function are:
try
myArduinoAddonLibrary = getappdata(0,'ARD_AD');
clear myArduinoAddonLibrary;
arduinoObj = getappdata(0,'ARD');
fclose(serial(arduinoObj.Port));
delete(serial(arduinoObj.Port))
clear arduinoObj;
catch errorObj
errordlg(getReport(errorObj,'extended','hyperlinks','off'),'Arduino Error');
end
What would I be doing wrong?
The error that appears when I try to create another Arduino connection in the same port is:
MATLAB connection to Due at COM9 exists in your workspace. To create a new connection, clear the existing object
For MATLAB 2019a
  1 Comment
Jason
Jason on 17 Sep 2019
However, I have noticed that if I click the exit task several times, the ports duplicate? What could this be?
Instrument Object Array
Index: Type: Status: Name:
1 serial closed Serial-COM9
2 serial closed Serial-COM9
3 serial closed Serial-COM9
At the end of the exit task, I now run
clear all
to make sure no variables are left in the GUI workspace. And the error has now changed to:
"Unable to create a communication link with the serial port. Please check your input argument PORT..."
However, MATLAB crashes with an internal error.

Sign in to comment.

Accepted Answer

Jason
Jason on 17 Sep 2019
We solved it using this:
try
clear
myArduinoAddonLibrary = getappdata(0,'ARD_AD');
clear myArduinoAddonLibrary;
arduinoObj = getappdata(0,'ARD');
fclose(serial(arduinoObj.Port));
delete(serial(arduinoObj.Port))
clear arduinoObj;
catch errorObj
errordlg(getReport(errorObj,'extended','hyperlinks','off'),'Arduino Error');
end
%Remove appdata from memory
rmappdata(0,'ARD')
rmappdata(0,'ARD_AD')
clear all;
We just added clear at the start made sure the workspace was totally clear at the end.

More Answers (1)

saleh said bouhliga
saleh said bouhliga on 20 Sep 2020
In the MatLab Help Center they had nice description of how to clear a variable from memory. Check it here: https://www.mathworks.com/help/matlab/ref/clearvars.html
In your case should be: clearvars -global a;

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!