The error you are encountering suggests that an earlier arduino or serialport object is still alive in MATLAB (or in another MATLAB session). Make sure to clear the previous arduino objects before calling the arduino function again, or simulating a model on the Arduino so write in the command window:
clear all
Additionally, before starting the serial communication you should properly check that serial port is free so write in the command window:
if ~isempty(instrfind)
fclose(instrfind);
delete(instrfind);
end
Refer to these similar MATLAB answers for more information:
- https://www.mathworks.com/support/search.html/answers/257651-failed-to-open-serial-port-com3-to-communicate-with-board-uno.html?fq%5B%5D=asset_type_name%3Aanswer&fq%5B%5D=category%3Asupport%2Fmatlab-su6911&page=1
- https://www.mathworks.com/support/search.html/answers/417507-why-do-i-receive-failed-to-open-serial-port-com-to-communicate-with-the-board-or-open-fail-port.html?fq%5B%5D=asset_type_name%3Aanswer&fq%5B%5D=category%3Asimulink%2Fsupportpkg-arduino&page=1
arduino() is a support package that enables you to use MATLAB to communicate with several Arduino boards under the entry-level series, MKR, and nano families of Arduino. You can read and write sensor data through the Arduino and immediately see the results in MATLAB without having to compile. It gives high-level functions such as readVoltage, writePWMDutyCycle, I²C/SPI helpers, etc. It is best for quick prototyping, controlling multiple pins/sensors at modest rates, etc.
serialport() gives you a raw byte stream but you write the Arduino sketch (or any MCU) protocol yourself.
Hence you can start with arduino() but if you hit speed limits or need a custom protocol you can switch to serialport().
For real time plotting multiple sensor streams, the example below shows how to enable callbacks to read streaming ASCII terminated data from an Arduino® board using the serialport interface:
Hope this helps!
