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 valuey = zeros(1,1000);%%delete(instrfind({Port'},{'COM3'}));%initiate COM Portpuerto_serial = serial ('COM3');puerto_serial.BaudRate = 9600;warning('off','MATLAB:serial:fscanf:unsuccessfulRead');fopen(puerto_serial);%counter of samplescontador_muestras=1;%initiate figure propertyfigure('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 sampleswhile contador_muestras <= numero_muestrasylim([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');drawnowcontador_muestras = contador_muestras+1;end%close portfclose(puerto_serial);delete(puerto_serial);clear all;end
Good luck!
0 comments:
Post a Comment