MATLAB Matlab and arduino: serial port connection

AI Thread Summary
To connect MATLAB to an Arduino via serial port, both the Arduino and MATLAB codes must match in settings such as baud rate, data bits, parity, and stop bits. The Arduino code initializes serial communication and sends the number 3, while the MATLAB code attempts to read this value. Users should ensure that the terminator settings are consistent, with suggestions to use 'CR' for compatibility. The discussion highlights confusion over using both fread() and fscanf() in MATLAB, prompting a need for clarification on their outputs. Proper synchronization of serial settings is crucial for accurate data retrieval.
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!
 
Physics news 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?
 

Similar threads

Back
Top