{"id":363,"date":"2012-02-27T12:43:24","date_gmt":"2012-02-27T17:43:24","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=363"},"modified":"2022-05-16T09:05:23","modified_gmt":"2022-05-16T13:05:23","slug":"controlling-rgb-led-via-potentiometer-using-arduino-and-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2012\/02\/27\/controlling-rgb-led-via-potentiometer-using-arduino-and-matlab\/","title":{"rendered":"Controlling RGB LED via Potentiometer Using Arduino and MATLAB"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>I'd like to introduce this week's guest blogger <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/29271\">Ankit Desai<\/a>. Ankit works for the Test &amp; Measurement team here at The MathWorks. Ankit has previously <a href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/05\/27\/transferring-data-between-two-computers-using-matlab\/\">written<\/a> about transferring data between two computers using MATLAB. In this post he will talk about using MATLAB Support Package\r\n         for Arduino.\r\n      <\/p>\r\n      <p>Arduino is rapidly growing as a prototyping platform for students, hobbyists and engineers. The <a href=\"https:\/\/www.mathworks.com\/hardware-support\/arduino-matlab.html\">MATLAB Support Package for Arduino<\/a> allows you to work with Arduino boards, for example UNO and Duemilanove, and allows for interactive development and debugging. The support package works on all platforms supported by MATLAB and\r\n         does not require any additional toolboxes.\r\n      <\/p>\r\n      <p>MATLAB Support Package for Arduino uses the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/matlab_external\/f105659.html\">Serial Port interface<\/a> in MATLAB for communication with the Arduino board.\r\n      <\/p>\r\n      <p>I recently got my hands on the <a href=\"http:\/\/www.sparkfun.com\/products\/10173\">Arduino Inventor Kit<\/a> from <a href=\"http:\/\/www.sparkfun.com\/\">Sparkfun<\/a>, and together with <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/answers\/contributors\/1020339-onomitra-ghosh\">Onomitra Ghosh<\/a>, decided to build a small project using the kit and <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/32374-legacy-matlab-and-simulink-support-for-arduino\">MATLAB Support Package for Arduino<\/a>. I decided to start with a simple project of&nbsp;controlling&nbsp;the color of an RGB LED via a potentiometer.\r\n      <\/p>\r\n      <p>The entire project was divided into three phases:<\/p>\r\n      <div>\r\n         <ol>\r\n            <li>Setting up the Arduino and Breadboard<\/li>\r\n            <li>Setting up MATLAB and Support Package<\/li>\r\n            <li>Writing MATLAB Code<\/li>\r\n         <\/ol>\r\n      <\/div>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Setting up the Arduino and Breadboard<\/a><\/li>\r\n         <li><a href=\"#2\">Setting up MATLAB and Support Package<\/a><\/li>\r\n         <li><a href=\"#3\">Writing MATLAB Code<\/a><\/li>\r\n         <li><a href=\"#5\">Conclusion<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Setting up the Arduino and Breadboard<a name=\"1\"><\/a><\/h3>\r\n   <p>Depending on the platform you are working on, <a href=\"http:\/\/arduino.cc\/en\/Guide\/HomePage\">Arduino's website<\/a> has a detailed set of instructions for setting up the Arduino IDE and connecting the Arduino board. Once the setup was complete,\r\n      I worked on the breadboard to have the setup similar to <a title=\"http:\/\/www.oomlout.com\/a\/products\/ardx\/circ-08\/\">CIRC-08<\/a> from the Sparkfun's Arduino Inventor Kit, except that I used an RGB LED instead of Green LED and hence instead of using just\r\n      <b>pin 9<\/b> - I used <b>pins 9, 10 and 11<\/b>.\r\n   <\/p>\r\n   <p>At this stage the Arduino board and rest of the components were ready.<\/p>\r\n   <h3>Setting up MATLAB and Support Package<a name=\"2\"><\/a><\/h3>\r\n   <p>MATLAB support package for Arduino comes with a server program <b>adiosrv.pde<\/b> that can be downloaded on the Arduino board. Once downloaded, the <b>adiosrv.pde<\/b> will:\r\n   <\/p>\r\n   <div>\r\n      <ol>\r\n         <li>Wait and listen for MATLAB commands<\/li>\r\n         <li>Upon receiving MATLAB command, execute and return the result<\/li>\r\n      <\/ol>\r\n   <\/div>\r\n   <p>The steps I performed to write\/download the server program to Arduino board were as following:<\/p>\r\n   <div>\r\n      <ol>\r\n         <li>Open Arduino IDE<\/li>\r\n         <li>Select the adiosrv.pde file by navigating through File &gt; Open in the IDE<\/li>\r\n         <li>Click the Upload button<\/li>\r\n      <\/ol>\r\n   <\/div>\r\n   <p>I was now ready to code in MATLAB.<\/p>\r\n   <h3>Writing MATLAB Code<a name=\"3\"><\/a><\/h3>\r\n   <p>MATLAB support package for Arduino provides a very easy to use function set to perform basic operations like analog read,\r\n      analog write, digital read and digital write.\r\n   <\/p>\r\n   <p>For the purpose of this example, I followed the following sequence:<\/p>\r\n   <div>\r\n      <ol>\r\n         <li>Read a value from analog input <b>pin 0<\/b>, where I connected the potentiometer\r\n         <\/li>\r\n         <li>Calculate the intensity for R,G and B colors of the LED based on the value read<\/li>\r\n         <li>Write calculated R, G and B intensity to analog output <b>pins 9, 10 and 11<\/b><\/li>\r\n         <li>Loop the sequence for predetermined amount of time<\/li>\r\n      <\/ol>\r\n   <\/div>\r\n   <p>In MATLAB the above sequence looks like:<\/p><pre> % Connect to the board\r\n a = arduino('COM8');<\/pre><pre> a.pinMode(9,'output');\r\n a.pinMode(10,'output');\r\n a.pinMode(11,'output');<\/pre><pre> % Start the timer now\r\n tic;<\/pre><pre> while toc\/60 &lt; 1 % Run for 1 minute.\r\n % Read analog input from analog pin 0\r\n % The value returned is between 0 and 1023\r\n     sensorValue = a.analogRead(0);<\/pre><pre> % For potentiometer value from 0 to 511, we will fade LED from red to\r\n % green keeping blue at constant 0.\r\n    if 0 &lt;= sensorValue &amp;&amp; sensorValue &lt; 512\r\n       greenIntensity = floor(sensorValue\/2.0);\r\n       redIntensity   = 255-greenIntensity;\r\n       blueIntensity  = 0;\r\n    else\r\n % For potentiometer value from 511 to 1023, we will fade LED from\r\n % green to blue keeping red at constant 0.\r\n       blueIntensity   = floor(sensorValue\/2.0) - 256;\r\n       greenIntensity  = 255 - blueIntensity;\r\n       redIntensity    = 0;\r\n    end<\/pre><pre> % Write the intensity to analog output pins\r\n    a.analogWrite(9,redIntensity);\r\n    a.analogWrite(10,greenIntensity);\r\n    a.analogWrite(11,blueIntensity);\r\n end<\/pre><pre> % Close session\r\n delete(a);\r\n clear a;<\/pre><h3>Conclusion<a name=\"5\"><\/a><\/h3>\r\n\r\n   <p>So why, you might ask, do I need MATLAB when I can just code it in Arduino IDE? The simple answer is - interactive development\r\n      and debugging capabilities.\r\n   <\/p>\r\n   <p>While working on this project, there were so many instances where I wanted to see the values returned from the potentiometer\r\n      as I was turning the knob or quickly set the RGB value of the LED. Using the Arduino IDE, I would have updated the code, re-compiled\r\n      it and uploaded the code to the board before I can see the updates in effect. With MATLAB support package, I was able to just\r\n      tweak the settings on the fly without any extra step.\r\n   <\/p>\r\n   <p>Make sure you check out the webinar: Learning Basic Mechatronics Concepts Using the Arduino Board and MATLAB, to learn more about Analog and Digital I\/O as well as DC, Servo and Stepper motor control.\r\n   <\/p>\r\n   <p>Have you used\/wanted to use Arduino for any cool projects?\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_a8c08779e311408e909212426d411690() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='a8c08779e311408e909212426d411690 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' a8c08779e311408e909212426d411690';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Ankit Desai';\r\n        copyright = 'Copyright 2012 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_a8c08779e311408e909212426d411690()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.13<br><\/p>\r\n<\/div>\r\n<!--\r\na8c08779e311408e909212426d411690 ##### SOURCE BEGIN #####\r\n%% Controlling RGB LED via Potentiometer Using Arduino and MATLAB\r\n% \r\n% I'd like to introduce this week's guest blogger\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/29271 Ankit\r\n% Desai>. Ankit works for the Test & Measurement team here at The\r\n% MathWorks. Ankit has previously\r\n% <https:\/\/blogs.mathworks.com\/loren\/2011\/05\/27\/transferring-data-between-two-computers-using-matlab\/\r\n% written> about transferring data between two computers using MATLAB. In\r\n% this post he will talk about using MATLAB Support Package for Arduino. \r\n% \r\n% <http:\/\/arduino.cc\/en Arduino> is rapidly growing as a prototyping\r\n% platform for students, hobbyists and engineers. The\r\n% <https:\/\/www.mathworks.com\/hardware-support\/arduino-matlab.html\r\n% MATLAB Support Package for Arduino> allows you to work with Arduino\r\n% boards, for example <http:\/\/www.arduino.cc\/en\/Main\/arduinoBoardUno UNO>\r\n% and <http:\/\/arduino.cc\/en\/Main\/arduinoBoardDuemilanove Duemilanove>, and\r\n% allows for interactive development and debugging. The support package\r\n% works on all platforms supported by MATLAB and does not require any\r\n% additional toolboxes.\r\n%\r\n% MATLAB Support Package for Arduino uses the\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/matlab_external\/f105659.html\r\n% Serial Port interface> in MATLAB for communication with the Arduino\r\n% board.   \r\n% \r\n% I recently got my hands on the <http:\/\/www.sparkfun.com\/products\/10173\r\n% Arduino Inventor Kit> from <http:\/\/www.sparkfun.com\/ Sparkfun>, and\r\n% together with\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/answers\/contributors\/1020339-onomitra-ghosh\r\n% Onomitra Ghosh>, decided to build a small project using the kit and\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/32374-legacy-matlab-and-simulink-support-for-arduino MATLAB Support\r\n% Package for Arduino>. I decided to start with a simple project\r\n% of\u00c2\u00a0controlling\u00c2\u00a0the color of an RGB LED via a potentiometer. \r\n%\r\n% The entire project was divided into three phases:\r\n% \r\n% # Setting up the Arduino and Breadboard\r\n% # Setting up MATLAB and Support Package\r\n% # Writing MATLAB Code\r\n%\r\n%% Setting up the Arduino and Breadboard\r\n% \r\n% Depending on the platform you are working\r\n% on, <http:\/\/arduino.cc\/en\/Guide\/HomePage Arduino's website> has a detailed set \r\n% of instructions for setting up the Arduino IDE and connecting the Arduino\r\n% board. Once the setup was complete, I worked on the breadboard to have\r\n% the setup similar to <http:\/\/www.oomlout.com\/a\/products\/ardx\/circ-08\/\r\n% CIRC-08> from the Sparkfun's Arduino Inventor Kit, except that I used an\r\n% RGB LED instead of Green LED and hence instead of using just *pin 9* - I\r\n% used *pins 9, 10 and 11*.\r\n%\r\n% At this stage the Arduino board and rest of the components were ready.\r\n%\r\n%% Setting up MATLAB and Support Package\r\n% \r\n% MATLAB support package for Arduino comes with a server program\r\n% *adiosrv.pde* that can be downloaded on the Arduino board. Once\r\n% downloaded, the *adiosrv.pde* will: \r\n% \r\n% # Wait and listen for MATLAB commands\r\n% # Upon receiving MATLAB command, execute and return the result\r\n% \r\n% The steps I performed to write\/download the server program to Arduino\r\n% board were as following: \r\n% \r\n% # Open Arduino IDE\r\n% # Select the adiosrv.pde file by navigating through File > Open in the IDE\r\n% # Click the Upload button\r\n% \r\n% I was now ready to code in MATLAB.\r\n% \r\n%% Writing MATLAB Code\r\n% \r\n% MATLAB support package for Arduino provides a very easy to use function set to\r\n% perform basic operations like analog read, analog write, digital read and\r\n% digital write. \r\n% \r\n% For the purpose of this example, I followed the following sequence:\r\n% \r\n% # Read a value from analog input *pin 0*, where I connected the potentiometer\r\n% # Calculate the intensity for R,G and B colors of the LED based on the value read\r\n% # Write calculated R, G and B intensity to analog output *pins 9, 10 and\r\n% 11*\r\n% # Loop the sequence for predetermined amount of time\r\n% \r\n% In MATLAB the above sequence looks like:\r\n%%\r\n%\r\n%   % Connect to the board\r\n%   a = arduino('COM8');\r\n%\r\n%   a.pinMode(9,'output');\r\n%   a.pinMode(10,'output');\r\n%   a.pinMode(11,'output');\r\n% \r\n%   % Start the timer now\r\n%   tic;\r\n%\r\n%   while toc\/60 < 1 % Run for 1 minute.\r\n%   % Read analog input from analog pin 0\r\n%   % The value returned is between 0 and 1023\r\n%       sensorValue = a.analogRead(0);\r\n%   \r\n%   % For potentiometer value from 0 to 511, we will fade LED from red to\r\n%   % green keeping blue at constant 0. \r\n%      if 0 <= sensorValue && sensorValue < 512\r\n%         greenIntensity = floor(sensorValue\/2.0);\r\n%         redIntensity   = 255-greenIntensity;\r\n%         blueIntensity  = 0;\r\n%      else\r\n%   % For potentiometer value from 511 to 1023, we will fade LED from\r\n%   % green to blue keeping red at constant 0.\r\n%         blueIntensity   = floor(sensorValue\/2.0) - 256;\r\n%         greenIntensity  = 255 - blueIntensity;\r\n%         redIntensity    = 0;\r\n%      end\r\n%\r\n%   % Write the intensity to analog output pins\r\n%      a.analogWrite(9,redIntensity);\r\n%      a.analogWrite(10,greenIntensity);\r\n%      a.analogWrite(11,blueIntensity);\r\n%   end\r\n% \r\n%   % Close session\r\n%   delete(a);\r\n%   clear a;\r\n\r\n%% Conclusion\r\n% \r\n% <html>\r\n% <iframe loading=\"lazy\" width=\"560\" height=\"315\"\r\n% src=\"https:\/\/www.youtube.com\/embed\/VsKtNoPUs0c\" frameborder=\"0\"><\/iframe>\r\n% <\/html>\r\n%\r\n% So why, you might ask, do I need MATLAB when I can just code it in\r\n% Arduino IDE? The simple answer is - interactive development and\r\n% debugging capabilities. \r\n% \r\n% While working on this project, there were so many instances where I\r\n% wanted to see the values returned from the potentiometer as I was turning\r\n% the knob or quickly set the RGB value of the LED. Using the Arduino\r\n% IDE, I would have updated the code, re-compiled it and uploaded\r\n% the code to the board before I can see the updates in effect. With MATLAB\r\n% support package, I was able to just tweak the settings on the fly without any\r\n% extra step. \r\n% \r\n% Make sure you check out the webinar:\r\n% <https:\/\/www.mathworks.com\/company\/events\/webinars\/wbnr43537.html Learning\r\n% Basic Mechatronics Concepts Using the Arduino Board and MATLAB>, to learn\r\n% more about Analog and Digital I\/O as well as DC, Servo and Stepper motor\r\n% control.  \r\n%\r\n% Have you used\/wanted to use Arduino for any cool projects? If so, please\r\n% feel free to share your project details in\r\n% <https:\/\/blogs.mathworks.com\/?p=363#respond here>.\r\n##### SOURCE END ##### a8c08779e311408e909212426d411690\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      I'd like to introduce this week's guest blogger Ankit Desai. Ankit works for the Test &amp; Measurement team here at The MathWorks. Ankit has previously written about transferring data... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2012\/02\/27\/controlling-rgb-led-via-potentiometer-using-arduino-and-matlab\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[42,49],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/363"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=363"}],"version-history":[{"count":9,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/363\/revisions"}],"predecessor-version":[{"id":5171,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/363\/revisions\/5171"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=363"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=363"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=363"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}