How can I run matlab connected to arduino more than once?

I have a problem with connecting my arduino uno to matlab.. It actually runs perfectly for the first time but when I run it again it says this (Failed to open serial port COM4 to communicate with Arduino board Uno. Make sure there is no other MATLAB arduino object for this board. For troubleshooting, see Arduino Hardware Troubleshooting.
.. I'm using this command to connect: a = arduino('com4','uno') ..
If anyone can help here I would appreciate it ...

2 Commenti

You have to delete the object which you have created. For example, if you have this object arduino_board = arduino(port, board, 'Libraries', 'Servo'); then you have to delete this object in the end of the code, i.e. clear arduino_board; all the objects which you have created like this should be cleared.
And how can you clear e.g. arduino_board ???

Accedi per commentare.

 Risposta accettata

Are you running the connect command
a = arduino('com4','uno')
a second time while object 'a' still exists in the workspace? You only need to connect once.

4 Commenti

Yup I am running the connect command
It runs perfectly once I open MATLAB file and run for the first time... But if i do some justifications on my coding and run again it says "Failed to connect to com4 ..." ...
So I have to close MATLAB and open it again so it can run normally..
also when I'm using servo function in GUI ... it open the GUI window connected to arduino perfectly but when I push the button to control the servo motor it gives me the error " Failed to connect to com 4 ..."
As mentioned by Esther you need to connect only once. When you do a = arduino and it works, a is now your connection to arduino and you can use that variable repeatedly to do other things. When using in a GUI try to make it a global variable of some sorts so that you don't have to create a new connection every time.
Yea global a was the mistake .. thanks

Accedi per commentare.

Più risposte (2)

All you have to write a command "clear all" on the first line of your code . That's it.
You have to delete the object which you have created. For example, if you have this object arduino_board = arduino(port, board, 'Libraries', 'Servo'); then you have to delete this object in the end of the code, i.e. clear arduino_board; all the objects which you have created like this should be cleared.

Categorie

Scopri di più su MATLAB Support Package for Arduino Hardware in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by