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

17 views (last 30 days)
% Create Arduino object with necessary libraries
arduinoObj = arduino("COM9", "Mega2560", Libraries = ["I2C", "SPI", "Serial", "Servo"]);
MATLAB connection to Mega2560 at COM9 exists in your workspace. To create a new connection, clear the existing object.
% Configure digital pins D20 and D21
configurePin(arduinoObj, "D20", "DigitalInput"); % D20 as input
configurePin(arduinoObj, "D21", "DigitalOutput"); % D21 as output
% Duration to record data (in seconds)
duration = 10;
% Time interval between consecutive data reads
stepTime = 1;
% Total number of data samples to be recorded
samples = duration / stepTime;
% Initialize array to store data for pin D20
D20Array = zeros(1, samples);
% Initialize dataIndex for storing in the array
dataIndex = 1;
% Start a stopwatch to track time (for the loop)
tObj = tic;
% Collect data in the loop for the specified duration
while toc(tObj) <= duration
% Read the state of pin D20 (DigitalInput)
D20 = readDigitalPin(arduinoObj, "D20");
% Store the read data in the corresponding data array
D20Array(dataIndex) = D20;
% Increment dataIndex
dataIndex = dataIndex + 1;
% Pause for the stepTime interval before the next reading
pause(stepTime);
end
% Convert the recorded data to a timetable for further analysis
% Ensure the name is consistent with what will be used in plotting
ARD_DATA_4 = timetable(seconds((1:samples)*stepTime)', D20Array');
% Plot the recorded data
plot(ARD_DATA_4.Time, ARD_DATA_4.Var1); % Use the correct variable name 'Var1' or whatever name the timetable has for the data
title('Recorded Data from Pin D20');
xlabel('Time (s)');
ylabel('Amplitude (0 or 1)');
grid on;

Answers (1)

Manish
Manish on 13 May 2025
Hi,
I understand that you're facing an error when connecting audio with MATLAB.
I assume that a previous connection was established with the device, and since that connection was not overridden, you are now encountering this error.
To clear the existing object from the workspace, use the 'clear' command.
Here is a sample code:
% Clear any previous Arduino connection
if exist('arduinoObj', 'var')
clear arduinoObj;
end
% Create Arduino object with necessary libraries
arduinoObj = arduino("COM9", "Mega2560", Libraries = ["I2C", "SPI", "Serial", "Servo"]);
For better understanding, refer to the documentation link below:
Hope it helps!

Community Treasure Hunt

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

Start Hunting!