Blink an LED Using MATLAB Support Package and Arduino

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);
    pause(0.5);
    writeDigitalPin(a, 9, 0);
    pause(0.5);
end

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. 

Common Error Messages

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 -

  1. Disconnect the USB cable from both Arduino and computer 
  2. Clean up MATLAB by typing clear in MATLAB Command Window
  3. Plug in the USB cable to computer and Arduino
  4. Try connecting to the Arduino from MATLAB by using arduino command 

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. 

This guide was first published on Jan 14, 2014. It was last updated on Jan 14, 2014. This page (Blink an LED Using MATLAB Support Package and Arduino) was last updated on Aug 18, 2019.