If any of the info on this website was useful for your projects or made your head spin with creative ideas, and you would like to share a token of your appreciation- a donation would be massively appreciated!

Your donation will go to my Robotics Fund, straight towards more sensors, actuators, books, and journeys. It takes a lot to continue building these robots, and I’m really thankful of everyone who helps encourage me along the way.



“A wise robot once said to me through Serial.println- that robots teach us about ourselves.”

Arduino to Matlab – Read in sensor data!

Matlab is by far the best software I have ever seen when it comes to plotting data and showing it in a visual format. I figured it would be awesome if I could get Arduino and Matlab to work together!

EDIT JULY 4, 2011: Apparently if you add


as the very first line, it handles the serial object deletion issue! WOOT!

Here’s the code that I came up with that works reasonably fast. It doesn’t wait for the buffer to be filled to then store it to a variable. Here, it is asynchronous communication. ^_^

This is a basic screenshot of what you will get, minus the green stars.


Here is the code. Let me know if you use, it would be neat to see what everyone would come up with!
*Note: The code highlighting for Matlab was buggy, so the below is using C code highlighting. Once you paste it into Matlab, it will be fine.

  1. % Basic Arduino and Matlab
  2. % Communication with an external hardware device
  3. % ———————————————-
  4. %
  5. % Erin Kennedy
  6. % Jan. 18, 2010
  7. %
  10. clear all; clc; close all;
  13. % Trycatch is to prevent Matlab from crashing when the program is finished
  14. try
  17. % Initialize serial port
  18. s = serial(‘/dev/tty.usbserial-A4001lVG’);
  19. %set(s, ‘ Terminator’, ‘LF’); % Default terminator is \n
  20. set(s,‘BaudRate’, 9600);
  21. set(s,‘DataBits’, 8);
  22. set(s,‘StopBits’, 1);
  23. fopen(s);
  24. s.ReadAsyncMode = ‘continuous’;
  27. % Various variables
  28. numberOfDatas = 50;
  29. data = zeros(1, numberOfDatas);
  30. i = 1;
  33. % Main graph figure
  34. figure(1);
  35. hold on;
  36. title(‘Incomming Data from External Device’);
  37. xlabel(‘Data Number’);
  38. ylabel(‘Analog Voltage (0-1023)’);
  41. % Start asynchronous reading
  42. readasync(s);
  45. while(i<=numberOfDatas)  
  48.     % Get the data from the serial object
  49.     data(i) = fscanf(s, ‘%d’);
  51.     % Plot the data
  52.     figure(1);
  53.     plot(i, data(i), ‘m*’);
  55.     % Ensure there are always 10 tick marks on the graph
  56.     if(i>10)
  57.        xlim([i10 i]);
  58.        set(gca,‘xtick’,[i10 i9 i8 i7 i6 i5 i4 i3 i2 i1 i])
  59.     end
  61.     % Draw and flush
  62.     drawnow;
  64.     %Increment the counter
  65.     i=i+1;
  68. end
  71. % Give the external device some time…
  72. pause(3);
  74. return;
  76. catch
  78. % Some of these crash the program it depends. The serial port is left
  79. % open, which is not good.                                              
  80. stopasync(s);
  81. fclose(s); % bad
  82. %delete(s);
  83. %clear s;
  85. fprintf(1, ‘Sorry, you"re going to have to close out of Matlab to close the serial port\n);
  87. return
  89. end

The code for the Arduino is this:

  1. //
  2. // BubbleBoy -> Matlab
  3. // ——————-
  4. //
  5. // Read LDR data, print them to Serial (where Matlab will receive them)
  6. //
  8. int LDRpin = 0;
  10. void setup() {
  12.   Serial.begin(9600);
  13.   pinMode(LDRpin, INPUT);
  15. }
  17. void loop() {
  19.  int photocellReading = analogRead(LDRpin);
  21.  Serial.println(photocellReading, DEC);
  22.  delay(200);
  24. }

Enjoy, happy matlabbing!

26 CommentsLeave a Comment

  • boolscott

    7 years ago

    I’m used to specifying which serial port the program must use for Processing apps, is that done automatically here?

    Is that what the “s = serial(‘/dev/tty.usbserial-A4001lVG’);” is about?

  • Joe Lotz

    7 years ago

    Awesome! I can’t wait to try this tonight.

  • Seb

    7 years ago

    Awesome post, this was just what I was looking for – thank you! (Tho I’m using a PC, and to answer boolscott’s question, replace the contents of serial() with “COMX” where X is the number of your com port the Arduino is connected to)

  • boolscott

    7 years ago

    Thanks Seb


    6 years ago

    Hey Erin,
    Thank you for the code. Exactly what i need to build my signature verification project. Arduino to matlab communication
    I’ll let you know of my progress.

  • wwn

    6 years ago

    ihad error like this ??? Error: File: Serial.m Line: 45 Column: 1
    Illegal use of reserved keyword “catch”.??? Error: File: Serial.m Line: 45 Column: 1
    Illegal use of reserved keyword “catch”.
    can anyone help me?

  • Nuclearrambo

    6 years ago

    EXCELLENT ….you came to my rescue while i am building my pulse oximeter 😀

    Thank you very much.

  • fremond

    6 years ago

    hello Erin,

    you are a lifesaver..i am so glad i found this website..i got a few things that i wish you can help me with..

    1st) while i executed the matlab code this error came out:

    ??? Undefined function or method ‘training’ for input
    arguments of type ‘char’.

    may i ask for your help to enlighten me?

    i am really a newbie in matlab and also arduino..hope that someone can help me..

  • fremond

    6 years ago

    hello erin,

    i wish to ask how something..since i have connected my potentiometer to arduino board..does the code you share here can read the data from the potentiometer and plot graph?

  • Dustyn Roberts

    6 years ago

    Thanks for that! Now if I can only figure out a way to close the serial port without turning off Matlab…

    Also have you seen this?

    Have you ever tried 2-way communication, like controlling a motor while logging sensor data in Matlab?

  • Giampy

    6 years ago

    By the way, there is a free Matlab interface to Arduino, which you can download from here:

    This lets you control your Arduino board over USB from a MATLAB session, in either Windows, Mac or Linux. For example you can instantiate an Arduino object from MATLAB using:

    >> a=arduino(‘COM5′);

    and then do stuff like:

    >> av=a.analogRead(5);
    >> a.pinMode(13,’output’);
    >> a.digitalWrite(13,1);
    >> delete(a)

  • Erin, the RobotGrrl

    6 years ago

    Thanks Dustyn! I think my friend got the serial port to be able to close by declaring the port as a global variable (in that big window in the middle when you start MATLAB), and using that variable name throughout the code. 😀 It was a weird solution though, and only worked sometimes.

    I did indeed see that, but I wrote the above code before the Arduino toolkit came out hahaha ;D

    Thanks for the comment, Giampy! :)

  • fremond

    6 years ago

    hi..thanks for the source code..

    can i ask is there any permanent solution that we do not need to close off matlab everytime after we obtain the sensor data from arduino to matlab?

  • fremond

    6 years ago

    can someone teach me how to program the arduino to receive data from two potentiometer and plot them using matlab??

  • Karrie Barbati

    4 years ago

    It is best to look for for a pre developed software bundle specially if you have no specialized understanding with regards to unlocking telephones. This is due to the fact these are generally the safest offers to use and will offer you a amount of resources that will support to make unlocking your Iphone less difficult.

  • Hugo

    4 years ago

    Good evening,thanks a lot for your tuturial, i have a problem, I want to send an array of pixels to matlab and then display the image in matlab, it is possible?

    Example: I have an array in arduino like this:

    = Array [23, 45, 34, 234, 10, 4, 200, 100;
    45,34,35, ….];

    and I want to send it to matlab and then make imshow this array. How to do this automatically? I do not know much about matlab. Someone can help me. In arduino I’m doing serial.write or Serial.print.

    Thank you for the attention and the help

  • sneha

    4 years ago

    hey i have a doubt about how to plot the output values of aurdino in matlab as a graph….both digital and real time graph??

  • GT

    4 years ago


    Thanks :)

  • enieruchomosci3170

    4 years ago

    hey there and thank you for your information – I have definitely picked up anything new from right here. I did however expertise some technical issues using this site, as I experienced to reload the web site lots of times previous to I could get it to load properly. nieruchomoscie I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will very frequently affect your placement in google and could damage your high quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my email and can look out for much more of your respective exciting content. Make sure you update this again very soon..

  • Shashank Sunil

    4 years ago

    I am trying matlab to turn the led light in arduino, I was wondering if anyone knew the data type of the serial information sent by the serial monitor to the arduino.
    So far I have the following code in matlab
    fwrite(s,’1′, ‘uint8′);
    %a= fscan(s);
    catch err
    disp(‘dint work’)
    I know that arduino is receiving some signal from matlab , but the arduino is not able to understand it !!!

    Arduino code:
    int ledpin=13;
    void setup ()

    pinMode(ledpin, OUTPUT);

    void loop()
    while (Serial.available()==0);
    int val = – ‘0’;

    if (val==1)
    else if (val==0)



    The ledpin 13 light blinks once or twice when I run the matlab script.

    any help , would be appreciated

  • archana

    4 years ago

    some plz help me how to interface arduino with matlab.
    i want to read data from arduino into matlab .

  • roshan

    4 years ago

    is it possible to read two or three analog inputs in arduino program and to plot graphs based on three analog inputs in Matlab.if it is possible please send me the code.i am using single arduino mega board and usb connected to system.i want to read five potentiometers at a time and run to see the how graph varies.

  • Ken

    3 years ago

    Thanks very much for the code Eric. For the port closing/Matlab restart issue, I’ve use this and is working so far (which no longer require / ):

    %% Closing port
    clear s
    % com is still open, you will not be able to use it with other
    % objects or programs.
    snew = instrfind;

  • chfakht

    2 years ago

    Hello ,
    i need some ressource for real time plotting of MPU6050 ((gyroscope + accelerometer ) ) or MPU9051 datas in matlab

    So that i can use it for tracking in real time

    any help here will be appreciated

  • corburterilio

    4 months ago

    Definitely, what a splendid website and enlightening posts, I surely will bookmark your site.All the Best!

Trackbacks for this post

  1. Send Arduino data to Matlab | Embedded projects from around the web

Leave a CommentPlease be polite. We appreciate that.

Your Comment