Arduino to Matlab – Read in sensor data!

Posted by Erin, the RobotGrrl on Friday, January 15th, 2010

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!

Posted in: Programming, Projects, School.
Tags: , , , , , ,

15 Responses to “Arduino to Matlab – Read in sensor data!”

  1. boolscott Says:

    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?

  2. Send Arduino data to Matlab | Embedded projects from around the web Says:

    [...] Here you can find simple and fast asynchronous Arduino to Matlab communication sources. It can be handy for fast sensor data displaying in convenient graph and even do some analysis. [...]

  3. Joe Lotz Says:

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

  4. Seb Says:

    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)

  5. boolscott Says:

    Thanks Seb

  6. SAMMOR Says:

    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

  7. wwn Says:

    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?

  8. Nuclearrambo Says:

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

    Thank you very much.

  9. fremond Says:

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

  10. fremond Says:

    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?

  11. Dustyn Roberts Says:

    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?

  12. Giampy Says:

    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)

  13. Erin, the RobotGrrl Says:

    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! :)

  14. fremond Says:

    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?

  15. fremond Says:

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

Leave a Reply