MATLAB Arduino Tutorial 1 - Serial Connection between Arduino to MATLAB to USB

on Wednesday, May 14, 2014
The Matlab Arduino team created awesome tutorial on how to connect matlab with arduino through serial port. They provide these tutorials as a guidance for those who want to do similar things. Source code is not provided. I think it would be helpful to publish the code for those who want to try. I will also comment about some pitfall that I went through when I follow these videos.

My arduino code:
The original video doesn't show the arduino code in the loop portion. I put a digitalWrite for pin 13 as a confirmation for the successful connection, ie pin 13 will lit up after a serial connection is set up successfully between arduino and Matlab:

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Serial.println('a');
  char a = 'b';
  while (a != 'a')
  {
    a = Serial.read();
 
  }

}
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(13,HIGH);
}

Matlab code
I use the same code as the video. IMPORTANT: you must save this code as a setupSerial.m file in the same folder before executing the function:
function[s,flag] = setupSerial(comPort)
flag = 1;
s = serial(comPort);
set(s,'DataBits',8);
set(s,'StopBits',1);
set(s,'BaudRate', 9600);
set(s,'Parity', 'none');
fopen(s);
a = 'b';
while (a~='a')
        a = fread(s,1,'uchar');
end
if (a=='a')
    disp('serial read');
end
fprintf(s,'%c','a');
mbox = msgbox('Serial Comm setup.'); uiwait(mbox);
fscanf(s,'%u');
end



0 comments:

Post a Comment