Now that we have the necessary software installed, it's time to blink an LED. In this example, we will use the MATLAB support package.
To establish a connection between MATLAB and Arduino boards, the following command can be used from MATLAB.
>> a = arduino
This command connects MATLAB to the first Arduino detected on the system. A MATLAB variable by the name 'a' should now appear on the workspace or an error message indicating what went wrong.
To switch on the LED connected to Pin 9 on the Due, execute the following command
>> writeDigitalPin(a, 9, 1)
Here we are sending a request from MATLAB to Arduino, to write on the Digital Pin 9 the value of 1. This should switch ON your LED.
To blink the LED, we have to switch it ON and OFF periodically.
for i = 1:10
writeDigitalPin(a, 9, 1);
writeDigitalPin(a, 9, 0);
Other functions that are related to the MATLAB Support Package for Arduino can also be used along with the arduino object 'a'.
To take a look at the featured examples from MATLAB Support Package for Arduino type
arduinoExamples in MATLAB Command Window.
Cannot detect Arduino hardware. Make sure original Arduino hardware is properly plugged in. If using unofficial(clone) hardware, specify port and board type. For more information, see this user's guide for additional troubleshooting steps.
As mentioned in the error message, it is good practice to mention the COM port at which the Due is connected to the computer. For Windows Users, Control Panel > Hardware and Sound > Devices and Printers.
>> a = arduino('COM4','Due')
If for some reason the connection between MATLAB and Arduino board is lost, the following error message appears.
The host and client connection is lost. Make sure the board is plugged in and/or recreate arduino and its related objects.
The best practices to follow to resolve this error -
- Disconnect the USB cable from both Arduino and computer
- Clean up MATLAB by typing
clearin MATLAB Command Window
- Plug in the USB cable to computer and Arduino
- Try connecting to the Arduino from MATLAB by using
The other common error message that one can encounter during the stage of reconnection is -
Failed to open serial port COM4 to communicate with Arduino board Due. Make sure there is no other MATLAB arduino object for this board. For troubleshooting, see Arduino Hardware Troubleshooting.
To resolve this error message, repeat all the steps from before after typing
clear all in MATLAB Command Window. In the event that this also does not help, close MATLAB and reopen before proceeding further.