<?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/"
	>

<channel>
	<title>Polisoft Design</title>
	<atom:link href="http://polisoftdesign.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://polisoftdesign.com</link>
	<description>Embedded Systems for Energy Efficient Lighting</description>
	<lastBuildDate>Wed, 18 Jan 2012 23:05:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Trailing Comments Formatter</title>
		<link>http://polisoftdesign.com/2012/01/18/trailing-comments-formatter/</link>
		<comments>http://polisoftdesign.com/2012/01/18/trailing-comments-formatter/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 19:57:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Coding Standards]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Code Bautifier]]></category>
		<category><![CDATA[Code Formatter]]></category>
		<category><![CDATA[coding style]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=470</guid>
		<description><![CDATA[<p>Commenting properly your C/C++ code isn&#8217;t always an easy task. Comments can be messy or they can really tell the story or translate it for people interested in the code (including you after the years). There are two types of comments programmers use in their code:</p> block of comments, usually separated from the code [...]]]></description>
			<content:encoded><![CDATA[<p>Commenting properly your C/C++ code isn&#8217;t always an easy task. Comments can be messy or they can really tell the story or translate it for people interested in the code (including you after the years). There are two types of comments programmers use in their code:</p>
<ul>
<li><em>block of comments</em>, usually separated from the code (for example, function headers or file headers);</li>
<li><em>inline comments</em>, usually inserted in the code in order to explain its functionality.</li>
</ul>
<p>This post deals with the last type &#8212; the inline comments. These comments can be either placed on a separate line, usually, before the code they intend to explain, or as a <em>trailing comments</em> following the lines of code that require explanation. If you are like me, coming from years of trying different programming styles and standards, you may appreciate trailing comments more &#8212; C style (<span style="color: #008000;">/* comment */</span>) or C++ style (<span style="color: #008000;">// comment</span>). My preference for trailing comments, if properly used and <em>aligned</em>, comes from the fact that they can tell the story &#8220;in parallel&#8221; with the code. The source becomes a two column text with the left side the code itself and with the right side the &#8220;translation&#8221; (i.e. the comments telling the story). Here is an example:</p>
<pre><span style="color: #800080;">PUBLIC</span> <span style="color: #008080;">QUE_ITEM</span>                 <strong><span style="color: #ff6600;">QueAdd</span></strong>              (<span style="color: #008080;">PQUEUE</span>             pque,
                                                     <span style="color: #008080;">QUE_ITEM</span>           pv_item)
{<span style="color: #008000;">/* ------------------------------------------------------------------------------------------- */</span>
    <span style="color: #800080;">QUE_ENTER_CRITICAL</span> ();

    <strong><span style="color: #0000ff;">if</span></strong> (pque-&gt;full == <span style="color: #800080;">TRUE</span>)                         <span style="color: #008000;">/* if queue already full                    */</span>
    {
        <span style="color: #800080;">QUE_EXIT_CRITICAL</span> ();
        <span style="color: #0000ff;"><strong>return</strong></span> <span style="color: #800080;">NULL</span>;                                <span style="color: #008000;">/* return NULL for full                     */</span>
    }
    pque-&gt;tail = <span style="color: #800080;">INCMOD</span> (pque-&gt;tail, pque-&gt;size);   <span style="color: #008000;">/* increment tail mod size                  */</span>
    <span style="color: #0000ff;"><strong>if</strong></span> (pque-&gt;head == pque-&gt;tail)                   <span style="color: #008000;">/* is the queue full?                       */</span>
    {
        pque-&gt;full = <span style="color: #800080;">TRUE</span>;                          <span style="color: #008000;">/* set the indicator and                    */</span>
        <span style="color: #800080;">QUE_EXIT_CRITICAL</span> ();
        <span style="color: #0000ff;"><strong>return</strong></span> <span style="color: #800080;">NULL</span>;                                <span style="color: #008000;">/* return NULL for full                     */</span>
    }
    <span style="color: #800080;">QUE_EXIT_CRITICAL</span> ();
    <span style="color: #0000ff;"><strong>return</strong></span> (pque-&gt;data[pque-&gt;tail] = pv_item);      <span style="color: #008000;">/* return pointer to a new object           */</span>
}</pre>
<p>The main reason people don&#8217;t use trailing comments is related to the alignment I mentioned above. Maintaining the alignment is tedious and time consuming: when writing the code it is probably counterproductive to align the trailing comments all the time or to realign the comments after making changes to the code.</p>
<p>The idea of a little utility was born from this simple observation: it is easier to just add trailing comments wherever is necessary without any alignment and align them automatically at the end. Moreover, this utility program can convert C style comments to C++ style comments and vice versa performing the alignment in the same time.</p>
<h3>Introducing TCAlign</h3>
<p><a href="http://polisoftdesign.com/wp-content/uploads/2012/01/TCAlign.exe"><strong>TCAlign</strong></a> is a trailing comment formatting utility for C/C++ source files that has no effect on C style comment blocks (i.e. multi-line comments).</p>
<p>In order to preserve some inline comments, TCAlign uses a <em>sensitivity threshold</em> defined as the column of text from where the utility will process the comments (i.e. anything before the threshold column remains untouched). For example, if the sensitivity threshold is 25, comments beginning in columns 1-24 will remain unaffected while comments starting in a column greater or equal to 25 will be aligned and/or changed style. Obviously, if you set the threshold too low, some one line comments will be changed as well. The minimum value for the sensitivity threshold is 4 (this is to avoid touching any comments starting in the first column and meant to be used as headers for files, functions, etc.) and its default value is 25.</p>
<p>The user can indicate the <em>trailing comment preferred position</em>; by default this position is in column 65. If a source line extends beyond this position, the comment will be simply appended at the end. I recommend that you try to write your code in such a way that you will avoid extremely long one line statements by breaking them logically in more shorter lines. The code will gain in readability and will allow you adding even more meaningful trailing comments. Personally, I try to keep my code between columns 1 and 64 but some may find this too restrictive (I prefer to work with the monitor in portrait mode). Considering your typical monitor and typical text editor or IDE, you should be able to use as much as 150&#8230;160 columns (or more for wide screen monitors). Selecting a preferred position of 80 could make more sense to you.</p>
<p>The other important parameter is the <em>trailing comment preferred length</em>; by default the length is 42 characters, again derived from my own personal preference. If a comment is longer than the preferred length, the program will use it as-is. Use a larger value if you prefer long lines.</p>
<p>Here is the command line syntax with explanations:</p>
<pre style="padding-left: 30px;"><strong>TCAlign</strong> -<strong>fi</strong> &lt;input_file&gt; [-<strong>fo</strong> &lt;output_file&gt;] [options]</pre>
<p>where the <em>input file</em> name (fully qualified, including path if necessary) designates a text file that would be interpreted as C/C++ source file. The <em>output file</em> name is optional: if missing, the utility will create a <em>backup file</em> before generating the output so that you have the option to revert to the original. If the output file name is indicated, the program will use it for output; don&#8217;t use the same name as the input file name or you will get an error.</p>
<p>The options are:</p>
<pre style="padding-left: 30px;">-<strong>cpp</strong>    use C++ comments style (default is C style);
-<strong>th</strong>     sensitivity threshold for trailing comments (default is 25);
-<strong>cpos</strong>   trailing comment preferred position (default is 65);
-<strong>csz</strong>    trailing comment preferred size (default is 42);
-<strong>help</strong>   this help text (other arguments are ignored).</pre>
<p>Notes:</p>
<ul>
<li>make sure that 3 &lt; <strong>th</strong> &lt; <strong>cpos</strong>; eventually, <strong>TCAling</strong> will swap <strong>th</strong> and <strong>cpos</strong> values in an attempt to order them correctly;</li>
<li>the minimum value for <strong>th</strong>, <strong>cpos</strong> and <strong>csz</strong> is 4; a smaller value will be quietly replaced with its corresponding default.</li>
</ul>
<p>Examples:</p>
<ol>
<li>Align trailing comments and change their style from C to C++ style using the default parameters:
<pre>tcalign -fi acmgmt.c -fo acmgmt_fmt -cpp</pre>
</li>
<li>Align trailing comments and change their style from C++ to C style using a threshold column of 80 and a comment length of 50:
<pre>tcalign -fi acmgmt.c -fo acmgmt_fmt -cpos 80 -csz 50</pre>
</li>
</ol>
<p><a href="http://polisoftdesign.com/wp-content/uploads/2012/01/TCAlign.exe">Download TCAlign</a> and start formatting your trailing comments. The TCAlign utility will also work for C# and other &#8220;C like&#8221; source files.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2012%2F01%2F18%2Ftrailing-comments-formatter%2F&amp;title=Trailing%20Comments%20Formatter" id="wpa2a_2"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2012/01/18/trailing-comments-formatter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solid-State Lighting and LEDs</title>
		<link>http://polisoftdesign.com/2010/08/31/solid-state-lighting-and-leds/</link>
		<comments>http://polisoftdesign.com/2010/08/31/solid-state-lighting-and-leds/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 22:21:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[LED Technology]]></category>
		<category><![CDATA[Solid-State Lighting]]></category>
		<category><![CDATA[LED]]></category>
		<category><![CDATA[OLED]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=441</guid>
		<description><![CDATA[<p class="wp-caption-text">Cree® XLamp® XP-G LED</p> <p>Solid-State Lighting (SSL) uses semiconductor materials to convert electricity into light. Some associate SSL only with with LEDs. In reality SSL is an umbrella term encompassing different types of technologies including Light-Emitting Diodes (LEDs) and Organic Light-Emitting Diodes (OLEDs). More recently, Light Emitting Capacitors (LEC) and Light-Emitting Polymers (LEP)  [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_442" class="wp-caption alignright" style="width: 301px"><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/Cree_XLamp_XP-G_LED.jpg"><img class="size-full wp-image-442" title="Cree_XLamp_XP-G_LED" src="http://polisoftdesign.com/wp-content/uploads/2010/08/Cree_XLamp_XP-G_LED.jpg" alt="Cree XLamp XP-G LED" width="291" height="225" /></a><p class="wp-caption-text">Cree®  XLamp®  XP-G LED</p></div>
<p>Solid-State Lighting (SSL) uses semiconductor materials to convert electricity into light. Some associate SSL only with with LEDs. In reality SSL is an umbrella term encompassing different types of technologies including <em>Light-Emitting Diodes</em> (LEDs) and <em>Organic Light-Emitting Diodes</em> (OLEDs). More recently, <em>Light Emitting Capacitors</em> (LEC) and <em>Light-Emitting Polymers</em> (LEP)  technologies are emerging.</p>
<p>While some of the technologies are evolving rapidly, LEDs are the more mature technology, particularly for white-light general illumination applications [1].</p>
<p>The best white LEDs are similar in efficiency to CFLs, but most of the white LEDs currently available in consumer products are only marginally more efficient than incandescent lamps. Lumens per Watt (lm/W) is the measure of how efficiently the light source is converting electricity into usable light. The best white LEDs available today can produce about 80-120 lm/W [2]. For comparison, incandescent lamps typically produce 12-15 lm/W; CFLs produce at least 50 lm/W [3].</p>
<p>Unlike other light sources, LEDs don’t “burn out;” they simply get dimmer over time. Although there is not yet  an official industry standard defining “life” of an LED, the leading manufacturers define it as the point at which light output has decreased to 70% of initial light output. Using that definition, the best white LEDs have been found to have a useful life of around 35,000 hours (that’s four years of continuous operation). For comparison, a 75-watt incandescent light bulb lasts about 1,000 hours; a comparable CFL lasts 8,000 to 10,000 hours. LED lifetime depends greatly on operating temperature [4]. An increase in operating temperature of 10°C can cut the useful life of an LED in half; with a good thermal management, the LED life can be increased to 50,000 hours or even more (almost 6 years of continuous operation).</p>
<p>References:</p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Light-emitting_diode" target="_blank"><em>Light-Emitting Diode</em></a> on Wikipedia</li>
<li><a href="http://members.misty.com/don/led.html" target="_blank"><em>The Most Efficient LEDs and where to get them!</em></a></li>
<li><a href="http://en.wikipedia.org/wiki/Luminous_efficacy" target="_blank"><em>Luminous Efficacy</em></a> on Wikipedia</li>
<li>Philips &#8211; <a href="http://www.philipslumileds.com/pdfs/WP12.pdf" target="_blank"><em>Understanding Power LED Lifetime Analysis</em></a></li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2010%2F08%2F31%2Fsolid-state-lighting-and-leds%2F&amp;title=Solid-State%20Lighting%20and%20LEDs" id="wpa2a_4"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/08/31/solid-state-lighting-and-leds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Light and Colors – Part 4</title>
		<link>http://polisoftdesign.com/2010/08/29/light-and-colors-%e2%80%93-part-4/</link>
		<comments>http://polisoftdesign.com/2010/08/29/light-and-colors-%e2%80%93-part-4/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 01:39:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[General Lighting]]></category>
		<category><![CDATA[chromaticity diagram]]></category>
		<category><![CDATA[CIE 1931]]></category>
		<category><![CDATA[color space]]></category>
		<category><![CDATA[gamut]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=426</guid>
		<description><![CDATA[<p class="wp-caption-text">The CIE 1931 Chromaticity Diagram</p> <p>The CIE XYZ color space [1] defines all colors in terms of three imaginary primaries X, Y, and Z based on the human visual system that possess the following properties:</p> Based on experimental data of human color matching; X, Y, and Z work like additive primaries RGB (every [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_437" class="wp-caption alignright" style="width: 481px"><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/CIE_1931_1000.png"><img class="size-full wp-image-437  " title="CIE_1931_1000" src="http://polisoftdesign.com/wp-content/uploads/2010/08/CIE_1931_1000.png" alt="CIE 1931 Chromaticity Diagram" width="471" height="512" /></a><p class="wp-caption-text">The CIE 1931 Chromaticity Diagram</p></div>
<p>The CIE <em>XYZ color space</em> [1] defines all colors in terms of three imaginary primaries <em>X</em>, <em>Y</em>, and <em>Z</em> based on the human visual system that possess the following properties:</p>
<ol>
<li>Based on experimental data of human color matching;</li>
<li><em>X</em>, <em>Y</em>, and <em>Z</em> work like additive primaries RGB (every color is expressed as a mixture of <em>X</em>, <em>Y</em>, and <em>Z</em>);</li>
<li>One of the three values &#8211; <em>Y</em> &#8211; represents <em>luminance</em>, i.e. the overall brightness (lightness) of the color as a function of wavelength;</li>
<li>All color values (<em>X</em> and <em>Z</em>) are positive.</li>
</ol>
<p>The <em>xyY color space</em> is derived directly from <em>XYZ</em> and is used to graph colors in two dimensions independent of lightness. The value <em>Y</em> is identical to the tristimulus value <em>Y</em> (in <em>XYZ</em>). The <em>x</em> and <em>y</em> values are called the <em>chromaticity coordinates</em> of the color and are computed directly from the tristimulus values <em>XYZ</em>. The chromaticity of a color was then specified by the two derived  parameters x and y, two of the three normalized values which are  functions of all three tristimulus values <em>X</em>, <em>Y</em>, and <em>Z</em> [2]:</p>
<p><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/x_CIE.png"><img class="alignnone size-full wp-image-434" title="x_CIE" src="http://polisoftdesign.com/wp-content/uploads/2010/08/x_CIE.png" alt="" width="109" height="34" /></a> <a href="http://polisoftdesign.com/wp-content/uploads/2010/08/y_CIE.png"><img class="alignnone size-full wp-image-435" title="y_CIE" src="http://polisoftdesign.com/wp-content/uploads/2010/08/y_CIE.png" alt="" width="109" height="34" /></a> <a href="http://polisoftdesign.com/wp-content/uploads/2010/08/z_CIE.png"><img class="alignnone size-full wp-image-436" title="z_CIE" src="http://polisoftdesign.com/wp-content/uploads/2010/08/z_CIE.png" alt="" width="194" height="34" /></a></p>
<p>The <em>xyY</em> values of colors can be plotted in a useful graph known as the <em>CIE chromaticity diagram</em>. Colors on the periphery of the diagram are saturated; colors become progressively desaturated and tend towards white somewhere in the middle of the plot. The point at <em>x</em> = <em>y</em> = <em>z</em> = 0.333 represents the white perceived from an equal-energy flat spectrum of radiation.</p>
<p>For any device such as a monitor or printer, we can plot its <em>gamut</em> &#8211; the colors that are reproducible using the device’s primaries [3]. This is one of the most common uses for the CIE diagram. The brighter triangle in the center of the plot shows the colors which can be reproduced by a standard computer screen, representing its gamut. Colors outside the triangle are said to be <em>out-of-gamut</em> for, and cannot be reproduced  on, normal display screens. They are artificially desaturated in the plot.</p>
<p>For all its simple derivation from eye-response functions, the 1931 CIE chromaticity diagram is not <em>perceptually uniform</em> because the mathematics of <em>xyY</em> do not model distances between colors. This is the reason why the area of green-turquoise in the large lobe at the top left of the diagram (inaccessible to monitors) appears to be disproportionally large compared with the others. To solve this problem, other color-space coordinate systems and plots were invented &#8211; CIELUV [4], CIELAB [5] &#8211; in an attempt to be more perceptually-uniform. Their use is fairly specialized.</p>
<p><span style="text-decoration: underline;">References:</span></p>
<ol>
<li><em><a href="http://en.wikipedia.org/wiki/CIE_1931_color_space" target="_blank">CIE 1931 color space</a></em> on Wikipedia</li>
<li>Danny Pascale &#8212; <a href="http://www.babelcolor.com/download/A%20review%20of%20RGB%20color%20spaces.pdf" target="_blank"><em>A Review of RGB Color Spaces &#8230; from xyY to R’G’B’</em></a></li>
<li><a href="http://en.wikipedia.org/wiki/Gamut" target="_blank"><em>Color Gamut</em></a> on Wikipedia</li>
<li><a href="http://en.wikipedia.org/wiki/CIELUV_color_space" target="_blank"><em>CIELUV color space</em></a> on Wikipedia</li>
<li><a href="http://en.wikipedia.org/wiki/Lab_color_space" target="_blank"><em>CIELAB color space</em></a> on Wikipedia</li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2010%2F08%2F29%2Flight-and-colors-%25e2%2580%2593-part-4%2F&amp;title=Light%20and%20Colors%20%E2%80%93%20Part%204" id="wpa2a_6"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/08/29/light-and-colors-%e2%80%93-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Light and Colors – Part 3</title>
		<link>http://polisoftdesign.com/2010/08/29/light-and-colors-%e2%80%93-part-3/</link>
		<comments>http://polisoftdesign.com/2010/08/29/light-and-colors-%e2%80%93-part-3/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 00:32:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[General Lighting]]></category>
		<category><![CDATA[color matching functions]]></category>
		<category><![CDATA[color model]]></category>
		<category><![CDATA[color perception]]></category>
		<category><![CDATA[tristimulus]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=414</guid>
		<description><![CDATA[<p></p> <p>Color perception is a brain process that starts in the eye’s cone receptors. These receptors are found in three varieties that exhibit sensitivity to approximately red, green, and blue colors. The separation between colors is not clean and there is significant overlap between the sensitivities of all three varieties, particularly between the red [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/ColorMatchingExperiment.png"><img class="alignright size-full wp-image-415" title="ColorMatchingExperiment" src="http://polisoftdesign.com/wp-content/uploads/2010/08/ColorMatchingExperiment.png" alt="" width="529" height="491" /></a></p>
<p>Color perception is a brain process that starts in the eye’s <em>cone receptors</em>. These receptors are found in three varieties that exhibit sensitivity to approximately <em>red</em>, <em>green</em>, and <em>blue </em>colors. The separation between colors is not clean and there is significant overlap between the sensitivities of all three varieties, particularly between the red and green cones.</p>
<p>Most studies of the three-color nature of human vision are based on some variation of this simple apparatus (see the figure on the right).</p>
<p>One part of the screen is illuminated by a lamp of a target color; the other by a mixture of three colored lamps. Each of the lamps is called a <em>stimulus</em> and, in tightly controlled experiments, may consist of light of a single wavelength (<em>monochromatic</em> light source). The test subject (<em>observer</em>) adjusts the intensities of the three lamps until the mixture appears to match the <em>target</em> color.</p>
<p>Experiments have shown that certain combinations of matching colors (usually some form of the primaries red, green, and blue) allow observers to match <strong>most, but not all</strong>, target colors. However, by adding light from one of these primaries to the target color, all possible target colors can be matched. The light added to the target color can be thought of as having been subtracted from the other two primaries &#8211; thus creating the theoretical notion of a <em>negative</em> amount of light []. This important observation shows that the trichromatic theory cannot generate all the colors perceived by the brain. On the other hand, the trichromatic theory allows a color vision modeling process that is practical and not overwhelmingly complex. In special cases, adding a fourth color is necessary in order to cover situations where using the trichromatic model does not lead to satisfactory results.</p>
<div id="attachment_421" class="wp-caption alignnone" style="width: 710px"><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/ColorMatchingFunctions_CIE1931.png"><img class="size-full wp-image-421" title="ColorMatchingFunctions_CIE1931" src="http://polisoftdesign.com/wp-content/uploads/2010/08/ColorMatchingFunctions_CIE1931.png" alt="CIE 1931 Color Matching Functions" width="700" height="300" /></a><p class="wp-caption-text">Human-Eye Cones Sensitivities and CIE 1931 Color Matching Functions</p></div>
<p>In 1931, the <em>Commission Internationale de l’Éclairage</em> (CIE)  established standards for color representation based on the  physiological perception of light. They are built on a set of three  color-matching functions, collectively called the <em>Standard Observer</em>,  related to the red, green and blue cones in the eye []. They were  derived by showing subjects color patches and asking them to match the  color by adjusting the output of three pure (monochromatic) colors of  435.8, 546.1, and 700 nm.</p>
<p><span style="text-decoration: underline;"> Definition:</span> A <em>tristimulus</em> description of a color is one that defines the color in terms of three quantities, or stimuli.</p>
<p>Tristimulus descriptions of color have certain advantages over spectral data: tristimulus models human vision reasonably well, and can be plotted in three dimensions. The space defined by these three axes is called <em>color space</em>. Colors in one color space are converted to another color space by use of a <em>transformation</em>. A color space is an example of a more general concept called a <em>color model</em>.</p>
<p><span style="text-decoration: underline;">References:</span></p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Color_theory" target="_blank"><em>Color Theory</em></a> on Wikipedia</li>
<li>Janet Lynn Ford – <a href="http://www.worqx.com/color/" target="_blank"><em>Color Theory Tutorial</em></a></li>
<li>Danny Pascale – <em>Color tutorials</em> at <a href="http://www.babelcolor.com/" target="_blank">BabelColor</a></li>
<li>Birren, Faber – <em>Light, Color, and Environment</em>, Chicago, Van Nostrand Reinhold Company, 1969</li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2010%2F08%2F29%2Flight-and-colors-%25e2%2580%2593-part-3%2F&amp;title=Light%20and%20Colors%20%E2%80%93%20Part%203" id="wpa2a_8"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/08/29/light-and-colors-%e2%80%93-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Light and Colors – Part 2</title>
		<link>http://polisoftdesign.com/2010/08/29/light-and-colors-part-2/</link>
		<comments>http://polisoftdesign.com/2010/08/29/light-and-colors-part-2/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 21:04:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[General Lighting]]></category>
		<category><![CDATA[light measurement]]></category>
		<category><![CDATA[photometry]]></category>
		<category><![CDATA[photopic vision]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=396</guid>
		<description><![CDATA[<p class="wp-caption-text">CIE Photometric Curve</p> <p>The human eye is an incredibly complex detector of electromagnetic radiation with wavelengths between 380 to 770 nm. The sensitivity of the eye to light varies with wavelength (see the CIE photometric curve for the day vision &#8211; V(λ) &#8211; the photopic visual response function). Photometry can be considered radiometry [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_397" class="wp-caption alignright" style="width: 438px"><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/PhotometricCurve.png"><img class="size-full wp-image-397" title="PhotometricCurve" src="http://polisoftdesign.com/wp-content/uploads/2010/08/PhotometricCurve.png" alt="CIE Photometric Curve" width="428" height="287" /></a><p class="wp-caption-text">CIE Photometric Curve</p></div>
<p>The human eye is an incredibly complex detector of electromagnetic radiation with wavelengths between 380 to 770 nm. The sensitivity of the eye to light varies with wavelength (see the CIE photometric curve for the day vision &#8211; <em>V</em>(λ) &#8211; the <em>photopic</em> visual response function). <em>Photometry</em> can be considered <em>radiometry</em> weighted by the visual response of the “average” human eye: 1 Watt of radiant energy at λ = 555 nm (maximum sensitivity of the eye) equals 683 lumens. The eye has different responses as a function of wavelength when it is adapted to light conditions (<em>photopic</em> vision) and dark conditions (<em>scotopic</em> vision). Photometry is typically based on the eye&#8217;s photopic response [1].</p>
<p>Photometric theory does not address how we perceive colors. The light being measured can be monochromatic or a combination or continuum of wavelengths; the eye’s response is determined by the CIE weighting function. This  underlines a crucial point: <em>the only difference between radiometric and photometric theory is in their units of measurement</em>.</p>
<p>Here are the <em>photometric quantities</em> and the relationship with their radiometric counterparts:</p>
<table style="height: 124px;" border="0" cellspacing="0" cellpadding="0" width="567">
<col width="93"></col>
<col width="117"></col>
<col width="55"></col>
<col width="146"></col>
<tbody>
<tr height="17">
<td width="93" height="17"><strong>(Radiometric)</strong></td>
<td width="117"><strong>Photometric</strong></td>
<td width="55"><strong>Symbol</strong></td>
<td width="146"><strong>Units</strong></td>
</tr>
<tr height="21">
<td height="21">(Power)</td>
<td>Luminous Flux</td>
<td>λ<span><sub>v</sub></span></td>
<td>lumen (lm)</td>
</tr>
<tr height="21">
<td height="21">(Intensity)</td>
<td>Luminous Intensity</td>
<td><em>I</em><span><sub>v</sub></span></td>
<td>lm/sr = candela (cd)</td>
</tr>
<tr height="21">
<td height="21">(Irradiance)</td>
<td>Illuminance</td>
<td><em>E</em><span><sub>v</sub></span></td>
<td>lumen/m<span><sup>2</sup></span><span> = lux</span></td>
</tr>
<tr height="21">
<td height="21">(Excitance)</td>
<td>Illuminance</td>
<td><em>M</em><span><sub>v</sub></span></td>
<td>lumen/m<span><sup>2</sup></span><span> = lux</span></td>
</tr>
<tr height="21">
<td height="21">(Radiance)</td>
<td>Luminance</td>
<td><em>L</em><span><sub>v</sub></span></td>
<td>lm/(m<span><sup>2</sup></span><span> sr) = cd/m</span><span><sup>2</sup></span><span> = nit</span></td>
</tr>
</tbody>
</table>
<h3>Photometry example: LED radiant intensity</h3>
<p>A specification sheet says that a red LED, with a pick wavelength of λ = 630 nm, emits <em>I</em><sub>v</sub> = 20 mcd (millicandelas). We want to know how many Watts are incident on a photodetector used to measure the light produced by the LED (need to convert photometric specification to radiometric values). Solving this problem properly requires knowing the spectral distribution of LED radiant intensity that leads to<em> I</em><sub>v</sub> = 20 mcd:<br />
<a href="http://polisoftdesign.com/wp-content/uploads/2010/08/Photometry_LED_Eq_01.png"><img class="size-full wp-image-408 alignnone" title="Photometry_LED_Eq_01" src="http://polisoftdesign.com/wp-content/uploads/2010/08/Photometry_LED_Eq_01.png" alt="" width="183" height="38" /></a><br />
where <em>V</em>(λ) is the photopic visual response function and <em>I</em><sub>λ</sub>(λ) is the radiant intensity distribution [2]. In practice determining the intensity is simplified by the existence of pre-calculated tables [3].<br />
<a href="http://polisoftdesign.com/wp-content/uploads/2010/08/Photometry_LED_Eq_02.png"><img class="alignnone size-full wp-image-409" title="Photometry_LED_Eq_02" src="http://polisoftdesign.com/wp-content/uploads/2010/08/Photometry_LED_Eq_02.png" alt="" width="470" height="101" /></a><br />
To find total emitted flux, multiply the result by the solid angle of LED emission.</p>
<p><span style="text-decoration: underline;">References:</span></p>
<ol>
<li><em><a href="http://en.wikipedia.org/wiki/Photometry_%28optics%29" target="_blank">Photometry (optics)</a></em> on Wikipedia</li>
<li><a href="http://en.wikipedia.org/wiki/Luminosity_function" target="_blank"><em>Luminosity function</em></a> on Wikipedia</li>
<li><a href="http://cvision.ucsd.edu/lumindex.htm" target="_blank"><em>Tables of luminosity functions</em></a> on UCSD Color Vision</li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2010%2F08%2F29%2Flight-and-colors-part-2%2F&amp;title=Light%20and%20Colors%20%E2%80%93%20Part%202" id="wpa2a_10"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/08/29/light-and-colors-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Light and Colors – Part 1</title>
		<link>http://polisoftdesign.com/2010/08/28/light-and-colors-part-1/</link>
		<comments>http://polisoftdesign.com/2010/08/28/light-and-colors-part-1/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 04:22:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[General Lighting]]></category>
		<category><![CDATA[absorption]]></category>
		<category><![CDATA[colorimetry]]></category>
		<category><![CDATA[colors]]></category>
		<category><![CDATA[emission]]></category>
		<category><![CDATA[light]]></category>
		<category><![CDATA[radiometry]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[visible spectrum]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=383</guid>
		<description><![CDATA[<p>There are many books and papers dedicated to the study of light from different perspectives: the artist, the scientist, the designer, the historian or the biologist. There is no point in repeating here what the literature provides in abundance. The goal of this post is to introduce some concepts that will be used later [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/LightSpectrum.png"><img class="alignright size-full wp-image-384" title="LightSpectrum" src="http://polisoftdesign.com/wp-content/uploads/2010/08/LightSpectrum.png" alt="The Spectrum of Visible Light" width="175" height="504" /></a>There are many books and papers dedicated to the study of light from different perspectives: the artist, the scientist, the designer, the historian or the biologist. There is no point in repeating here what the literature provides in abundance. The goal of this post is to introduce some concepts that will be used later in other posts so that the reader will not have to spend hours searching for basic definitions.</p>
<p>Generally speaking the <em>light</em> is the electromagnetic radiation within the part of the spectrum visible to the human eye: with wavelengths approximately between 400 and 700 nm [1]. There are only two ways that can affect the wavelength composition of light: <em>emission</em> and <em>absorption</em>.</p>
<p>The <em>emission </em>caused by a chemical or physical process is always related to the <em>light source</em>. There is no naturally occurring &#8220;perfect&#8221; white light source in the sense that the spectrum is flat (i.e. it emits the same amount of each wavelength). What the human eye perceive as white is very subjective: each of us sees a different &#8220;nuance of white&#8221;.</p>
<p>The <em>absorption</em> is the opposite of emission and happens when the light is transformed into a different form of energy.The amount of absorption of each wavelength is dependent on the nature of the object that light touches.</p>
<p>The <em>reflection</em> can be simply reduced to an absorption followed by a re-emission of the light. Usually, some wavelengths are absorbed more than others, so the light that emerges has a different wavelength composition.</p>
<p><em>Transmission</em> can be reduced to absorption: the amount of absorption of each wavelength, and thus the intensity that emerges from the material, depends on the physical characteristics of that material. There is no such think as the <em>perfect transmitter</em> &#8212; only vacuum (theoretically, the absence of matter) could be one.</p>
<p>The light science needs a special absorptive device that converts light into electrical signals: <em>photo sensor</em> (or photo detector).</p>
<p><em>Colors</em> may result:</p>
<ul>
<li>through the emission of certain wavelengths in different proportions;</li>
<li> from white light through the absorption of certain wavelengths in different proportions.</li>
</ul>
<p>The spectral curve of an object is its visual fingerprint, describing how the object affects light at each wavelength:</p>
<ul>
<li>a reflective object will be characterized by its <em>reflectance graph</em>;</li>
<li>a transmissive object will be characterized by its <em>transmittance graph</em>;</li>
<li>an emissive object will be characterized by its <em>emittance graph</em>.</li>
</ul>
<div id="attachment_389" class="wp-caption aligncenter" style="width: 838px"><a href="http://polisoftdesign.com/wp-content/uploads/2010/08/SpectralCurves.png"><img class="size-full wp-image-389     " title="SpectralCurves" src="http://polisoftdesign.com/wp-content/uploads/2010/08/SpectralCurves.png" alt="Spectral Curves" width="828" height="228" /></a><p class="wp-caption-text">a. Reflectance Graph _____________________ b. Transmittance Graph _____________________ c. Emittance Graph</p></div>
<p style="text-align: center;">
<p>From a purely scientific point of view the <em>spectral data is a complete and unambiguous description of color information</em>. Unfortunately, the way our eye interprets that information is far from being objective.</p>
<p>The light science refers to all the aspects of light either seen as radiation characterized unequivocally by its physical parameters (like spectral data) or based on a statistical model of the human visual response to light:</p>
<ul>
<li> <em>radiometry</em> &#8211; the science of measuring light in any portion of the electromagnetic spectrum (but usually limited to infrared, visible and ultraviolet);</li>
<li> <em>photometry</em> &#8211; the science of measuring visible light in units that are weighted according to the sensitivity of the human eye;</li>
<li><em>colorimetry</em> &#8211; the science of color as perceived by the human eye.</li>
</ul>
<p><span style="text-decoration: underline;">References:</span></p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Visible_light" target="_blank"><em>Visible spectrum</em></a> on Wikipedia</li>
<li>James M. Palmer; Barbara G. Grant &#8211; <a href="http://spie.org/x648.html?product_id=798237" target="_blank"><em>The Art of Radiometry</em></a> (SPIE Press Book)</li>
<li><a href="http://www.optics.arizona.edu/palmer/opti400/suppdocs/bkappndx.pdf" target="_blank">Appendices section</a> from <em>The Art of Radiometry</em> (above) in PDF format</li>
<li>Ian Ashdown &#8211; <a href="http://www.helios32.com/Measuring%20Light.pdf" target="_blank"><em>Photometry and Radiometry &#8211; A Tour Guide for Computer Graphics Enthusiasts</em></a> in PDF format</li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2010%2F08%2F28%2Flight-and-colors-part-1%2F&amp;title=Light%20and%20Colors%20%E2%80%93%20Part%201" id="wpa2a_12"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/08/28/light-and-colors-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CoOS Real Time Kernel (CooCox.org) – Part 3</title>
		<link>http://polisoftdesign.com/2010/08/28/coos-real-time-kernel-coocox-org-%e2%80%93-part-3/</link>
		<comments>http://polisoftdesign.com/2010/08/28/coos-real-time-kernel-coocox-org-%e2%80%93-part-3/#comments</comments>
		<pubDate>Sat, 28 Aug 2010 22:06:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[RTOS]]></category>
		<category><![CDATA[CoOS]]></category>
		<category><![CDATA[interrupt latency]]></category>
		<category><![CDATA[real-time]]></category>
		<category><![CDATA[reviews]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=380</guid>
		<description><![CDATA[<p>Lesson learned: the presence of an RTOS doesn&#8217;t mean you will get a better real-time performance for your application! I know, it sounds counterintuitive but this is real. A hard real-time system where the interrupts should be serviced as quickly as they come will have to rely on small and fast interrupt service routines [...]]]></description>
			<content:encoded><![CDATA[<p>Lesson learned: <strong>the presence of an RTOS doesn&#8217;t mean you will get a better real-time performance for your application</strong>! I know, it sounds counterintuitive but this is real. A hard real-time system where the interrupts should be serviced as quickly as they come will have to rely on small and fast interrupt service routines only and not on operating system services that may be served with longer latencies. Most embedded programmers know this but in the rush of writing applications and meeting tight deadlines they forget the basic things like &#8220;<strong>keep the darn ISRs short</strong>&#8220;.</p>
<p>After using CoOS for few months in a relatively complex project, I must say that this kernel does a very good job for its intended target: ARM Cortex M3 processor. As I mentioned before, the CoOS kernel isn&#8217;t perfect in the sense that heavily loaded systems may experience issues like lost interrupts. After additional testing, I was surprised that more established kernels (µC/OS II, FreeRTOS) exhibit worse problems when it comes to latency related problems. As usual, these problems can be solved by designing the application differently and reducing the interrupt rate that make use of kernel services that are the most likely causes of system misbehavior.</p>
<p>For example, if you have a system with serial interfaces working at 115200 bps in interrupt mode, the time between interrupts coming from one UART is only ~87 µs. If the ISR involves setting a semaphore through a system call, about 1.8 µs will be added to the ISR execution time. Not to mention that the UART ISR time will add to the system timer ISR time occasionally delaying system services processing and task switches. In some circumstances this may work fine and no abnormal behavior will be observed. This may be the case when the system uses one high speed UART as the main source of rapid coming interrupts. Adding another similar UART (or maybe more) will push the system over the limits and problems like missing system timer interrupts will arise. In such cases the embedded developer can spend days looking for the source of errors.</p>
<p>One way to solve this problem is to <strong>avoid using any system calls </strong>(including those designed as safe for ISR use) in the interrupt service routines that are triggered by fast peripherals (e.g. SPI, I2C or UARTS at high data rates). This approach may work very well if the ISR code is short and executed quickly.</p>
<p>Another way is to <strong>reduce the interrupt rate</strong> by using Direct Memory Access (DMA) or hardware FIFOs if available. Most modern microcontrollers, especially in the Cortex M3 class, will give you one option or another. For example, a UART with a 16 byte FIFO operating at 115200 bps can reduce the interrupt interval to ~1.39 ms! Using higher data rates (e.g. &gt;1 Mbps) will only be possible with the help of hardware. Remember, no RTOS kernel will enable better responsiveness for such fast occurring events &#8212; only the hardware can help.</p>
<p>As a rule of thumb, whenever the interrupt rate is faster than ~100 kHz, do not use the RTOS assistance at all.</p>
<p>While investigating the CoOS 1.12 responsiveness, I uncovered a problem in the way the kernel handles the service requests that come from user ISRs invoked by <strong>isr_<em>Function</em></strong>() calls. Let&#8217;s examine first the implementation of the service request handling.</p>
<p>The <em>service requests</em> are placed synchronously in a queue that is processed either at the end of the ISR if there is no conflict with the OS (no task scheduling happening) or asynchronously in the <strong>SysTick</strong> handler when the scheduling takes place. Because in more than 90% of cases there is no conflict with the OS, the system requests are served promptly which explains why even a heavy loaded system works fine most of the time. Once a request cannot be served immediately and it is placed in the queue, the latency time increases up to one <strong>SysTick</strong> period. Assuming a <strong>SysTick</strong> every 1 ms (the minimum supported by CoOS) the response time may be too slow to accommodate the interrupt rate of a certain peripheral, the service request queue will become full quickly and the system may start missing events. One way to compensate is to increase the size of the service request queue which is 4 items by default. With enough RAM one can try 10…20 items with some hope for improvement.</p>
<p>Unfortunately, version 1.12 of CoOS contained a mistake in the way the service request queue was implemented: when I signaled this problem to the authors, they fixed this issue in version 1.13 which seems to function properly now. I&#8217;m sure that my solution to this problem isn&#8217;t optimal and probably violates what the authors wanted when they claimed that interrupt latency in CoOS is 0! Such a claim assumes that the interrupts will be kept enabled 100% of the time. My solution uses a short critical section that involved disabling interrupts briefly when accessing the service queue. If no system services are invoked in ISRs, the original claim stands. Not in the case <strong>isr_<em>Function</em></strong>() calls are used in user ISRs. However, the penalty in latency time isn&#8217;t significant in most practical situations. I am convinced that a better implementation of the service queue management is possible using the mutual exclusion primitives that Cortex M3 provides at the machine level.</p>
<p>In conclusion, the current version of CoOS (1.13) seems to be stable enough for complex projects and I encourage other embedded developers to give it a try.</p>
<p>Please post any issues you find here and I will do my part in continuing the investigations and report my findings in the future.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpolisoftdesign.com%2F2010%2F08%2F28%2Fcoos-real-time-kernel-coocox-org-%25e2%2580%2593-part-3%2F&amp;title=CoOS%20Real%20Time%20Kernel%20%28CooCox.org%29%20%E2%80%93%20Part%203" id="wpa2a_14"><img src="http://polisoftdesign.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/08/28/coos-real-time-kernel-coocox-org-%e2%80%93-part-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Matter of Interrupts and Mutual Exclusion – Part 5</title>
		<link>http://polisoftdesign.com/2010/05/03/a-matter-of-interrupts-and-mutual-exclusion-part-5/</link>
		<comments>http://polisoftdesign.com/2010/05/03/a-matter-of-interrupts-and-mutual-exclusion-part-5/#comments</comments>
		<pubDate>Mon, 03 May 2010 22:20:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Drivers]]></category>
		<category><![CDATA[RTOS]]></category>
		<category><![CDATA[critical section]]></category>
		<category><![CDATA[interrupts]]></category>
		<category><![CDATA[mutual exclusion]]></category>
		<category><![CDATA[shared resources]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/2010/05/03/a-matter-of-interrupts-and-mutual-exclusion-part-5/</guid>
		<description><![CDATA[Mutual exclusion as a way to ensure that the asynchronous access to a common resource (variable, object, peripheral). [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most delicate problems in embedded programming is to ensure that the asynchronous access to a common resource (variable, object, peripheral) does not lead the system to unpredictable behavior. When studied, the concept of <em>mutual exclusion</em> seems logical and perceived by most as common sense. But when it comes to implementation many programmers struggle to deal with the side effects of our “single threaded” mindset.</p>
<p>In the following picture two independent processes – A and B – compete for an object that can be accessed by both between the moments <em>t</em><sub>1</sub> and <em>t</em><sub>2</sub>. The two processes can be either an <em>interrupt</em> and the <em>main thread</em> or two <em>tasks</em> in a multitasking environment. The conflict comes from the fact that accessing the object requires a finite amount of time that is not 0 and the moments of preemption are completely unpredictable. Some may argue that most of the time the two processes will not access the resource in the same time and the probability for conflict is almost 0. Well, “<em>most of the time</em>” and “<em>is almost 0</em>” aren’t good enough. This has to change in “<em>all of the time</em>” and “<em>is always 0</em>” in order to have a reliable and determinist system.</p>
<p><a href="http://polisoftdesign.com/wp-content/uploads/2010/05/Clipboard04.png"><img class="aligncenter size-full wp-image-359" title="Mutual Exclusion Problem" src="http://polisoftdesign.com/wp-content/uploads/2010/05/Clipboard04.png" alt="Two Processes Sharing an Object" width="579" height="304" /></a></p>
<p>Another category of people may think that accessing the object is a basic CPU feature that translates into some indivisible micro-operation sequence that cannot be disturbed (i.e. interrupted). Nothing can be more mistaken. In reality, even simple operations like incrementing a counter variable may translate into more than one machine instruction. For example, process B executing:</p>
<pre style="padding-left: 30px;">pcom_buf-&gt;rx_count++;<strong>
<span style="color: #0000ff;">if</span></strong> (pcom_buf-&gt;rx_count &gt;= <span style="color: #800080;">MAX_COUNT</span>)
{   . . .</pre>
<p>translates (for an ARM Cortex-M3 processor) into something like:</p>
<pre style="padding-left: 30px;">LDRH     R3,[R0, #+28]        <span style="color: #008000;">; load " pcom_buf-&gt;rx_count"</span>
ADDS     R3,R3,#+1            <span style="color: #008000;">; increment its value</span>
STRH     R3,[R0, #+28]        <span style="color: #008000;">; put the result back</span>
CMP      R3,#+10              <span style="color: #008000;">; compare with MAX_COUNT</span>
BCC.N    . . .
</pre>
<p>Now assume that process A (e.g. an interrupt) preempts process B (e.g. main thread) somewhere between the instructions above, and executes:</p>
<pre style="padding-left: 30px;">pcom_buf-&gt;rx_count--;</pre>
<p>What will be the value of <strong>pcom_buf-&gt;rx_count</strong> seen by process B in the <strong>if</strong> test?<br />
What the programmer expects the value of <strong>pcom_buf-&gt;rx_count</strong> should be in the <strong>if</strong> test?</p>
<p>Imagine that in place of a simple counter a more complex object, like our Rx FIFO, has to be shared. The number of machine instructions generated for the access will increase and the probability of conflict will increase as well.</p>
<p>This simple example shows why the mutual exclusion represents such an important aspect of embedded programming.</p>
<p>The most logical way to solve this problem is to make sure that <strong>only one process can access the shared object at one time</strong>, and this access has to be complete or <em>atomic</em> (indivisible). The section of code we need to protect from concurrent access is known as <em>critical section</em>.</p>
<p>As for the implementation, most programmers will disable the interrupts before the access and re-enable the interrupts when the access was done. The method works well and without significant performance penalties as long as the critical section is short and the delay introduced by this temporary interrupt disabling is reasonable. The following picture shows the result of disabling interrupts while accessing the shared object:</p>
<p><a href="http://polisoftdesign.com/wp-content/uploads/2010/05/Clipboard05.png"><img class="aligncenter size-full wp-image-360" title="Solving the Mutual Exclusion Problem" src="http://polisoftdesign.com/wp-content/uploads/2010/05/Clipboard05.png" alt="Two Processes that Do Not Conflict over the Shared Resource" width="579" height="143" /></a></p>
<p>The result is obvious: the two processes will access the object sequentially and the process A will be delayed slightly because of process B keeping the CPU locked while the critical section is executed.</p>
<p>Most modern compilers have the support for manipulating the interrupt system. This support is materialized by one of the following: special macros, library functions, inline assembly code or intrinsic functions. Either one is good as long as it is used wisely. For example, GCC for ARM uses the intrinsic functions <strong>__disable_irq</strong>() and <strong>__enable_irq</strong>(), while IAR EWARM uses the intrinsic functions <strong>__disable_interrupt</strong>() and <strong>__enable_interrupt</strong>().</p>
<p>Let’s examine a critical section that is protected by using this method:</p>
<pre><span style="color: #008080;">U8</span>  <span style="color: #ff6600;">Com_ReadRxByte</span> <strong> (</strong><span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>)
{</strong><em><span style="color: #008000;">////////////////////////////////////////////////////////////////////////////////////////</span>
 </em>   <span style="color: #008080;">U8</span>     b_val<strong>; </strong><em>                                 <span style="color: #008000;">// byte holder</span></em>

    <span style="color: #ff6600;">__disable_interrupt</span> ();                        <span style="color: #008000;"><em>// enter the critical section</em></span>
    b_val <strong>=</strong> pcom_buf<strong>-&gt;</strong>rx_buf<strong>[</strong>pcom_buf<strong>-&gt;</strong>rx_head<strong>];   </strong><span style="color: #008000;"><em>// extract one byte and</em></span>
    pcom_buf<strong>-&gt;</strong>rx_head <strong>=</strong> <strong>(</strong>pcom_buf<strong>-&gt;</strong>rx_head <strong>+</strong> 1<strong>)</strong> <strong>% </strong><em> <span style="color: #008000;">// advance the head index and wrap</span></em>
                         pcom_buf<strong>-&gt;</strong>rx_buf_size<strong>;</strong><em>    <span style="color: #008000;">// around if past end of buffer</span></em>
    pcom_buf<strong>-&gt;</strong>rx_count<strong>--;</strong> <em>                         <span style="color: #008000;">// decrement the byte counter</span></em>
    <span style="color: #ff6600;">__enable_interrupt</span> ();                         <span style="color: #008000;"><em>// exit the critical section</em></span>
    <span style="color: #0000ff;"><strong>return</strong></span> b_val<strong>;</strong><em>                                  <span style="color: #008000;">// return the extracted byte</span></em><strong>
}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span></pre>
<p>The statements between the functions <strong>__disable_interrupt</strong>() and <strong>__enable_interrupt</strong>() will have exclusive control of the CPU while the critical section is executed: their result is always predictable.</p>
<p>Is it good enough now? It is definitely better than before but still not perfect.</p>
<p>What happens if the caller disabled the interrupts before invoking <strong>Com_ReadRxByte</strong>()? Executing <strong>__enable_interrupt</strong>() before the return statement, <strong>Com_ReadRxByte</strong>() re-enables the interrupts unconditionally leaving the caller to think that the interrupts are still being disabled. Imagine a situation where the caller enters in its own critical section, then invokes <strong>Com_ReadRxByte</strong>(), executes few more statements after that and, finally, exits the critical section: the last part of the caller critical section remains unprotected.</p>
<p>There are several ways to fix this, but all have something in common: we need to know what is the status of the interrupt system before calling <strong>__disable_interrupt</strong>(). Saving the interrupt state and later restoring it solves this final problem. I will define few macros to deal with this (unfortunately, the definitions are processor and compiler dependent):</p>
<pre><strong>#define</strong> <span style="color: #800080;">INTR_STAT_STOR</span>        <span style="color: #008080;">INTR_STAT</span> __intr_stat__  <em><span style="color: #008000;">// this is storage declaration!</span>

</em><strong>#define</strong> <span style="color: #800080;">IRQ_DISABLE_SAVE</span><strong>()</strong>    __intr_stat__ <strong>=</strong> <span style="color: #ff6600;">__get_PRIMASK</span> <strong>();</strong>    \
                              <span style="color: #ff6600;">__disable_interrupt</span> <strong>()
</strong>
<strong>#define</strong> <span style="color: #800080;">IRQ_ENABLE_RESTORE</span><strong>()</strong>  <span style="color: #ff6600;">__set_PRIMASK</span> <strong>(</strong>__intr_stat__<strong>)</strong></pre>
<p>These macros implemented in IAR EWARM 5.xx will work fine for any Cortex-M3 microcontroller. The first macro (<strong>INTR_STAT_STOR</strong>) defines a local storage of type INTR_STAT (actually U32) that will be used to save the contents of PRIMASK special register that contains the interrupt enable bit. The <strong>IRQ_DISABLE_SAVE</strong>() macro reads the PRIMASK register and store its contents in the <strong>__intr_stat__</strong> location defined before. The IRQ_ENABLE_RESTORE() macro reloads the PRIMASK register with its saved value, restoring the interrupt status.</p>
<p>Now we can put everything together:</p>
<pre><span style="color: #008080;">U8</span>  <span style="color: #ff6600;">Com_ReadRxByte</span> <strong> (</strong><span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>)
{</strong><span style="color: #008000;"><em>////////////////////////////////////////////////////////////////////////////////////////</em></span><em>
 </em>   <span style="color: #008080;">U8</span>     b_val<strong>; </strong><em>                                 <span style="color: #008000;">// byte holder</span></em>
    <span style="color: #800080;">INTR_STAT_STOR</span><strong>; </strong><em>                               <span style="color: #008000;">// interrupt status storage</span></em><span style="color: #008000;">
</span>
    <span style="color: #800080;">IRQ_DISABLE_SAVE</span> ();                           <span style="color: #008000;"><em>// enter the critical section</em></span>
    b_val <strong>=</strong> pcom_buf<strong>-&gt;</strong>rx_buf<strong>[</strong>pcom_buf<strong>-&gt;</strong>rx_head<strong>];   </strong><span style="color: #008000;"><em>// extract one byte and</em></span>
    pcom_buf<strong>-&gt;</strong>rx_head <strong>=</strong> <strong>(</strong>pcom_buf<strong>-&gt;</strong>rx_head <strong>+</strong> 1<strong>)</strong> <strong>% </strong><em> <span style="color: #008000;">// advance the head index and wrap</span></em>
                         pcom_buf<strong>-&gt;</strong>rx_buf_size<strong>;</strong><em>    <span style="color: #008000;">// around if past end of buffer</span></em>
    pcom_buf<strong>-&gt;</strong>rx_count<strong>--;</strong> <em>                         <span style="color: #008000;">// decrement the byte counter</span></em>
    <span style="color: #800080;">IRQ_ENABLE_RESTORE</span> ();                         <span style="color: #008000;"><em>// exit the critical section</em></span>
    <span style="color: #0000ff;"><strong>return</strong></span> b_val<strong>;</strong><em>                                  <span style="color: #008000;">// return the extracted byte</span></em><strong>
}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span></pre>
<p>We will return to the problem of mutual exclusion later in the context of a real-time multitasking environment. In the mean time, try to put everything to work in your projects and post your comments or questions here. Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/05/03/a-matter-of-interrupts-and-mutual-exclusion-part-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Matter of Interrupts and Mutual Exclusion – Part 4</title>
		<link>http://polisoftdesign.com/2010/04/28/a-matter-of-interrupts-and-mutual-exclusion-part-4/</link>
		<comments>http://polisoftdesign.com/2010/04/28/a-matter-of-interrupts-and-mutual-exclusion-part-4/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 21:51:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Drivers]]></category>
		<category><![CDATA[RTOS]]></category>
		<category><![CDATA[active waiting]]></category>
		<category><![CDATA[FIFO]]></category>
		<category><![CDATA[interrupts]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=345</guid>
		<description><![CDATA[Mutual exclusion as a way to ensure that the asynchronous access to a common resource (variable, object, peripheral). [...]]]></description>
			<content:encoded><![CDATA[<p>Today I will modify the code to support FIFO empty/full checking. Having the <strong>rx_counter</strong> to keep track of the actual content of the buffer it will make this task easy:</p>
<pre><span style="color: #008080;">BOOL</span> <span style="color: #ff6600;">Com_IsRxBufEmpty</span> <strong>(</strong><span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>)</strong>
<strong>{</strong><em><span style="color: #008000;">////////////////////////////////////////////////////////////////////////////////////////</span>
 </em>   <span style="color: #0000ff;"><strong>return</strong></span> <strong>(</strong>pcom_buf<strong>-&gt;</strong>rx_count <strong>==</strong> 0<strong>);</strong><em>               <span style="color: #008000;">// return TRUE if empty</span>
</em><strong>}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span>

<span style="color: #008080;">BOOL </span><span style="color: #ff6600;">Com_IsRxBufFull</span> <strong>(</strong><span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>)</strong>
<strong>{</strong><em><span style="color: #008000;">////////////////////////////////////////////////////////////////////////////////////////</span>
   </em> <span style="color: #0000ff;"><strong>return</strong></span> <strong>(</strong>pcom_buf<strong>-&gt;</strong>rx_count <strong>&gt;=</strong> pcom_buf<strong>-&gt;</strong>rx_buf_size<strong>);</strong> <em>  <span style="color: #008000;">// return TRUE if full</span>
</em><strong>}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span></pre>
<p>Or, if you like, write them as macros:</p>
<pre><span style="color: #808000;"><strong>#define</strong></span> <span style="color: #800080;">Com_IsRxBufEmpty</span><strong>(</strong>pcb<strong>)</strong> <strong> (</strong>pcb<strong>-&gt;</strong>rx_count <strong>==</strong> 0<strong>)</strong>
<span style="color: #808000;"><strong>#define</strong></span> <span style="color: #800080;">Com_IsRxBufFull</span><strong>(</strong>pcb<strong>)</strong>   <strong>(</strong>pcb<strong>-&gt;</strong>rx_count <strong>&gt;=</strong> pcb<strong>-&gt;</strong>rx_buf_size<strong>)</strong></pre>
<p>(we will talk more about when to use macros vs. when to use functions).</p>
<p>Now we have the ability to handle the situations where knowing if the FIFO is full or empty is important.</p>
<p>For example, in the <strong>Com_ISR</strong>() function, if the FIFO is full and characters continue to come, one decision may be to drop them (in place of overwriting the buffer):</p>
<pre><span style="color: #0000ff;"><strong>void</strong></span>  <span style="color: #ff6600;">Com_ISR</span>  <strong>(<span style="color: #0000ff;">void</span>)</strong> <em>                      <span style="color: #008000;">// USART Rx handler (ISR)</span>
</em><strong>{</strong><em><span style="color: #008000;">////////////////////////////////////////////////////////////////////////////////////////</span>
</em><em> </em>   <span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>;</strong> <em>               <span style="color: #008000;">// pointer to COM buffer</span>
 </em>   <span style="color: #008080;">U8</span>             b_char<strong>;</strong> <em>                 <span style="color: #008000;">// byte holder</span>
 </em>
    <em><span style="color: #008000;">// . . . . . .                          // identify the interrupt</span>
   </em> pcom_buf <strong>=</strong> <span style="color: #ff6600;">Com_GetBufPtr</span> <strong>(</strong><span style="color: #800080;">USART1</span><strong>);</strong> <em>     <span style="color: #008000;">// obtain the pointer to the circular buffer</span>
 </em> <em>  // . . . . . .                          <span style="color: #008000;">// do other things as required</span>
   </em> b_char <strong>=</strong> <span style="color: #ff6600;">USART_ReceiveData</span> <strong>(</strong><span style="color: #800080;">USART1</span><strong>);</strong> <em>   <span style="color: #008000;">// get one byte from USART1</span>
 </em> <strong>  <span style="color: #0000ff;">if</span></strong><span style="color: #0000ff;"> </span><strong>(!</strong><span style="color: #ff6600;">Com_IsRxBufFull</span> <strong>(</strong>pcom_buf<strong>))</strong> <em>       <span style="color: #008000;">// if FIFO buffer not full</span>
   </em> <strong>{</strong><span style="color: #008000;">
<span style="color: #000000;">        <span style="color: #ff6600;">Com_WriteRxBuf</span> <strong>(</strong>pcom_buf<strong>,</strong> b_char<strong>);</strong> </span></span><em><span style="color: #000000;"> </span><span style="color: #008000;">// write the byte into the circular buffer</span>
   </em> <strong>}</strong>
    <em><span style="color: #008000;">// . . . . . .                          // do other things as required</span>
</em><strong>}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span></pre>
<p>I’m not going to argue about this way of solving the FIFO overrun situation over another solution – the programmer who knows the application can decide what is the best way to handle this.</p>
<p>In the case of <strong>ComGetChar</strong>(), the attempt to extract a byte from a FIFO that is empty will lead, most likely, to waiting. Let’s imagine for a moment that we have the ability to delay the code execution for a number of milliseconds. The parameter <strong>timeout</strong> will indicate the amount of time the function will wait for a character to arrive before returning with an error code. Be aware that I do not say how the delay is actually implemented (in some cases the delay can be invoked by a system function call, if available):</p>
<pre><span style="color: #008080;">S32</span>   <span style="color: #ff6600;">ComGetChar</span>   <strong>(</strong><span style="color: #008080;">U32</span> timeout<strong>)</strong> <em>           <span style="color: #008000;">// the "GetChar()" function</span>
</em><strong>{</strong><span style="color: #008000;"><em>////////////////////////////////////////////////////////////////////////////////////////</em></span><em>
</em><em> </em>   <span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>;</strong> <em>               <span style="color: #008000;">// pointer to COM buffer</span>
   </em> <span style="color: #008080;">U8</span>             b_val<strong>;</strong> <em>                  <span style="color: #008000;">// byte holder</span>
 </em>
    pcom_buf <strong>=</strong> <span style="color: #ff6600;">Com_GetBufPtr</span> <strong>(</strong>USART1<strong>);</strong> <em>     <span style="color: #008000;">// obtain the pointer to the circular buffer</span>
   </em> <em><span style="color: #008000;">// . . . . . .                          // do other things as required</span>
</em>    <span style="color: #0000ff;"><strong>while</strong> </span><strong>(</strong><span style="color: #ff6600;">Com_IsRxBufEmpty</span> <strong>(</strong>pcom_buf<strong>))</strong> <em>    <span style="color: #008000;">// as long as the FIFO is empty</span>
 </em> <strong>  {</strong>
   <strong>     <span style="color: #0000ff;">if</span></strong><span style="color: #0000ff;"> </span><strong>(</strong>timeout <strong>==</strong> 0<strong>)</strong> <em>                  <span style="color: #008000;">// if time is out</span>
 </em>       <strong>{</strong>
            <span style="color: #0000ff;"><strong>return</strong> </span><strong>(-</strong>1<strong>);</strong> <em>                   <span style="color: #008000;">// return -1 as error code</span>
 </em>       <strong>}</strong>
        <strong>else</strong>                                <span style="color: #008000;"><em>// otherwise</em></span>
        <strong>{</strong>
            timeout<strong>--;</strong>                      <span style="color: #008000;"><em>// update the delay counter</em></span>
 <strong>       }</strong>
        <span style="color: #ff6600;">DelayMilliseconds</span> <strong>(</strong>1<strong>);</strong> <em>             <span style="color: #008000;">// delay one millisecond and wait more</span>
</em>    <strong>}</strong>
    b_val <strong>=</strong> <span style="color: #ff6600;">Com_ReadRxByte</span> <strong>(</strong>pcom_buf<strong>);</strong> <em>     <span style="color: #008000;">// extract character from the circular buffer</span>
 </em> <strong>  <span style="color: #0000ff;">return</span></strong><span style="color: #0000ff;"> </span><strong>(</strong><span style="color: #008080;">S32</span><strong>)</strong>b_val <strong>&amp;</strong> 0xFF<strong>;</strong> <em>              <span style="color: #008000;">// return character as a 32-bit signed int</span>
</em><strong>}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span></pre>
<p>Essentially, when the FIFO is empty, the execution will stall for <strong>timeout</strong> milliseconds. The caller should be aware of this. In the context of a multi-tasking environment, delaying (or looping for long times), in the right conditions, will not stop other tasks to be executed. However, in a simple foreground/background environment where the CPU executes one thread that may only be interrupted by ISR execution, waiting can freeze the application.</p>
<p>There are many ways of avoiding this active waiting.</p>
<ul>
<li>The easiest way is to check the FIFO status before invoking <strong>ComGetChar</strong>(): if there are characters, the function can be called without time penalty: if not, the program can continue on a different path (assuming the data is not temporarily needed). This is also the essence of <em>cooperative multi-tasking</em>: when one thread reaches the point where it has to wait it yields control to a different thread and when that thread needs to wait the yield process continues. Cooperative multi-tasking can be implemented in many ways: state machines, co-routines, etc.</li>
<li>Another way is to use a <em>preemptive multi-tasking</em> approach where the tasks are interrupted from time to time (even when no I/O is involved) and executed according to a pre-established CPU sharing policy. This way no task can freeze the entire system while waiting for data or an event to happen. What a modern preemptive RTOS does is just this – it multiplexes the CPU based on a certain policy involving priorities, time sharing and cooperative primitives. But this is a much longer discussion…</li>
</ul>
<p>In the following post I will return to the mutual exclusion problem in the context of the simple situation of a single tasking with interrupts (or foreground/background) programming environment. Have patience and post your comments here!</p>
]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/04/28/a-matter-of-interrupts-and-mutual-exclusion-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Matter of Interrupts and Mutual Exclusion – Part 3</title>
		<link>http://polisoftdesign.com/2010/04/27/a-matter-of-interrupts-and-mutual-exclusion-part-3/</link>
		<comments>http://polisoftdesign.com/2010/04/27/a-matter-of-interrupts-and-mutual-exclusion-part-3/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 23:07:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Drivers]]></category>
		<category><![CDATA[RTOS]]></category>
		<category><![CDATA[communication driver]]></category>
		<category><![CDATA[FIFO]]></category>
		<category><![CDATA[interrupts]]></category>
		<category><![CDATA[mutual exclusion]]></category>

		<guid isPermaLink="false">http://polisoftdesign.com/?p=339</guid>
		<description><![CDATA[Mutual exclusion as a way to ensure that the asynchronous access to a common resource (variable, object, peripheral). [...]]]></description>
			<content:encoded><![CDATA[<p>Studying the implementation of the FIFO buffer from my previous posting some may have realized already that the code does not address few important things:</p>
<ul>
<li>The example does not give the reader any indication where the buffer is actually allocated and how and when this allocation is done.</li>
<li>There is no check if the FIFO buffer is empty (in <strong>ComGetChar</strong>) or full (in <strong>Com_ISR</strong>) – the <strong>rx_counter</strong> is not used anywhere to detect such conditions despite of the declared intention of making it the holder of the actual number of bytes in the FIFO.</li>
<li>There is no mutual exclusion mechanism in place to prevent concurrent access to either the buffer itself or to the <strong>rx_counter</strong> that is, you heard it right, just another shared resource requiring protection.</li>
</ul>
<p>Judging by the way the FIFO data structure was declared, the buffer itself is not allocated statically when a variable of COM_RX_BUFFER type is defined. We need either a pre-allocated buffer of a given size or a dynamically allocated piece of memory to initialize the <strong>rx_buf</strong> pointer. I think the best idea is to let the caller perform these operations, offering just the right means to do it.</p>
<p>The easiest way is to declare some storage area, statically allocated, and have a function to perform the initialization. The user must write something like:</p>
<pre><span style="color: #808000;"><strong>#define</strong></span> <span style="color: #800080;">RX_BUFFER_SIZE</span>       128

<span style="color: #008080;">U8</span>      MyRxStorage<strong>[</strong><span style="color: #800080;">RX_BUFFER_SIZE</span><strong>];

<span style="color: #0000ff;">void</span></strong> <span style="color: #ff6600;">MyFunction</span>  <strong>(<span style="color: #0000ff;">void</span>)</strong> <em>                    <span style="color: #008000;">// user function</span></em>
<strong>{</strong><em><span style="color: #008000;">////////////////////////////////////////////////////////////////////////////////////////</span>
 </em> <em>  <span style="color: #008000;">// . . . . . .                          // code that does not require serial I/O</span>
</em>    <span style="color: #ff6600;">ComRxBufInit</span> <strong>(</strong>MyRxStorage<strong>,</strong> <em>             <span style="color: #008000;">// initialize the Rx FIFO before</span>
                 </em> <span style="color: #800080;">RX_BUFFER_SIZE</span><strong>);</strong>          <em><span style="color: #008000;">// using it later in the function</span>
</em>    <em><span style="color: #008000;">// . . . . . .</span>
</em>    UserChar <strong>=</strong> <span style="color: #ff6600;">ComGetChar</span> <strong>(</strong>1000<strong>);</strong>           <span style="color: #008000;"><em>// now you can read one byte</em></span>
 <em>   <span style="color: #008000;">// . . . . . .</span>                          <span style="color: #008000;">// do other things as required</span>
</em><strong>}</strong> <em><span style="color: #008000;">///////////////////////////////////////////////////////////////////////////////////////</span>
</em></pre>
<p>In the case of dynamically allocated memory, you will have to obtain the buffer by calling:</p>
<pre style="padding-left: 30px;">MyRxStorage <strong>=</strong> <span style="color: #ff6600;">malloc</span> <strong>(</strong><span style="color: #800080;">RX_BUFFER_SIZE</span><strong>);</strong></pre>
<p>and declaring <strong>MyRxStorage</strong> as a pointer not as an array. But I’m against using dynamic allocation in embedded programming. Keep an eye on my blog and&#8230; one day I will tell you why.</p>
<p>The function <strong>ComRxBufInit</strong>() will look like the one below:</p>
<pre><strong>void</strong>  <span style="color: #ff6600;">ComRxBufInit</span>  <strong>(</strong><span style="color: #008080;">U8</span> <strong>*</strong>pbuff<strong>,</strong> <span style="color: #008080;">U32</span> size<strong>)</strong> <em>  <span style="color: #008000;">// Initialize the Rx FIFO structure</span>
</em><strong>{</strong><em><span style="color: #008000;">///|///////////////////////////////////////|////////////////////////////////////////////</span>
 </em>   <span style="color: #008080;">COM_RX_BUFFER</span> <strong>*</strong>pcom_buf<strong>;</strong>                <em><span style="color: #008000;">// pointer to COM buffer</span>
 </em>
    pcom_buf <strong>=</strong> <span style="color: #ff6600;">Com_GetBufPtr</span> <strong>(</strong><span style="color: #800080;">USART1</span><strong>);</strong>      <em><span style="color: #008000;">// obtain the pointer to the circular buffer</span>
   </em> pcom_buf<strong>-&gt;</strong>rx_buf <strong>=</strong> pbuff<strong>;</strong> <em>              <span style="color: #008000;">// store the FIFO buffer pointer</span>
   </em> pcom_buf<strong>-&gt;</strong>rx_buf_size <strong>=</strong> size<strong>;</strong>           <em><span style="color: #008000;">// and its size</span>
   </em> pcom_buf<strong>-&gt;</strong>rx_count <strong>=</strong> 0<strong>;</strong>                 <em><span style="color: #008000;">// reset the byte counter</span>
   </em> pcom_buf<strong>-&gt;</strong>rx_head <strong>=</strong> 0<strong>;</strong> <em>                 <span style="color: #008000;">// and the head</span>
   </em> pcom_buf<strong>-&gt;</strong>rx_tail <strong>=</strong> 0<strong>;</strong> <em>                 <span style="color: #008000;">// and tail pointers</span>
 </em> <em>  <span style="color: #008000;">// . . . . . .                          // do other initialization things</span>
 </em><strong>}</strong> <span style="color: #008000;"><em>///////////////////////////////////////////////////////////////////////////////////////</em></span></pre>
<p>As a side note, the function <strong>Com_GetBufPtr</strong>() was implemented to help the programmer to expand the code for more than one serial interface. In the end of my series of posts dedicated to this subject I will offer a fully functional code that will be able to handle any number of serial interfaces – the only part the programmer should be providing would be the lower layer that give access to the USART registers and the hardware initialization required by the MCU (I/O pins, baud rate, etc.)</p>
<p>I know this looks to many like a never ending story. Believe me, it has an ending or, even better, a <em>happy ending</em>. Stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://polisoftdesign.com/2010/04/27/a-matter-of-interrupts-and-mutual-exclusion-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

