Greetings!

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.


USD


CAD

“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

delete(instrfindall);

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.

matlabscreenshot

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. %
  8.  
  9.  
  10. clear all; clc; close all;
  11.  
  12.  
  13. % Try-catch is to prevent Matlab from crashing when the program is finished
  14. try
  15.  
  16.    
  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’;
  25.  
  26.  
  27. % Various variables
  28. numberOfDatas = 50;
  29. data = zeros(1, numberOfDatas);
  30. i = 1;
  31.  
  32.  
  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)’);
  39.  
  40.  
  41. % Start asynchronous reading
  42. readasync(s);
  43.  
  44.  
  45. while(i<=numberOfDatas)  
  46.    
  47.    
  48.     % Get the data from the serial object
  49.     data(i) = fscanf(s, ‘%d’);
  50.    
  51.     % Plot the data
  52.     figure(1);
  53.     plot(i, data(i), ‘m*’);
  54.    
  55.     % Ensure there are always 10 tick marks on the graph
  56.     if(i>10)
  57.        xlim([i-10 i]);
  58.        set(gca,‘xtick’,[i-10 i-9 i-8 i-7 i-6 i-5 i-4 i-3 i-2 i-1 i])
  59.     end
  60.    
  61.     % Draw and flush
  62.     drawnow;
  63.    
  64.     %Increment the counter
  65.     i=i+1;
  66.    
  67.    
  68. end
  69.  
  70.  
  71. % Give the external device some time…
  72. pause(3);
  73.  
  74. return;
  75.  
  76. catch
  77.  
  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;
  84.  
  85. fprintf(1, ‘Sorry, you"re going to have to close out of Matlab to close the serial port\n);
  86.  
  87. return
  88.  
  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. //
  7.  
  8. int LDRpin = 0;
  9.  
  10. void setup() {
  11.  
  12.   Serial.begin(9600);
  13.   pinMode(LDRpin, INPUT);
  14.  
  15. }
  16.  
  17. void loop() {
  18.  
  19.  int photocellReading = analogRead(LDRpin);
  20.  
  21.  Serial.println(photocellReading, DEC);
  22.  delay(200);
  23.  
  24. }

Enjoy, happy matlabbing!

24 CommentsLeave a Comment


  • boolscott

    5 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

    5 years ago

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

  • Seb

    5 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

    4 years ago

    Thanks Seb

  • SAMMOR

    4 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.
    Sam

  • wwn

    4 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

    4 years ago

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

    Thank you very much.

  • fremond

    3 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

    3 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

    3 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?
    http://www.mathworks.com/matlabcentral/fileexchange/27843

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

  • Giampy

    3 years ago

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

    http://www.mathworks.com/academia/arduino-software/arduino-matlab.html

    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

    3 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. :D 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

    3 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

    3 years ago

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

  • Karrie Barbati

    2 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

    2 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

    2 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

    1 year ago

    AMAZING!

    Thanks :)

  • enieruchomosci3170

    1 year 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

    1 year ago

    Hey,
    Hi,
    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
    clear;
    s=serial(‘com3′);
    fopen(s);
    try
    fwrite(s,’1′, ‘uint8′);
    %a= fscan(s);
    fclose(s);
    catch err
    fclose(s);
    disp(‘dint work’)
    end
    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 ()
    {
    Serial.begin(9600);

    pinMode(ledpin, OUTPUT);
    }

    void loop()
    {
    while (Serial.available()==0);
    int val = Serial.read() – ’0′;

    if (val==1)
    {
    digitalWrite(ledpin,HIGH);
    }
    else if (val==0)
    {
    digitalWrite(ledpin,LOW);
    }

    Serial.println(val);

    }

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

    any help , would be appreciated
    thanks

  • archana

    1 year ago

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

  • roshan

    1 year 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.
    Thanks

  • Ken

    10 months 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
    stopasync(s);
    clear s
    % com is still open, you will not be able to use it with other
    % objects or programs.
    snew = instrfind;
    delete(snew);

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