Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab and arduino: serial port connection

  1. Apr 8, 2013 #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!
     
  2. jcsd
  3. Apr 8, 2013 #2
    Double check that you have the right parity and numbers of stop bits.
     
  4. Apr 8, 2013 #3
    Sorry, I'm pretty new at this. What are parity and numbers of stop bits?
     
  5. Apr 9, 2013 #4
    In this the guy uses LF for the terminator. Try it.

    J.
     
  6. Apr 9, 2013 #5
    LF gives a Terminator error so I have to use CR.
     
  7. Apr 10, 2013 #6
    Okay, then try the following

    Arduino

    Code (Text):

    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 (Text):

    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?
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Matlab and arduino: serial port connection
Loading...