MATLAB Arduino Tutorial 2.0 - Serial Connection between Arduino to MATLAB ( Streaming value)

on Wednesday, May 14, 2014

In the previous post, I demonstrated how to exchange string value between Matlab and Arduino. It's very simple but effective to test the serial port communication. In this post, I will show you how to continuously stream value from analog read of arduino to Matlab plot.

Initially, I intend to post the source code for the MATLAB Arduino Tutorial 2 - Connecting and calibrating a 3-axis accelerometer but the code for this tutorial is so complex. The author blends many different MATLAB functions to the barebone of the code. I can't figure them out for now. I try to find another tutorial which tells a simple way to stream int value from arduino to MATLAB. It's in Spanish. Don't worry, it's easy to understand. The code is very clear.

Matlab+Arduino: Serial port communication [geekytheory.com]

In this video, the author graph the voltage of a potential meter measured by an analog pin of arduino, and graph it by Matlab continuously

Arduino code: read data from analog pin A3 every 100ms, send data to serialport. You can choose any pin.
 // the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A3);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(100);        // delay in between reads for stability
}
Matlab code: I commented in English
function Matlab_Arduino(numero_muestras)
close all;
clc;
%% matrix to store output value
y = zeros(1,1000);


%%delete(instrfind({Port'},{'COM3'}));
%initiate COM Port
puerto_serial = serial ('COM3');
puerto_serial.BaudRate = 9600;
warning('off','MATLAB:serial:fscanf:unsuccessfulRead');

fopen(puerto_serial);

%counter of samples
contador_muestras=1;

%initiate figure property
figure('Name','Serial comm')
title('SERIAL COMMUNICATION MATLAB ARDUINO');
xlabel('number mustra');
ylabel('Voltage');
grid on;
hold on;

%plot received value until counter samples reach number of prefer samples
while contador_muestras <= numero_muestras
    ylim([0 1024]);
    xlim([contador_muestras-20 contador_muestras+5]);
    valor_poten = fscanf(puerto_serial, '%d')';
    y(contador_muestras) = (valor_poten(1));
    plot(contador_muestras, y (contador_muestras),'X-r');
    drawnow
    contador_muestras = contador_muestras+1;
end
%close port
    fclose(puerto_serial);
    delete(puerto_serial);
    clear all;
    
end




Good luck!

0 comments:

Post a Comment