You are viewing an older revision! See the latest version

Interfacing with Matlab

Table of Contents

  1. Reference

Using the basic serial over usb communication method, it is possible to interact with Matlab using the Matlab "serial" object. Using this method it is very easy to dump data from mbed into Matlab to be displayed or processed.

The code on the mbed side is exactly the same as you would use to talk to a pc with terraterm or similar. I have been using it to read analogue data from an accellerometer, so basically just dumping data from 3 AnalogIn's over the serial connection, using the code below:

main.cpp

#include "mbed.h"

AnalogIn x(18);
AnalogIn y(19);
AnalogIn z(20);

int main() {
    while(1) {
       printf("%d,%d,%d\n", x.read_mv(), y.read_mv(), z.read_mv());
    wait(0.1);
    }
}

The Matlab code I have been using basically just reads in the data from the serial port and displays it as a graph. The graph overwrites itself every n samples and the x-labels update to match. The try/catch block is important as if an error occurs while the serial object is instantiated before fclose() is called then the port remains open and cannot be closed. The only solution I have found to this is to restart the PC, so using a try/catch to close the port on an error is important!

function accell()

TIMEOUT = 5;    %time to wait for data before aborting
XPOINTS = 50;   %number of points along x axis

try
    %create serial object to represent connection to mbed
    mbed = serial('COM4', ...
                  'BaudRate', 9600, ...
                  'Parity', 'none', ...
                  'DataBits', 8, ...
                  'StopBits', 1);       %change depending on mbed configuration
    
    set(mbed,'Timeout',TIMEOUT);        %adjust timeout to ensure fast response when mbed disconnected
    
    fopen(mbed);        %open serial connection

    position = 1;       %initialise graph variables
    time = 1;
    x = [(1:XPOINTS)' (1:XPOINTS)' (1:XPOINTS)'];
    xlabels = (1:XPOINTS);
    y = zeros(XPOINTS,3);
    
    while (1)       %loop forever (or until an error occurs)
        
        values = fscanf(mbed, '%f,%f,%f');    %get values into vector
                                              %assumes data formatted as
                                              %'1,2,3'
        y(position,:) = values';    %put into y to be displayed
        
        %update position on x-axis and x-axis labels
        xlabels(position) = time;
        time = time + 1;
        if (position < XPOINTS)
            position = position + 1;
        else
            position = 1;
        end

        %display
        plot(x,y);
        set(gca, 'XTick', 1:XPOINTS);
        set(gca, 'XTickLabel', xlabels);

        drawnow;    %this is required to force the display to update before the function terminates
    end

    fclose(mbed);   %close connection (this should never be reached when using while(1), but included for completeness)
    
catch
    %in case of error or mbed being disconnected
    disp('Failed!');
    fclose(mbed);   %close connection to prevent COM port being lokced open
end 

When this is executed (assuming mbed is already churning out data), a plot window appears and is continually updated until mbed is disconnected. At this point, after the timeout period has elapsed, the read fails and the control is safely passed back to the Matlab command line by the catch block. This is certainly not very elegant, but does seem safe and reliable, though I'm sure it must be possible to do this better by sending synchronisation data back and forth across the link.

The code for just reading in the data from mbed into a variable is only a few lines long, the majority of this code is concerned with formatting and displaying the data. Using fscanf the data can be automatically converted from the string receieved back into seperate variables using (I think!) exactly the same syntax as was used in printf on mbed to put it into a string in the first place. The actual important bits of code for doing things are just:

mbed = serial('COM4', ...
                  'BaudRate', 9600, ...
                  'Parity', 'none', ...
                  'DataBits', 8, ...
                  'StopBits', 1);
             
fopen(mbed);
values = fscanf(mbed, '%f,%f,%f');
	
fclose(mbed);

There is also an fprintf function which can be used to write data back to mbed over the same serial connection using the same syntax, though I've not played with this yet.

Reference


All wikipages