Connecting Arduino board to MATLAB

3 views (last 30 days)
H404
H404 on 17 Jun 2025
Answered: TED MOSBY on 18 Jun 2025
I’m trying to interface my Arduino Uno with MATLAB to read sensor data and send control signals in real time. Why am I getting a 'Failed to open serial port' error often when I want to recoonect it ? Also shall I use arduino() or serialport() for better performance? How does it differ? Can real time plotting be done of the values I take from different sensors?

Answers (1)

TED MOSBY
TED MOSBY on 18 Jun 2025
Hi @H404,
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:
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!

Community Treasure Hunt

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

Start Hunting!