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

arduinofcloseserial

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

Best Answer

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.
Related Question