matlab and arduino: serial port connection

Discussion in 'Embedded Systems and Microcontrollers' started by lcr2139, Apr 8, 2013.

  1. lcr2139

    Thread Starter New Member

    Jul 26, 2012
    1
    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!
     
  2. tshuck

    Well-Known Member

    Oct 18, 2012
    3,531
    675
    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.
     
  3. Georacer

    Moderator

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

    Code ( (Unknown Language)):
    1. data=zeros(1000,3);
    2. for i=1:1:size(data,1)
    3.     data(i,:)=str2num(fgets(arduino));
    4.     if mod(i*100/size(data,1),10)==0
    5.         disp(['Progress ', num2str((i/size(data,1)*100)),'%'])
    6.     end
    7. end
    8.  
    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.
     
Loading...