<?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>Stack Overflow</title>
	<atom:link href="http://embeddedgurus.com/stack-overflow/feed/" rel="self" type="application/rss+xml" />
	<link>http://embeddedgurus.com/stack-overflow</link>
	<description>Thoughts on embedded systems by Nigel Jones</description>
	<lastBuildDate>Wed, 01 Feb 2012 20:38:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>The absolute truth about abs()</title>
		<link>http://embeddedgurus.com/stack-overflow/2012/02/the-absolute-truth-about-abs/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2012/02/the-absolute-truth-about-abs/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 12:05:11 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[General C issues]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=772</guid>
		<description><![CDATA[One of the more depressing things about the C language is how often the results of various operations are undefined. A prime example of this is the abs() function that I&#8217;m fairly sure is liberally dispersed throughout your code (it is through mine). The undefined operation of the abs() function comes about if you have [...]]]></description>
			<content:encoded><![CDATA[<p>One of the more depressing things about the C language is how often the results of various operations are undefined. A prime example of this is the abs() function that I&#8217;m fairly sure is liberally dispersed throughout your code (it is through mine). The undefined operation of the abs() function comes about if you have the temerity to use a compiler that represents negative numbers using 2&#8242;s complement notation. In this case, the most negative representable number is always numerically larger than the most positive representable number. In plain English, for 16 bit integers, the range is -32768 &#8230; + 32767. Thus if you pass -32768 to the abs() function, the result is undefined.</p>
<p>The problem of course in an embedded system is that undefined operations are just dangerous, so surely an embedded compiler will do something sensible, like return +32767 if you pass -32768 to abs? To test this hypothesis I whipped up the following code for my favourite 8 bit compiler (IAR&#8217;s AVR compiler).</p>
<pre>#include &lt;stdlib.h&gt;
#include &lt;inttypes.h&gt;
#include &lt;stdio.h&gt;

void main(void)
{
    int16_t i;
    int16_t absi;

    i = INT16_MIN + 1;        /* Set i to one more than the most negative number */
    absi = abs(i);

    printf("Argument = %" PRId16 ". Absolute value of argument = %" PRId16, i, absi);

    i--;                    /* i should now equal INT16_MIN */
    absi = abs(i);
    printf("\nArgument = %" PRId16 ". Absolute value of argument = %" PRId16, i, absi);
}</pre>
<p>If you don&#8217;t understand the printf strings, see this <a href="http://embeddedgurus.com/stack-overflow/2011/02/formatted-output-when-using-c99-data-types/">article</a>. Here&#8217;s the output of this code:</p>
<pre>Argument = -32767. Absolute value of argument = 32767
Argument = -32768. Absolute value of argument = -32768</pre>
<p>Clearly abs(-32768) = -32768 is not a very useful result! If I look in &lt;stdlib.h&gt; I find that abs() is implemented as</p>
<pre>  int abs(int i)
  {      /* compute absolute value of int argument */
    return (i &lt; 0 ? -i : i);
  }</pre>
<p>Clearly no check is being made on the bounds of the parameter, and so the result that we get depends upon how the negation of the argument is performed. Thus this leads me to my first suggestion, namely write your own abs function. I&#8217;ll call this function sabs() for safe abs(). The first pass implementation for sabs() looks like this (note you&#8217;ll have to include &lt;limits.h&gt; to get INT_MIN and INT_MAX):</p>
<pre>int sabs(int i)
{
    int res;

    if (INT_MIN == i)
    {
        res = INT_MAX;
    }
    else
    {
        res = i &lt; 0 ? -i : i;
    }

    return res;
}</pre>
<p>Here&#8217;s the output:</p>
<pre>Argument = -32767. Absolute value of argument = 32767
Argument = -32768. Absolute value of argument = 32767</pre>
<p>I think for most embedded systems this is a better result. However what happens if you use a smaller integer than the native integer size (e.g. a 16 bit integer on a 32 bit system, or an 8 bit integer on a 16 bit system?). To test this question, I modified the code thus:</p>
<pre>#include &lt;stdlib.h&gt;
#include &lt;limits.h&gt;
#include &lt;inttypes.h&gt;
#include &lt;stdio.h&gt;

int sabs(int i);

void main(void)
{
    int8_t i;
    int8_t absi;

    i = INT8_MIN + 1;        /* Set i to one more than the most negative number */
    absi = sabs(i);

    printf("Argument = %" PRId8 ". Absolute value of argument = %" PRId8, i, absi);

    i--;                    /* i should now equal INT8_MIN */
    absi = sabs(i);
    printf("\nArgument = %" PRId8 ". Absolute value of argument = %" PRId8, i, absi);
}

int sabs(int i)
{
    int res;

    if (INT_MIN == i)
    {
        res = INT_MAX;
    }
    else
    {
        res = i &lt; 0 ? -i : i;
    }

    return res;
}</pre>
<p>So in this case, the native integer size is 16 bits and I&#8217;m passing an 8 bit integer. Here&#8217;s the output:</p>
<p>Argument = -127. Absolute value of argument = 127<br />
Argument = -128. Absolute value of argument = -128</p>
<p>Clearly, I still haven&#8217;t solved the problem, as I&#8217;d really like abs(-128) to be 127 when using 8 bit integers.  I suspect that I could come up with some fancy expression that handles all integer types.  However I&#8217;m a great believer in simple code, and so  my recommendation is that you write sabs() functions for all your integer types. Thus:</p>
<pre>/* Safe 8 bit absolute function */</pre>
<pre>int8_t sabs8(int8_t i)
{
    int8_t res;

    if (INT8_MIN == i)
    {
        res = INT8_MAX;
    }
    else
    {
        res = i &lt; 0 ? -i : i;
    }

    return res;
}</pre>
<pre>/* Safe 16 bit absolute function */</pre>
<pre>int16_t sabs16(int16_t i)
{
    int16_t res;

    if (INT16_MIN == i)
    {
        res = INT16_MAX;
    }
    else
    {
        res = i &lt; 0 ? -i : i;
    }

    return res;
}</pre>
<pre>/* Safe 32 bit absolute function */</pre>
<pre>int32_t sabs32(int32_t i)
{
    int32_t res;

    if (INT32_MIN == i)
    {
        res = INT32_MAX;
    }
    else
    {
        res = i &lt; 0 ? -i : i;
    }

    return res;
}</pre>
<p>&nbsp;</p>
<p>The above approach is all well and good, but let&#8217;s face it, I&#8217;ve added a lot of overhead for a very rare condition. So this raises the question as to whether there is a better way of doing things? Well in many cases we use the abs() function to check for some limit. For example</p>
<pre>    if (abs(i) &gt; SOME_LIMIT)
    {
        printf("\nLimit exceeded");
    }</pre>
<p>In cases like these, you can use what I call a negative absolute function, aka nabs(). nabs() works with negative absolutes and so can&#8217;t overflow. To demonstrate, here&#8217;s the code:</p>
<pre>int nabs(int i);

void main(void)
{
    int i;
    int absi;

    i = INT_MIN + 1;        /* Set i to one more than the most negative number */
    absi = nabs(i);

    printf("Argument = %d Negative absolute value of argument = %d", i, absi);

    i--;                    /* i should now equal INT_MIN */
    absi = nabs(i);
    printf("\nArgument = %d Negative absolute value of argument = %d", i, absi);

    i = INT_MAX;
    absi = nabs(i);
    printf("\nArgument = %d Negative absolute value of argument = %d", i, absi);
}

int nabs(int i)
{
    return i &gt; 0 ? -i : i;
}</pre>
<p>The output looks like this:</p>
<pre>Argument = -32767 Negative absolute value of argument = -32767
Argument = -32768 Negative absolute value of argument = -32768
Argument = 32767 Negative absolute value of argument = -32767</pre>
<p>Armed with this function, you merely flip your tests around, such that you have:</p>
<pre>    if (nabs(i) &lt; SOME_NEGATIVE_LIMIT)
    {
        printf("\nLimit exceeded");
    }</pre>
<p>I&#8217;ll leave it to you to decide whether gaining the efficiency is worth it for the rather strange looking code.</p>
<p>As a final note, do a search for the abs() function on the Internet. You&#8217;ll find that most references don&#8217;t mention the undefined behavior of abs with INT_MIN as an argument. The notable exception is the always excellent <a href="http://www.gnu.org/software/libc/manual/html_node/Absolute-Value.html">GNU reference</a> . It&#8217;s thus hardly surprising that most embedded systems use abs().</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2012/02/the-absolute-truth-about-abs/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Simplify, then add lightness</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/12/simplify-then-add-lightness/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/12/simplify-then-add-lightness/#comments</comments>
		<pubDate>Sat, 31 Dec 2011 18:34:00 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Consulting]]></category>
		<category><![CDATA[General C issues]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=757</guid>
		<description><![CDATA[As 2011 draws to a close I have reason to be thinking about things automotive. As part of my musings, I was reminded of the famous mantra espoused by the late Colin Chapman of Lotus Cars &#8211; &#8216;Simplify, then add lightness&#8217;. I have always liked this aphorism for its idea of &#8216;adding lightness&#8217; rather than [...]]]></description>
			<content:encoded><![CDATA[<p>As 2011 draws to a close I have reason to be thinking about things automotive. As part of my musings, I was reminded of the famous mantra espoused by the late Colin Chapman of Lotus Cars &#8211; &#8216;Simplify, then add lightness&#8217;. I have always liked this aphorism for its idea of &#8216;adding lightness&#8217; rather than &#8216;subtracting weight&#8217;.</p>
<p>So what&#8217;s this got to do with embedded systems you ask? Well, when it comes to embedded systems programming, I think Chapman&#8217;s concept is spot on. While most people would probably agree that simplifying an embedded system is a good thing, I wonder though how many actively work so as to achieve this? In my case I regularly hold conversations with my clients which can be summarized as: <em>Yes I can do that, but it comes at the expense of complexity &#8211; and complexity leads to bugs &#8211; and bugs are very expensive.</em> I have found that clients are quite appreciative of this as it forces them to evaluate what is truly important about the product. Incidentally, when I first started in the consulting business, I thought that it was my job to give the client whatever it was they asked for. The fact that in doing so I was often giving them a serious disservice was quite a revelation when the penny finally dropped.</p>
<p>So what about the &#8216;adding lightness&#8217; directive? Well clearly this is an interesting concept when it comes to firmware. I take it to mean that the code should be simple, easy to read, and fast in execution &#8211; in other words not unlike a Lotus sports car. If I have cause to re-read the code many months or years later and I find that the code has stood the test of time and is a pleasure to read, then I think I have achieved the required lightness. If by contrast the code is out of date and ugly to read then I know I have failed. In short it&#8217;s the difference between designing a <a href="http://en.wikipedia.org/wiki/Lotus_Elan">Lotus Elan</a> and an <a href="http://en.wikipedia.org/wiki/AMC_Pacer">AMC Pacer</a>.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/12/simplify-then-add-lightness/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Novel uses for RTC registers</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/12/novel-uses-for-rtc-registers/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/12/novel-uses-for-rtc-registers/#comments</comments>
		<pubDate>Sun, 04 Dec 2011 14:25:44 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Hardware]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=646</guid>
		<description><![CDATA[For obvious reasons, I usually write about things that are widely applicable. Today I&#8217;m going to deviate from this slightly and talk about the real time clock registers / RAM that are available on some (many?) ARM processors as well as I suspect a number of other architectures. An excerpt from the NXP data sheet [...]]]></description>
			<content:encoded><![CDATA[<p>For obvious reasons, I usually write about things that are widely applicable. Today I&#8217;m going to deviate from this slightly and talk about the real time clock registers / RAM that are available on some (many?) ARM processors as well as I suspect a number of other architectures. An excerpt from the NXP data sheet is shown in the figure below.</p>
<div id="attachment_672" class="wp-caption aligncenter" style="width: 714px"><a href="http://embeddedgurus.com/stack-overflow/files/2011/02/ARM_RTC_Registers.jpg"><img class="size-full wp-image-672" src="http://embeddedgurus.com/stack-overflow/files/2011/02/ARM_RTC_Registers.jpg" alt="" width="704" height="777" /></a><p class="wp-caption-text">NXP LPC17xx RTC registers</p></div>
<p>Of most interest is the column labeled &#8216;Reset Value&#8217;. You will notice that the values highlighted in red are &#8216;NC&#8217;. &#8216;NC&#8217; means that the registers are unaffected by a reset condition. Furthermore, these particular registers may also be powered from an alternate power source such that they are also unaffected by loss of power. So why is this useful? Well I have found a couple of uses for them beyond the obvious and intended applications of maintaining date and time (for the RTC registers) and for providing non-volatile R/W storage for the General Purpose registers.</p>
<h2>Communicating with the Bootstrap loader</h2>
<p>Most embedded applications today contain a bootstrap loader (BSL). Although there are several ways of entering the BSL from the main application, the most common that I see is to force a watchdog reset, resulting in the CPU rebooting and starting up in the BSL. This technique is pretty good and I use it all the time. However I usually find it necessary for the main application to communicate some information to the BSL. For example, at a minimum the BSL needs to know that it has been intentionally entered for the purposes of performing a firmware update (as opposed to being entered as a result of a genuine watchdog failure). Under some circumstances I also need to pass other information to the BSL such as the port that initiated the update. In the past I have tended to pass this information via EEPROM. However with these registers available to me, I now use them for this task.</p>
<h2>Debugging</h2>
<p>If you are plagued with your system taking unexpected resets, then it&#8217;s a relatively trivial matter to write some debug code that writes context information to these registers. For example most RTOS provide mechanisms for calling user functions prior to performing a task switch. Within this function it&#8217;s trivial to write the task ID to one of these registers. Then it&#8217;s just a matter of putting a breakpoint on the entry into main() to discover which task was running when the reset occurred. Once you have it narrowed down to a task, you can then instrument functions in a similar manner.</p>
<p>I suspect I may find other uses for these registers in the future. Suffice to say I&#8217;d really like it if this feature became widespread across all processor families.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/12/novel-uses-for-rtc-registers/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>An open letter to the developers of the MPLAB IDE</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/09/an-open-letter-to-the-developers-of-the-mplab-ide/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/09/an-open-letter-to-the-developers-of-the-mplab-ide/#comments</comments>
		<pubDate>Wed, 28 Sep 2011 00:21:57 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Compilers / Tools]]></category>
		<category><![CDATA[Microchip]]></category>
		<category><![CDATA[MPLAB]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=749</guid>
		<description><![CDATA[I recently inherited a project that uses a Microchip PIC18 processor. Without going into too much detail, suffice it to say that I ended up using Microchip&#8217;s MPLAB IDE Version 8.73 together with Microchip&#8217;s C compiler. It had been a number of years since I last used MPLAB, in part because my experience back then [...]]]></description>
			<content:encoded><![CDATA[<p>I recently inherited a project that uses a Microchip PIC18 processor. Without going into too much detail, suffice it to say that I ended up using Microchip&#8217;s MPLAB IDE Version 8.73 together with Microchip&#8217;s C compiler. It had been a number of years since I last used MPLAB, in part because my experience back then was so painful. I was heartened to see that the version number had jumped from 6.X to 8.X and so I was fully expecting to find an IDE that was at the very least, decent. Boy was I disappointed. In no particular order, here are some of the head-slapping things I discovered. Disclaimer: I&#8217;m no MPLAB expert (and quite frankly after this experience I doubt I will ever become one). Thus it&#8217;s entirely possible that the issues listed below are a reflection of my incompetence.</p>
<h3>No editor support for splitting the window</h3>
<p>The title says it all. Text editors back in the DOS allowed you to open a file and look at various parts of the file at the same time via split windows. This is such a fundamental operation for text editors that I couldn&#8217;t believe it wasn&#8217;t supported. Do the developers of MPLAB use an editor with this limitation?</p>
<h3>No single file compilation</h3>
<p>There appears to be no way to simply compile a single file. Instead one is forced to perform a make. Not only is this really time consuming as make wades through all the files that aren&#8217;t relevant, it&#8217;s also a pain because:</p>
<ul>
<li>It forces you to correct problems in the first file that make finds to process &#8211; rather than the one you are interested in.</li>
<li>If the compilation passes, it proceeds immediately to the link and download phase &#8211; regardless whether you want to or not.</li>
</ul>
<h3>A baffling debugger configuration interface</h3>
<p>The first time I tried to download to the debugger, I received an error message telling me that there was a problem with the configuration bits. I beat my head against the issue for a few hours and in the end called a colleague who is a Microchip Consultant (Matt).  Matt told me that he avoided using MPLAB, but vaguely recollected that you had to configure the debugger to explicitly download to the target. Well Matt was spot on. I was just left wondering why anyone would want to debug code without having it downloaded first.</p>
<h3>A joke of a simulator</h3>
<p>While I was waiting to get hold of Matt, I experimented with the simulator. Despite the documentation saying that various peripherals were supported, I found that the simulator simply didn&#8217;t support them. Matt confirmed that the simulator was a piece of junk that no one bothered using.</p>
<h3>Unnecessary variable scope limitation</h3>
<p>I&#8217;m not sure if this is an IDE or a compiler issue. Anyway, when debugging within MPLAB, I discovered that if I had the temerity to declare a variable as static, then the only time I could examine its value was if the variable was in compiler scope. That is, if I was stopped in file foo.c, then the debugger would not let me see the values of static variables declared in bar.c. As a result, I was forced to declare variables as global simply so that I could look at them. Quite frankly, it blows my mind that in 2011 an IDE can force you to adopt lousy programming practices because of its limitations.</p>
<h3>No pointer dereferencing</h3>
<p>In a similar vein, I discovered that MPLAB only shows you the values of pointers, and not what they are pointing to. I thought that limitation disappeared at least ten years ago.</p>
<h3>Limited support for &#8216;large &#8216;arrays</h3>
<p>The PIC18 doesn&#8217;t handle arrays or structures greater than 256 bytes very well. However the Microchip compiler guys came up with a decent work around that is quite straight forward to use &#8211; until you want to look at the array in the debugger. In a nutshell all you seem to be able to do is examine the array / structure in the memory window. You can forget about looking at 16 bit integers, or other such &#8216;complex&#8217; constructs.</p>
<h3>Breakpoints that aren&#8217;t where I put them</h3>
<p>I discovered that placing a breakpoint on a function call was highly problematic. In some cases the break would occur prior to the call, and in other cases it would occur after the call. If I wanted the breakpoint in the called function, I&#8217;d put it there myself, thank you.</p>
<p>Anyway, I could go on &#8211; but I think you get the picture. What I don&#8217;t get is this. Microchip is a big successful company. Why, after a decade of trying can&#8217;t they come up with a decent development environment? It has got to be costing them a lot of design wins when people such as myself cringe at the though of having to use their tools.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/09/an-open-letter-to-the-developers-of-the-mplab-ide/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Effective C Tip #9 – use #warning</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/09/effective-c-tip-9-%e2%80%93-use-warning/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/09/effective-c-tip-9-%e2%80%93-use-warning/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 22:21:28 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Effective C/C++]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=744</guid>
		<description><![CDATA[This is the ninth in a series of tips on writing effective C. Way back in 1999 I wrote an article for Embedded Systems Programming concerning the #error directive. If you aren&#8217;t particularly familiar with #error, then I suggest you read the article. While the #error directive has remained one of my most popular tools, [...]]]></description>
			<content:encoded><![CDATA[<p>This is the ninth in a <a href="http://embeddedgurus.com/stack-overflow/2009/02/effective-c-tips-1-using-vsprintf/">series</a> of tips on writing effective C. Way back in 1999 I wrote an <a href="http://www.rmbconsulting.us/in-praise-of-the-c-preprocessors-error-directive">article </a>for Embedded Systems Programming concerning the #error directive. If you aren&#8217;t particularly familiar with #error, then I suggest you read the article. While the #error directive has remained one of my most popular tools, I have become an equally big fan of #warning.</p>
<p>Before I delve into the uses of #warning, I must warn you (if you would pardon the pun) that #warning is a non standard directive. However it is supported by IAR, GCC, Microchip&#8217;s C18 compiler, Hi-Tech and probably a whole raft of other vendors. In other words, it&#8217;s pretty standard for a non-standard feature.</p>
<p>The use of #warning is simple enough:</p>
<pre>#warning This is a warning</pre>
<p>This will result in the compiler issuing a warning with the text &#8216;This is a warning&#8217; printed to stderr. Please note that, just as for #error, there is *no* requirement that the text be in quotes. If you insist on putting quotes around the text, then they will be printed to stderr as well.</p>
<p>With the syntax out of the way, here&#8217;s some of the ways that I use #warning.</p>
<h3>Protecting Incomplete Code</h3>
<p>Very often when I&#8217;m coding, I like to get the big picture in place without worrying about the minutiae of the implementation details.  As a result I end up with functions or loop bodies that are incomplete. In these cases I simply add a #warning to alert me to the issue. For example</p>
<pre>void foo(void)
{</pre>
<pre>#warning To be completed</pre>
<pre>}</pre>
<p>Thus what happens now is that whenever I compile the module, I get a warning (i.e. reminder) that there is something important still to be done.</p>
<h3>Commenting Out Code</h3>
<p>I *never* comment code out anymore as part of the debugging process, as it is simply too easy to forget that the code has been removed. Instead I use this construct:</p>
<pre>void foo(void)</pre>
<pre>{</pre>
<pre># if 0</pre>
<pre>   /* Code to be temporarily removed is here */</pre>
<pre>#else</pre>
<pre>#warning Temporary debug construct. Fix me!
   /* Experimental code goes here */</pre>
<pre>#endif</pre>
<pre>}</pre>
<p>In this case whenever I compile the module, I get a warning (i.e. reminder) that I have some experimental code in the image.</p>
<h3>The Key Final Step</h3>
<p>While the above are useful constructs, the real power of #warning comes if you configure your compiler to treat warnings as errors for the release build. If you do this and you have inadvertently left incomplete or debug code in the image, then your compilation will fail. In short, this technique will guarantee that you never release code that includes / excludes code that shouldn&#8217;t / should be there. That&#8217;s effective C.</p>
<p><a href="http://embeddedgurus.com/stack-overflow/2009/12/effective-c-tip-8-structure-comparison/">Previous Tip</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/09/effective-c-tip-9-%e2%80%93-use-warning/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Rabbit patches and embedded systems</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/08/rabbit-patches-and-embedded-systems/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/08/rabbit-patches-and-embedded-systems/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 14:09:18 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=739</guid>
		<description><![CDATA[You may think from the title that I&#8217;m writing about Rabbit microprocessors &#8211; but no I&#8217;m actually intending to talk about bunnies. What you ask do rabbits have to do with embedded systems? Well read on and find out&#8230; If you have ever had a vegetable garden then you will know that they are magnets [...]]]></description>
			<content:encoded><![CDATA[<p>You may think from the title that I&#8217;m writing about Rabbit microprocessors &#8211; but no I&#8217;m actually intending to talk about bunnies. What you ask do rabbits have to do with embedded systems? Well read on and find out&#8230;</p>
<p>If you have ever had a vegetable garden then you will know that they are magnets for rabbits. Furthermore, you will soon find out that it takes extraordinary efforts to keep the rabbits out, as they have a tremendous ability to circumvent all sorts of fences.  When faced with such a problem, it is sometimes advisable to build a rabbit patch. The basic idea is this &#8211; you plant your garden and put a fence around it, and then on the outside of the fence you plant a second vegetable garden that is purely for the rabbits &#8211; i.e. a rabbit patch. The rabbits feed on the rabbit patch and leave your real garden alone because they would have to exert effort to get to it &#8211; and they don&#8217;t need to as there needs are satiated by the rabbit patch.</p>
<p>So what has this to do with embedded systems? Well let me describe a scenario to you that is almost certainly all too familiar to anyone that has been doing this for a few years.</p>
<p>It&#8217;s dog and pony show time and marketing is coming to pronounce judgement on your latest creation. Now if you are fortunate, the folks in marketing are a pleasure to work with. However from time to time, you run into someone who is incapable of attending a dog and pony show without offering criticisms / complaints. (I&#8217;m talking about the sort of person who would have criticized <a href="http://en.wikipedia.org/wiki/David_%28Michelangelo%29">Michelangelo&#8217;s David</a> at its unveiling). When faced with such an individual, I have found that the answer is to build the embedded system&#8217;s equivalent of a rabbit patch. It works like this. You intentionally put into the demonstration something that obviously isn&#8217;t quite right. Come time for the dog and pony show, the complainer latches on to the &#8216;problem&#8217;, and proceeds to explain in detail why it is wrong. You sit there and graciously accept the pearls of wisdom dispensed to you. You can then proceed to the meat of the presentation and get some useful work done.  The meeting ends and our protagonist walks away happy &#8211; and you have managed to actually have a useful and productive meeting. Naturally the fix to the &#8216;problem&#8217; is a flick of a compilation switch.</p>
<p>So now you know what a rabbit patch is. I encourage you to use it sparingly. I also encourage you to watch out for it being used on you! I have sat in on a couple of presentations where I&#8217;m pretty sure a rabbit patch has been deployed. Fortunately I&#8217;m also pretty sure the rabbit patch wasn&#8217;t for my benefit&#8230;</p>
<p>On a personal note, I&#8217;m expecting to return to my normal blogging schedule. The long awaited hardware test may actually make an appearance soon.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/08/rabbit-patches-and-embedded-systems/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How to lockup the in-flight entertainment system on a Boeing 777</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/06/how-to-lockup-the-in-flight-entertainment-system-on-a-boeing-777/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/06/how-to-lockup-the-in-flight-entertainment-system-on-a-boeing-777/#comments</comments>
		<pubDate>Sat, 18 Jun 2011 14:31:59 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Firmware Bugs]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=725</guid>
		<description><![CDATA[I have recently returned from  a short trip to the UK. I flew both ways on what appeared to be a relatively new Boeing 777 courtesy of  United Airlines. As is now common place on trans-Atlantic wide-body aircraft, my seat came with its own in-flight entertainment system. After I took my seat to fly to [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently returned from  a short trip to the UK. I flew both ways on what appeared to be a relatively new Boeing 777 courtesy of  United Airlines. As is now common place on trans-Atlantic wide-body aircraft, my seat came with its own in-flight entertainment system. After I took my seat to fly to London, I was a little surprised to see that the in-flight entertainment system was suddenly rebooted. How did I know this? Well there was cute Linux penguin in the top left hand corner, plus I (and the rest of the plane) was treated to the always delightful task of watching hundreds of lines of startup script scrolling across the screen. After a minute or two the reboot came to an end and I was presented with the now standard touch screen user interface.This should have given me a hint that the in-flight entertainment system wasn&#8217;t the most stable of applications.</p>
<p>Now flights from the east coast of the USA to Europe tend to be night flights, and this flight was no exception. Being a seasoned traveler I have my trans-Atlantic night flight routine down pat. Get settled in, have something to eat, put on the noise cancelling headphones, select a classical music channel and then try and sleep for the rest of the flight. I followed my routine, and after selecting the appropriate music channel, I selected the volume control icon. This resulted in a pop-up window from which I adjusted the volume to something reasonable. I then made the fateful mistake. Rather than exiting the volume adjust window, I simply hit the &#8216;on/off&#8217; button. This of course doesn&#8217;t turn the system off, it merely blanks the display. I then settled in for my nap. Several hours later, I woke up and wondered how far into the flight we were and thus decided to take a look at the real-time route map. Accordingly I turned the display &#8216;on&#8217; and was rewarded with what I expected to see, namely the volume control screen. A photograph is shown below:</p>
<p><a href="http://embeddedgurus.com/stack-overflow/files/2011/06/Boeing-777-Lockup1.jpg"><img class="aligncenter size-large wp-image-727" src="http://embeddedgurus.com/stack-overflow/files/2011/06/Boeing-777-Lockup1-1024x678.jpg" alt="" width="1024" height="678" /></a></p>
<p>When I touched the Back button, nothing happened. Hmmm thought I, has my system died? Answer &#8211; no. I could still adjust the volume, and I could still mute and un-mute the audio. I could also turn the system &#8216;on&#8217; and &#8216;off&#8217;. Clearly the problem was that there was no &#8216;back&#8217; associated with the Back button. Needless to say, United Airlines wasn&#8217;t going to reboot the entire system so that I could experiment some more, plus I was tired. Anyway I resolved to experiment some more on the return flight.</p>
<p>Thus a week later I&#8217;m on a Boeing 777 with the same in flight entertainment system. I brought up the volume control page and did nothing. After about 30 seconds, the pop-up window auto cleared. This was the clue I needed. I thus brought up the volume control page again and immediately turned the unit &#8216;off&#8217; and then a few seconds later &#8216;on&#8217;. When I did this the back button worked correctly. I repeated the exercise a few more times, and it always worked. I then repeated the exercise, but this time I waited longer than the screen timeout period. Voila &#8211; lockup. Clearly this was a case where there was a gaping hole in the state machine that was driving the user interface. At this point I found some interesting thoughts crossing my mind:</p>
<ul>
<li>Idiot. Now you can&#8217;t watch any movies.</li>
<li>I bet the designer didn&#8217;t use a formal state machine tool such as <a href="http://embeddedgurus.com/stack-overflow/2008/05/visualstate/">visualSTATE</a>, or <a href="http://www.state-machine.com/">QP</a></li>
<li>Whenever there are two distinct ways of exiting a state (in this case, user action or the passage of time), life gets complicated</li>
<li>Preserving state across a &#8216;power down&#8217; is always difficult</li>
<li>I hope the guy that wrote the in-flight entertainment  system had nothing to do with the flight control systems on the plane!</li>
</ul>
<p>Anyway if you find yourself on a plane with an in-flight entertainment system in the near future, see if you too can crash the system &#8211; and let us know how you did it.</p>
<p>P.S. I woke up this morning to <a href="http://www.msnbc.msn.com/id/43448373/ns/travel-news/">read </a>that a computer &#8216;glitch&#8217; effectively grounded United Airlines yesterday. See <a href="http://embeddedgurus.com/stack-overflow/2008/02/the-perils-of-overloading/">this </a>for thoughts on United&#8217;s computer system.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/06/how-to-lockup-the-in-flight-entertainment-system-on-a-boeing-777/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Sanity checking data</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/05/sanity-checking-data/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/05/sanity-checking-data/#comments</comments>
		<pubDate>Mon, 30 May 2011 00:51:52 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Firmware Bugs]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=712</guid>
		<description><![CDATA[One of the major differences between embedded systems engineers and the general public is that we tend to notice embedded systems a lot more &#8211; both when they do something very well, and also of course when they do things not so well. The latter happened to me recently when I was pursuing one of [...]]]></description>
			<content:encoded><![CDATA[<p>One of the major differences between embedded systems engineers and the general public is that we tend to notice embedded systems a lot more &#8211; both when they do something very well, and also of course when they do things not so well. The latter happened to me recently when I was pursuing one of my hobbies, namely riding my bicycle. I&#8217;m quite a keen cyclist, in part because I happen to live in part of the world which has some terrific riding country. (To see what I mean, check out the <a href="http://billtan.zenfolio.com/">photos </a>of the ride in question. They were taken by my cycling (and skiing) buddy Bill &#8211; who I think you&#8217;ll agree is a very fine photographer. Click <a href="http://billtan.zenfolio.com/f526726580">here </a>to see more of his published work. If you hunt carefully, you&#8217;ll find some pictures of yours truly).</p>
<p>Anyway at about 25 miles into the ride, I noticed that my Incite bike computer was showing that I had ridden 34 miles. This struck me as unlikely, and so I asked Bill what mileage he had on his computer &#8211; 25 being the answer. I thus cycled through the computer screens, until I came to this one (photo courtesy of Bill Tan).</p>
<p style="text-align: center"><a href="http://embeddedgurus.com/stack-overflow/files/2011/05/132mph1.jpg"><img class="aligncenter size-medium wp-image-716" src="http://embeddedgurus.com/stack-overflow/files/2011/05/132mph1-240x300.jpg" alt="" width="240" height="300" /></a></p>
<p>Apparently the computer thought that I had hit 132.6 mph at some point &#8211; and obviously sustained it for quite a while for me to gain about 9 miles. Now to understand how this could come about, you need to know a little about my bike computer. The computer consists of two parts, the User Interface (shown above) and the pick up. The pick up senses wheel rotation by a magnet passing close to what I assume is a Hall Effect Sensor. Now whereas many bike computers transfer the signal along a cable to the display, mine transmits it using an RF link &#8211; and this I suspect was the root cause of the problem. My guess is that at some point in the ride, I rode into an area of RF interference that the display interpreted as signals from the pickup. The firmware in the bike computer appears to have blithely accepted the RF data as valid and thus produced the ridiculous result shown here.</p>
<p>Now I have often been faced with this kind of problem &#8211; and the solution is not easy. However IMHO Incite really fell down on the job here. If I had been writing the code, I suspect that I&#8217;d have done the following:</p>
<ol>
<li><a href="http://embeddedgurus.com/stack-overflow/2010/10/median-filtering/">Median filter</a> the data to remove random outliers. (Incite may be doing this).</li>
<li>Sanity check the output of the median filter. If the answer is &#8216;impossible&#8217; (like a human pedaling a bicycle at 132.6 mph), then reject the data and let the user know that something is amiss. Incite did neither of these things.</li>
</ol>
<p>Rejecting the data is actually a little harder than it sounds. If you reject data, what do you replace it with? Common choices are:</p>
<ol>
<li>Zero</li>
<li>The most recent valid data</li>
<li>The average of the last N readings.</li>
</ol>
<p>Each of these has its place and is application dependent.</p>
<p>Letting the user know that something is amiss, is usually straight forward &#8211; flashing the erroneous value is the normal solution.</p>
<p>Anyway, the bottom line is that a wise embedded engineer always sanity checks the incoming (and outgoing) data. If you do you are less likely to end up as the subject of a blog posting.</p>
<h2>A personal note</h2>
<p>I apologize for the abysmal rate at which I have been posting. I moved house this spring, which coupled with me being extremely <a href="http://embeddedgurus.com/stack-overflow/2011/02/consulting-as-a-leading-economic-indicator-update-2/">busy</a> has resulted in there simply not being enough hours in the day. When that happens, something has to give. I hope to return to my normal blog posting rate in July.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/05/sanity-checking-data/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>The N_ELEMENTS macro</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/03/the-n_elements-macro/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/03/the-n_elements-macro/#comments</comments>
		<pubDate>Fri, 18 Mar 2011 22:00:37 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[General C issues]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=699</guid>
		<description><![CDATA[Many years ago I came across a simple macro that has proven to be quite useful. Its usual definition looks something like this: #define N_ELEMENTS(X)           (sizeof(X)/sizeof(*(X))) Its nominal use is to determine the number of elements in an incomplete array declaration. For example void foo(void) { uint8_t bar[] = {0, 1, 2, 3, 4}; [...]]]></description>
			<content:encoded><![CDATA[<p>Many years ago I came across a simple macro that has proven to be quite useful. Its usual definition looks something like this:</p>
<pre>#define N_ELEMENTS(X)           (sizeof(X)/sizeof(*(X)))
</pre>
<p>Its nominal use is to determine the number of elements in an incomplete array declaration. For example</p>
<pre>void foo(void)
{
 uint8_t bar[] = {0, 1, 2, 3, 4};
 uint8_t    i;

 /* Transmit each byte in bar[] */
 for (i = 0; i &lt; N_ELEMENTS(bar); ++i)
 {
  txc(bar[i]);
 }
}
</pre>
<p>Clearly this is quite useful. However, once you have this macro in your arsenal you will eventually run into a conundrum. To illustrate what I mean consider the following code:</p>
<pre>#define BUF_SIZE    (5)
void foo(void)
{
 uint8_t bar[BUF_SIZE] = {0, 1, 2, 3, 4};
 uint8_t    i;

 /* Transmit each byte in bar[] */
 for (i = 0; i &lt; BUF_SIZE; ++i)
 {
  txc(bar[i]);
 }
}
</pre>
<p>This uses the classic approach of  defining a manifest constant  (BUF_SIZE) and then using it to define the array size and also as the loop limit. The conundrum is this: is one better off using N_ELEMENTS in this case as well. In other words, is the following better code?</p>
<pre>#define BUF_SIZE    (5)
void foo(void)
{
 uint8_t bar[BUF_SIZE] = {0, 1, 2, 3, 4};
 uint8_t    i;

 /* Transmit each byte in bar[] */
 for (i = 0; i &lt; N_ELEMENTS(bar); ++i)
 {
  txc(bar[i]);
 }
}
</pre>
<p>This code is guaranteed to operate on every element of the array bar[] regardless of what is done to the array declaration. For example:</p>
<pre>#define BUF_SIZE    (5)
void foo(void)
{
 uint8_t bar[BUF_SIZE + 1] = {0, 1, 2, 3, 4, 5};
 uint8_t    i;

 /* Transmit each byte in bar[] */
 for (i = 0; i &lt; N_ELEMENTS(bar); ++i)
 {
  txc(bar[i]);
 }
}
</pre>
<p>In this case I have changed the array declaration. The code that uses N_ELEMENTS would still work while the code that used BUF_SIZE would have failed. So from this perspective the N_ELEMENTS code is more robust. However I don&#8217;t think the N_ELEMENTS based code is as easy to read. As a result I have oscillated back and fore over the years as to which approach is better. My current view is that the N_ELEMENTS approach is indeed the better way. I&#8217;d be interested in your opinion.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/03/the-n_elements-macro/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>An embedded systems hardware test &#8211; a collaborative effort</title>
		<link>http://embeddedgurus.com/stack-overflow/2011/02/an-embedded-systems-hardware-test-a-collaborative-effort/</link>
		<comments>http://embeddedgurus.com/stack-overflow/2011/02/an-embedded-systems-hardware-test-a-collaborative-effort/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 23:14:39 +0000</pubDate>
		<dc:creator>Nigel Jones</dc:creator>
				<category><![CDATA[Hardware]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/stack-overflow/?p=686</guid>
		<description><![CDATA[Regular readers will probably be aware that back in 2000 I wrote an article for Embedded Systems Programming magazine entitled A ‘C’ Test: The 0×10 Best Questions for Would-be Embedded Programmers. In the intervening years I have often thought that it would be entertaining / useful to come up with a similar test—except this time [...]]]></description>
			<content:encoded><![CDATA[<p>Regular readers will probably be aware that back in 2000 I wrote an article for Embedded Systems Programming magazine entitled <a href="http://embeddedgurus.com/stack-overflow/2009/09/a-c-test-the-0x10-best-questions-for-would-be-embedded-programmers-reprised/">A ‘C’ Test: The 0×10 Best Questions for Would-be Embedded Programmers</a>. In the intervening years I have often thought that it would be entertaining / useful to come up with a similar test—except this time I would be testing someone&#8217;s hardware knowledge. As a result over the years I have collected together a number of fun questions, which I intend to use in the forth-coming article. However it occurred to me that I have a lot of very smart readers and that collectively we could put together a far better test than I could do so on my own. Thus I&#8217;m looking for your hardware questions! Before you flood me with your suggestions here are the ground rules:</p>
<ol>
<li><a href="http://www.rmbconsulting.us/embedded-systems-design">Embedded systems design</a>, not hardware design<br />
The test is intended to test the hardware knowledge of persons <em>writing embedded code</em>. It is NOT a test for persons that will be <em>designing</em> hardware. Thus questions about the minutiae of hardware filter design are not what I&#8217;m looking for.</li>
<li>Traps<br />
The best questions will be examples from your past where someone got into trouble because they didn&#8217;t understand something about the hardware that you thought they should have.</li>
<li>Why<br />
As well as posing the question (and giving the answer!), please explain why you think it&#8217;s important that someone should know what you are asking.</li>
<li>Oscilloscope and logic analyzer<br />
I expect that the questions will cover circuits, processor architectures and tools. While I&#8217;m interested in all three, I&#8217;m particularly interested in elegant questions that will allow the questioner to determine if the candidate knows how to use an oscilloscope or logic analyzer.</li>
<li>Original<br />
Please don&#8217;t send me any copyrighted or plagiarized material. Links are of course fine. (I mention this because not only is it legally and morally wrong &#8211; but I&#8217;m also tired of people ripping off my work and claiming it as their own).</li>
<li>Attribution<br />
If I choose to use your suggestion, then tell me how you&#8217;d like it attributed. Full name + email address through anonymous are all fine.</li>
<li>Early bird&#8230;<br />
If I get multiple similar suggestions, then the first one received gets the credit.</li>
<li>Fame<br />
By sending me something you are agreeing to let me publish it. Other than attribution (and the accompanying fame <img src='http://embeddedgurus.com/stack-overflow/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ), no other compensation will be given.</li>
</ol>
<p>Anyway, if you&#8217;d like to participate then <a href="mailto:najones@rmbconsulting.us?subject=HW%20Test">contact me</a></p>
<p>Thanks! I expect that I will publish the article in a few weeks.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/stack-overflow/2011/02/an-embedded-systems-hardware-test-a-collaborative-effort/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>

