<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Troniquices4en</title>
	<atom:link href="http://troniquices4en.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://troniquices4en.wordpress.com</link>
	<description>Ramblings of an Engineer</description>
	<lastBuildDate>Sun, 17 Jul 2011 22:54:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='troniquices4en.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Troniquices4en</title>
		<link>http://troniquices4en.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://troniquices4en.wordpress.com/osd.xml" title="Troniquices4en" />
	<atom:link rel='hub' href='http://troniquices4en.wordpress.com/?pushpress=hub'/>
		<item>
		<title>How to do several things at the same time</title>
		<link>http://troniquices4en.wordpress.com/2011/06/27/how-to-do-several-things-at-the-same-time/</link>
		<comments>http://troniquices4en.wordpress.com/2011/06/27/how-to-do-several-things-at-the-same-time/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 15:30:18 +0000</pubDate>
		<dc:creator>Njay</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[embedded]]></category>
		<category><![CDATA[multitasking]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://troniquices4en.wordpress.com/?p=5</guid>
		<description><![CDATA[Nope, it&#8217;s not an article on time management ! Sometimes I see people around pushing hard on their brains about &#8220;how to do several things at the same time&#8221; in an Arduino or any other microcontroller board. Sometimes they even start thinking about threads and operating systems, but in such small machines and with newbie [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=troniquices4en.wordpress.com&amp;blog=24573447&amp;post=5&amp;subd=troniquices4en&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Nope, it&#8217;s not an article on time management <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ! Sometimes I see people around pushing hard on their brains about &#8220;how to do several things at the same time&#8221; in an Arduino or any other microcontroller board. Sometimes they even start thinking about <em>threads</em> and <em>operating systems</em>, but in such small machines and with newbie programmers, the best thing to do really is to stay away from the complexity of preemptive multitask / time sharing systems and <em>synchronization</em> theory. But then, is there any programming method adequate to resource-scarce machines and easy to use? There is indeed. Just keep on reading the article <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><span id="more-5"></span> A multitasking system is complex for machines with limited resources like an Arduino and complex for newbies, so I recommend (and in fact that&#8217;s why I use, although I&#8217;m far from being a newbie) the &#8220;event model&#8221;, also called &#8220;cooperative multitasking&#8221;. This model works by events and it works very well as long as there are no &#8220;atomic&#8221; operations that take a long time.</p>
<p>In the event model, each task is executed in a function but that function cannot block. The program&#8217;s main loop calls all tasks (functions) sequentially, usually in a round-robin fashion. Then it&#8217;s a matter of applying some &#8220;tricks&#8221; to prevent the tasks from blocking execution, using state machines.</p>
<p>Let&#8217;s pick a problem I saw at LusoRobotica.com (a Portuguese robotics forum) that gave birth to the original version of this article: to have 2 LEDs blinking at different speeds and send an increasing number to the serial port. This comprises 3 tasks.</p>
<p>The main loop invokes the 3 tasks in sequence, and at the end it pauses for 10ms. This pause provides a known &#8220;time unit&#8221;, making the loop run at a certain known speed, otherwise it would be executed at maximum speed and it would be impossible to control the frequency at which, for example, the LEDs blink:</p>
<pre><code><strong>int</strong> loop ()
{
    blinkLed1();
    blinkLed2();
    sendNumber();
    delayMs(10);
}</code></pre>
<p>Now we know that each task is invoked at 10ms intervals. If we want our LED1 blinking once a second, we have to invert the LED&#8217;s state every 500ms. Since we know that each task is called every 10ms, we need to invert the state every 500ms / 10ms = <strong>50</strong> task calls, and for that we use a variable to count the calls:</p>
<pre><code><strong>void</strong> blinkLed1 ()
{
    <strong>static int</strong> counter = 0;

    counter = counter + 1;
    <strong>if</strong> (counter == 50)
    {
        togglePin(...);
        counter = 0;
    }
}</code></pre>
<p>A variable declared with <code>static</code> is like a global variable but is only visible inside the code block where it&#8217;s declared (a C/C++ code block is a piece of code enclosed in {}&#8217;s). I could have declare it outside all functions, but since it concerns, and is only used inside, that function, I decided to declare it as static to get things more clean and organized. Another reason to declare variables as static whenever possible is that we can have &#8220;global&#8221; variables with the same name &#8211; which is useful in the kind of programming model we&#8217;re talking about here since we can have many &#8220;counter&#8221; variables and other useful names. <code>blinkLED2()</code>&#8216;s task function can use the same name for the &#8220;counter&#8221; variable since it&#8217;s only visible inside the block where it was declared.<br />
This kind of variable must be &#8220;global&#8221; because their value must be preserved between calls at the same task.</p>
<p>Task <code>blinkLED2()</code> is similar to <code>blinkLED1()</code>; the only change is the LED pin and the number 50, which must be re-calculated for the desired blink frequency.</p>
<p>Now let&#8217;s do the <code>sendNumber()</code> task, that may seem complex but in fact it isn&#8217;t. What we need to do is to have a variable to save the last number sent to the serial port, and then increment it and send it on each task call:</p>
<pre><code><strong>void</strong> sendNumber ()
{
    <strong>static int</strong> number = 0;

    number = number + 1;
    Serial.write(number);
}</code></pre>
<p>This task tries to send a number every 10ms, which can be just to fast for what we want or even for the serial port&#8217;s data transmission speed (baudrate). In that case, we need to change the number sending such that only 1 count is sent every second. This is easy to do, because that&#8217;s exactly what the <code>blinkLED()</code> tasks already do! For a time interval of 1 second our counter variable needs to count 1000ms / 10ms = 100 times before sending the next number:<br />
<code>
<pre><strong>void</strong> sendNumber()
{
    <strong>static int</strong> counter = 0;

    counter = counter + 1;
    <strong>if</strong> (counter == 100)
    {
        <strong>static int</strong> number = 0;

        number = number + 1;
        Serial.write(number);

        counter = 0;
    }
} </pre>
<p></code><br />
Note that the original <code>sendNumber()</code>&#8216;s code is unchanged in the new function, but now inside the &#8220;if (counter == &#8230;&#8221; section so that it is now executed only once every 100 task calls.</p>
<p>There are a few more details I don&#8217;t mention in this article but the general technique is explained, and it allows us to do many things &#8220;simultaneously&#8221; in a simple way. What&#8217;s more important is that the tasks don&#8217;t take too long nor block; for example, you shouldn&#8217;t do delays inside them. If you need a delay, use the counter method to pause for the desired time and control the task using a state machine (like having 2 states, &#8220;delay&#8221; and &#8220;work&#8221;), just like in the examples above. Tasks must do something &#8220;quick&#8221; and leave.</p>
<p>Using this code structure you can implement lots of things and it&#8217;s a secure way of doing some multitasking.</p>
<p>Enjoy <img src="http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif?m=1286131766g" alt=";)" /></p>
<p><em>p.s. The code doesn&#8217;t compile, it&#8217;s just for illustration purposes.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/troniquices4en.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/troniquices4en.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/troniquices4en.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/troniquices4en.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/troniquices4en.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/troniquices4en.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/troniquices4en.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/troniquices4en.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=troniquices4en.wordpress.com&amp;blog=24573447&amp;post=5&amp;subd=troniquices4en&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://troniquices4en.wordpress.com/2011/06/27/how-to-do-several-things-at-the-same-time/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a4c2820225d36623e6a1f04113c7b1ed?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Njay</media:title>
		</media:content>

		<media:content url="http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif?m=1286131766g" medium="image">
			<media:title type="html">;)</media:title>
		</media:content>
	</item>
	</channel>
</rss>
