Opening a basic serial connection to the Arduino in Matlab is not difficult and is documented. Data is sent to the device using the fprintf() function and received using fscanf().

s = serial('COM3', 'BaudRate', 9600);
fopen(s);
fprintf(s, 'Hello World!');
line = fscanf(s);
fclose(s);

If we have data continually being sent by our device there are two ways of capturing it. We can create a loop within Matlab to constantly check if any data has been received however this doesn’t seem like brilliant coding practise. Alternatively we can make use of the Matlab’s BytesAvailable event and read the input buffer only when data is received.

Unfortunately, unlike languages like C++, Matlab is only able to pass variables by value and not by reference. So if we create an array in our workspace to hold the received data, our callback function will be unable to update it. However in Matlab it is possible to nest functions within the body of another. The variables defined in the outer function will be accessible to the inner function.

% Calling the function myFunc will display the number 10.
% Demonstrates that nested function has access to variables.
function myFunc

    myVar = 10;

    innerFunc()

    function innerFunc
        myVar
    end

end

The code to establish a serial connection is written into a Matlab function which also contain an array of all received data. The callback function of the BytesAvailable event is defined as a nested function and hence  can add to the data array when new data is received. This allows us to perform analysis on the data in parallel to it being read.

The full sourcecode of my function is shown below:
Read the rest of this entry »