MATLAB Error Exception w/ Arduino

1 view (last 30 days)
Brendan Kenefick
Brendan Kenefick on 10 Jun 2020
Answered: Dhruv on 2 Jun 2025
Hello,
I am working on a project using the combination of Arduino and MATLAB and am sometimes (not often, but multiple times already) running into an issue when MATLAB stops due to an error while the Arduino is still transmitting data.
Essentially, the code begins with Arduino object getting opened, which begins the transmission of data to MATLAB. After the data is finished transmitting, the MATLAB code closes the Arduino object. However, every once in a while, an error occurs on the MATLAB end during data transmission and the code is quit. When this happens the Arduino object is unable to be closed and it causes a whole bunch of issues. Since it remains open and transmitting it will not allow for the program to re-run (as there isn't an arduino object to open since it is already running).
So, I was wondering if there was a way to automatically run a set of code whenever an error occurs during this process? In this code the Arduino object will be closed (ensuring that it is turned off even when there is an error). Any advice is appreciated
Thank you for your help!

Answers (1)

Dhruv
Dhruv on 2 Jun 2025
In order to handle unexpected errors during Arduino-MATLAB communication, use MATLAB's try-catch structure to ensure the Arduino object is properly closed even if an error occurs.
This prevents issues like a locked serial port or the inability to reconnect. Wrapping your code in a try-catch block allows you to clean up resources and avoid restarting MATLAB.
Additionally, consider using onCleanup for guaranteed cleanup actions. These techniques help maintain stable communication and allow safe re-execution of your program.
You may refer to the below documentations for further details:
I hope this helps!

Categories

Find more on Arduino Hardware in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!