Matlab and arduino: serial port connection

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 6K views
lcr2139
Messages
58
Reaction score
0
Hello, I am trying to hook up MATLAB to my arduino. I am trying to write a number to the serial port in the arduino IDE and retrieving the same number in the MATLAB IDE. My arduino code is:

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

void loop() {

if (Serial.available()){
Serial.println(3);

delay(100); // delay in between reads for stability
}
}


And my MATLAB code looks like:

%s = serial('COM9');
s = serial ( 'COM9' , 'BaudRate' , 9600, 'terminator' , 'CR' );
%set(s,'BaudRate',4800);
fopen(s);

fprintf(s,'*IDN?')
fread(s)
disp(s)
out = fscanf(s);
fclose(s)
delete(s)
clear s

and the MATLAB output looks like:

10
51
13
10
51
13
10
51
13

How can I change this so only "3" comes out?
Thanks!
 
on Phys.org
Double check that you have the right parity and numbers of stop bits.
 
Sorry, I'm pretty new at this. What are parity and numbers of stop bits?
 
In http://home.iitb.ac.in/~rahul./ITSP/serial_comm_matlab.pdf the guy uses LF for the terminator. Try it.

J.
 
LF gives a Terminator error so I have to use CR.
 
Okay, then try the following

Arduino

Code:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600,SERIAL_8N1);
}

void loop() {
  if (Serial.available()){
    Serial.println(3);
    delay(100); // delay in between reads for stability
    }
}

On the Matlab side:

Code:
s = serial ( 'COM9' , 'BaudRate' , 9600, 'DataBits', 8, 'Parity', 'none', 'StopBits', 1, 'terminator' , 'CR' );
fopen(s);
fprintf(s,'*IDN?')
fread(s)
disp(s)
out = fscanf(s);
fclose(s)
delete(s)
clear s

This will make sure that everything serial is set the same on both ends of the cable.

Also, something I have some difficulties understanding: you are using fread() and fscanf() in the same run. Why? What's the content of the variable out?