matlab and arduino: serial port connection

Thread Starter

lcr2139

Joined Jul 26, 2012
1
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!
 

tshuck

Joined Oct 18, 2012
3,534
You can't. at least not on the MATLAB side. MATLAB is displaying the ASCII values that your Arduino is outputting. Look at asciitable.com for clarification on the numbers sent, note they are in hex.

You can either get MATLAB to ignore the other stuff, or only output the number from the Arduino.

The fprintf will output formatted text, try using a serial write or something like that, not too familiar with Arduino to help you on the exact command.
 

Georacer

Joined Nov 25, 2009
5,182
This is a snippet of code of how I read 1000 lines of three values each, from Arduino to Matlab.

Rich (BB code):
data=zeros(1000,3);
for i=1:1:size(data,1)
    data(i,:)=str2num(fgets(arduino));
    if mod(i*100/size(data,1),10)==0
        disp(['Progress ', num2str((i/size(data,1)*100)),'%'])
    end
end
I write them in Arduino with Serial.print and read them with fgets in Matlab and then use str2num.

Ask further if you have more questions.
 
Top