Updated on Jan 2017!
In this quick post we will write a Matlab script and a Arduino sketch to read and write serial commands.

Arduino side

This sketch is really simple, we will initialize the serial port with 9600 as baudrate in the setup() then call the serialRoutine() function in the main loop. The routine sends an incrementing integer via serial if the received command is ‘M’ and sends the “Ok” string when it receives ‘T’.

Matlab side

This script uses the serial(‘port’) function to create a serial port object associated with the specified serial port.
Check your Arduino Port. If you are using Windows modify the port variable to match the correct COM port. If you are a Linux user, open a terminal and create a symbolic link to the /dev/ttyS101 file as follows:

userk@dopamine:~$  sudo rm /dev/ttyS101
userk@dopamine:~$  sudo ln -s /dev/ttyACM18 /dev/ttyS101

Replace ttyACM18 with your port. Ok.
Now, easy game, let’s setup the baudrate to 9600, the terminator character to a carriage return and a few more stuff as the Timeout and the BufferSize.

Finally, if you print ‘T’ we should receive “Ok”, if you send ‘M’ we should get an integer.

Don’t forget to close, delete and clear the serial object or you won’t be able to use the serial port with Arduino anymore.

Full Code