Wiring and Matlab

From Wiring

Jump to: navigation, search

By Luis Arias and Martha Maldonado

This tutorial introduces the basic interfacing between the Wiring hardware and Matlab . Wiring sends the values from an analog sensor (in this case a potentiometer) through the serial port and Matlab reads the values and plots a graph that shows the behavior of the sensor during a time lapse.

*Remember that an analog sensor takes values ​​ranging from 0 to 1023.

Contents

Wiring Communication to Matlab

Setup Diagram

Potentiometer.png

Wiring Code

/**
* Simple Matlab comunication example
*
* Communicates Wiring with Matlab sending sensor values through the
* serial port. Matlab reads the values and plots a graph.
*/

int sensorA;

void setup()
{
  Serial.begin(9600);  // sets the serial port to 9600
}

void loop()
{
  sensorA = analogRead(0);
  Serial.println(sensorA); 
  delay(20);                      // wait 20ms for next reading
}

Matlab Code

% Simple Wiring - Matlab comunication example
% by Luis Arias and Martha Maldonado
% 
% Communicates Wiring with Matlab sending sensor values through the
% serial port. Matlab reads the values and plots a graph.

%Deletes previous serial port objects. Change the port "COM9"
%according to your serial port on Wiring.
delete(instrfind('Port','COM9'));

%Creates a serial port object with the specified speed of data transmission
%and specifies the reading in each line break
serObj = serial('COM9','BaudRate',9600,'Terminator','CR/LF');

%Opens the port to connect the serial port object to the device
fopen(serObj);

%Creates the figure and defines the properties of it
figure('Name','Matlab-Wiring Communication');
axes('XLim',[0 60],'YLim',[0 1023]);    %Axis limits
title('Real Time Matlab-Wiring Communication')
ylabel('Sensor Value')
xlabel('Approximate Time (s)')     
grid on
hold on

%Creates a line object with no default x and y values, the line color is
%blue and width is 2 mm
l = line(nan,nan,'Color','b','LineWidth',2);

%Initialize variables to plot the graph
sensorVal = zeros(1,1000);  %Array of zeros of 1000 size
i = 1;

%Generates the graph until 60 seconds
 for i=1:600
    %Serial port reading
    reading = fscanf(serObj,'%d,%d')';
    %Assign the value of the reading to the sensorVal i position
    sensorVal(i)=reading(1);
    %Generates a row vector of i points linearly spaced between. Determines
    %the advancement of the graph at x axis.
    x = linspace(0,i/10,i);
    set(l,'YData',sensorVal(1:i),'XData',x);
    drawnow
end

%Cleans and deletes serial port objects
fclose(serObj);
delete(serObj);
clear serObj;

Matlab Output

The following image shows the graph generated by Matlab after changing the potentiometer values ​​over 1 minute.

Screenshot.JPG



Language: English  • Español
Personal tools