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

Serial Communication btwn Matlab and Arduino

  1. Jul 22, 2011 #1
    I'm trying to setup serial communication between Matlab and an Arduino. As a test I have a logical input to the Arduino (it can be either 0 or 1). I then want to pass the value of the input to Matlab and display it. Here's the Arduino code I have:
    Code (Text):

    void setup() {
      pinMode(5, INPUT);

    void loop() {
      int NPleft = digitalRead(5);
    Here's the Matlab code:
    Code (Text):

    clear all
    s1 = serial('COM3');    % define serial port
    s1.BaudRate=9600;               % define baud rate
    I want Matlab to check the value being sent to it serially every second. What ends up happening is it just displays the first value it gets over and over again. So if the first value of the input is 1, it keeps displaying 1 over and over again regardless if the input goes back to 0. What am I doing wrong?
  2. jcsd
  3. Jul 26, 2011 #2


    User Avatar
    Science Advisor

    Can you try with more simple serial output, like the Hello World program in this Arduino serial tutorial?

    You might want to use a terminal program like Teraterm before moving onto MATLAB (go for the open-source one, not the one from Ayera):

    Within MATLAB, I believe that the serial buffer size is 512 bytes, and you should be able to use the 1-second polling as long as you don't have a buffer overrun (receiving more than 512 bytes). You may want to use the BytesAvailable and/or TransferStatus along with a loop to print out new values as they're received (more documentation under the Reading Data section):
    http://www.mathworks.com/help/techdoc/matlab_external/f62852.html [Broken]

    Good luck!
    Last edited by a moderator: May 5, 2017
  4. Jul 26, 2011 #3
    try sending in a header, then read the next byte, use the function fread() not fscanf(). fread() reads one byte at a time. For example

    Code (Text):

    ser = serial('COM4', 'BaudRate', 38400);
    one_byte = fread(ser, 1, 'int8'); %reads exactly one byte
    two_bytes = fread(ser, 1, 'int16'); %read exactly two byes and converts them to 1 integer (why?)
    Last edited: Jul 26, 2011
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook