<?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>State Space</title>
	<atom:link href="http://embeddedgurus.com/state-space/feed/" rel="self" type="application/rss+xml" />
	<link>http://embeddedgurus.com/state-space</link>
	<description>A Blog by Miro Samek</description>
	<lastBuildDate>Fri, 26 Feb 2010 05:07:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Free store is not free lunch</title>
		<link>http://embeddedgurus.com/state-space/2010/01/free-store-is-not-free-lunch/</link>
		<comments>http://embeddedgurus.com/state-space/2010/01/free-store-is-not-free-lunch/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 19:27:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Coding Standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2010/01/29/free-store-is-not-free-lunch/</guid>
		<description><![CDATA[In my previous post &#8220;A Heap of Problems&#8221; I have compiled a list of problems the free store (heap) can cause in real-time embedded (RTE) systems. This was quite a litany, although I didn’t even touch the more subtle problems yet (for example, the C++ exception handling mechanism can cause memory leaks when a thrown [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post &#8220;<a href="http://www.embeddedgurus.net/state-space/2010/01/heap-of-problems.html">A Heap of Problems</a>&#8221; I have compiled a list of problems the free store (heap) can cause in real-time embedded (RTE) systems. This was quite a litany, although I didn’t even touch the more subtle problems yet (for example, the C++ exception handling mechanism can cause memory leaks when a thrown exception bypasses memory de-allocation).</p>
<p>But even though the free store is definitely not a free lunch, getting by without the heap is certainly easier said than done. In C, you will have to rethink implementations that use lists, trees, and other dynamic data structures. You’ll also have to severely limit your choice of the third-party libraries and legacy code you want to reuse (especially if you borrow code designed for the desktop). In C++, the implications are even more serious because the object-oriented nature of C++ applications results in much more intensive dynamic-memory use than in applications using procedural techniques. For example, most standard C++ libraries (e.g., STL, Boost, etc.) requrie the heap. Without it, C++ simply does not feel like the same language.</p>
<p>Here are a few common sense guidelines for dealing with the heap:</p>
<p>1. For smaller systems, such as microcontrollers with only on-chip RAM, you probably don&#8217;t want to open the heap can of worms at all. The problems and waste that goes with the heap aren&#8217;t simply worth the trouble.</p>
<p>For systems with sufficient RAM, such as processors with megabytes of external DRAM, trading some of this cheap RAM for convenience in programming might be a reasonable deal. In the following discussion I assume that the system is big enough to run under a preemptive RTOS.</p>
<p>2. The simplest option is to limit the use of the heap to just one task. In this case, heap is not being shared concurrently and does not need any mutual-exclusion protection mechanism. To limit the non-determinism of the heap, I would recommend assigning low priority to the task that uses the heap. The priority should be lower than any real-time task.</p>
<p>3. At the expense of introducing a mutual protection to *all* heap operations (e.g., a mutex), you can allow more than one task to use the heap. However, I would still strongly recommend against using the heap in any tasks with real-time deadlines. All tasks that use the heap should run at a lower priority than any of the real-time tasks.</p>
<p>4. In any case, heap should never be used inside the interrupt service routines (ISRs).</p>
<p>In summary, using the heap in real-time embedded (RTE) systems always requires extra thought and discipline. You should always make sure that the heap is correctly integrated with your runtime environment.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2010/01/free-store-is-not-free-lunch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Heap of Problems</title>
		<link>http://embeddedgurus.com/state-space/2010/01/heap-of-problems/</link>
		<comments>http://embeddedgurus.com/state-space/2010/01/heap-of-problems/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 22:24:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2010/01/24/a-heap-of-problems/</guid>
		<description><![CDATA[Some design problems never seem to go away. You think that anybody who has been in the embedded software development business for a while must have learned to be wary of malloc() and free() (or their C++ counterparts new and delete). Then you find that many developers actually don&#8217;t know why embedded real-time systems are [...]]]></description>
			<content:encoded><![CDATA[<p>Some design problems never seem to go away. You think that anybody who has been in the embedded software development business for a while must have learned to be wary of malloc() and free() (or their C++ counterparts new and delete). Then you find that many developers actually don&#8217;t know why embedded real-time systems are so particularly intolerant of heap problems.</p>
<p>For example, recently an Embedded.com reader attacked my comment to the article &#8220;<a href="http://www.embedded.com/design/opensource/216800007">Back to the Basics &#8211; Practical Embedded Coding Tips: Part 1 Reentrancy, atomic variables and recursion</a>&#8220;, in which I advised against using the heap. Here is this reader&#8217;s argumentation:</p>
<blockquote><p>I have no idea why did you bring up the pledge not to use the heap, on modern 32-bit MCUs (ARMs etc) there is no reason &#8211; and no justification &#8211; to avoid using the heap. The only reason not to use the heap is to avoid memory fragmentation, but good heap implementation and careful memory allocation planning will overcome that.</p></blockquote>
<p>As I cannot disagree more with the statements above, I decided that it&#8217;s perhaps the time to re-post my &#8220;heap of problems&#8221; list, which goes as follows:</p>
<ul>
<li>Dynamically allocating and freeing memory can fragment the heap over time to the point that the program crashes because of an inability to allocate more RAM. The total remaining heap storage might be more than adequate, but no single piece satisfies a specific malloc() request.</li>
<li>Heap-based memory management is wasteful. All heap management algorithms must maintain some form of header information for each block allocated. At the very least, this information includes the size of the block. For example, if the header causes a four-byte overhead, then a four-byte allocation requires at least eight bytes, so only 50 percent of the allocated memory is usable to the application. Because of these overheads and the aforementioned fragmentation, determining the minimum size of the heap is difficult. Even if you were to know the worst-case mix of objects simultaneously allocated on the heap (which you typically don&#8217;t), the required heap storage is much more than a simple sum of the object sizes. As a result, the only practical way to make the heap more reliable is to massively oversize it.</li>
<li>Both malloc() and free() can be (and often are) nondeterministic, meaning that they potentially can take a long (hard to quantify) time to execute, which conflicts squarely with real-time constraints. Although many RTOSs have heap management algorithms with bounded, or even deterministic performance, they don&#8217;t necessarily handle multiple small allocations efficiently.</li>
</ul>
<p>Unfortunately, the list of heap problems doesn&#8217;t stop there. A new class of problems appears when you use heap in a multithreaded environment. The heap becomes a shared resource and consequently causes all the headaches associated with resource sharing, so the list goes on:</p>
<ul>
<li>Both malloc() and free() can be (and often are) non-reentrant; that is, they cannot be safely called simultaneously from multiple threads of execution.</li>
<li>The reentrancy problem can be remedied by protecting malloc(), free(), realloc(), and so on internally with a mutex, which lets only one thread at a time access the shared heap. However, this scheme could cause excessive blocking of threads (especially if memory management is nondeterministic) and can significantly reduce parallelism. Mutexes can also be subject to priority inversion. Naturally, the heap management functions protected by a mutex are not available to interrupt service routines (ISRs) because ISRs cannot block.</li>
</ul>
<p>Finally, all the problems listed previously come on top of the usual pitfalls associated with dynamic memory allocation. For completeness, I&#8217;ll mention them here as well.</p>
<ul>
<li>If you destroy all pointers to an object and fail to free it or you simply leave objects lying about well past their useful lifetimes, you create a memory leak. If you leak enough memory, your storage allocation eventually fails.</li>
<li>Conversely, if you free a heap object but the rest of the program still believes that pointers to the object remain valid, you have created dangling pointers. If you dereference such a dangling pointer to access the recycled object (which by that time might be already allocated to somebody else), your application can crash.</li>
<li>Most of the heap-related problems are notoriously difficult to test. For example, a brief bout of testing often fails to uncover a storage leak that kills a program after a few hours, or weeks, of operation. Similarly, exceeding a real-time deadline because of nondeterminism can show up only when the heap reaches a certain fragmentation pattern. These types of problems are extremely difficult to reproduce.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2010/01/heap-of-problems/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A nail for a fuse</title>
		<link>http://embeddedgurus.com/state-space/2009/11/a-nail-for-a-fuse/</link>
		<comments>http://embeddedgurus.com/state-space/2009/11/a-nail-for-a-fuse/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 17:13:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/11/27/a-nail-for-a-fuse/</guid>
		<description><![CDATA[If I were to search my soul, I&#8217;d have to admit that the use of assertions has helped me more than any other single technique, even more than my favorite state machines. But, the use of assertions, simple as they are, is surrounded by so many misconceptions and misunderstandings that it&#8217;s difficult to know where [...]]]></description>
			<content:encoded><![CDATA[<p>If I were to search my soul, I&#8217;d have to admit that the use of assertions has helped me more than any other single technique, even more than my favorite state machines. But, the use of assertions, simple as they are, is surrounded by so many misconceptions and misunderstandings that it&#8217;s difficult to know where to start. The discussion around the recent Jack Genssle&#8217;s article &#8220;<a href="http://www.embedded.com/columns/breakpoint/221800158">The Use of Assertions</a>&#8221; shows many of the misunderstandings.</p>
<p>I suppose that the main difficulties in understanding assertions lay in the fact that while the implementation of assertions is trivial, the effective use of assertions requires a paradigm shift in the view of software construction and the nature of software errors in particular.</p>
<p>Perhaps the most important point to understand about assertions is that they neither handle nor prevent errors, in the same way as fuses in electrical circuits don&#8217;t prevent accidents or abuse. In fact, a fuse is an intentionally introduced <span style="font-weight:bold">weak</span> spot in the circuit that is designed to fail sooner than anything else, so actually the whole circuit with a fuse is less robust than without it.</p>
<p>I believe that the analogy between assertions and fuses (which, by the way has been originally proposed by Niall Murphy in a private conversation at one of the Embedded Systems Conferences) is accurate and valuable, because it helps in making the paradigm shift in understanding many aspects of using assertions. Here I&#8217;d only like to elaborate just two aspects.    </p>
<p>First, the analogy to fuses correctly suggests that assertions work best in the &#8220;weakest&#8221; spots. Such &#8220;weak spots&#8221; are often found at the interface between components (e.g., preconditions in a function) but there are many others. The best assertions are those that protect the most of the system. In other words, the best assertions catch errors that would have the most impact on the rest of the system. </p>
<p>The second important implication of the fuse analogy is the issue of disabling assertions in the production code. As the comments to the aforementioned <a href="http://www.embedded.com/columns/breakpoint/221800158">article</a> suggest, most engineers tend to disable assertions before shipping the code, especially in the safety critical products. I believe that this is exactly <span style="font-weight:bold">backwards</span>.</p>
<p>I understand that the standard &#8220;assert.h&#8221; header file is designed to use assertions only in a debug build, so the macro assert() compiles to nothing when the symbol NDEBUG is defined. I strongly suggest rethinking this philosophy, because disabling assertions in the release configuration is like using nails, paper clips, or coins for fuses. Just imagine finding a nail in place of a fuse in a hospital&#8217;s operating room or in a dashboard of an airliner? What would you think of this sort of &#8220;repairs&#8221;? </p>
<p>Yet, by disabling assertions in our code we do exactly this.  </p>
<p>I believe it is very important to understand that assertions have a very important role to play, especially in the filed and especially in the mission-critical systems, because they add additional <span style="font-weight:bold">safety</span> layer in the software. Perhaps the biggest fallacy of our profession is the naïve optimism that our software will not fail. In a nutshell we somehow believe that when we stop checking for errors, they will stop occurring. After all&#8211;we don&#8217;t see them anymore. But this is not how computer systems work. An error, no matter how small, can cause catastrophic failure. With software, there are no &#8220;small&#8221; errors. Our software is either in complete control over the machine or it isn&#8217;t. Assertions help us know when we lose control. </p>
<p>So what do I suggest we do when the assertion fires in the filed? The proper course of action requires a lot of thinking and sometimes a lot of work. In safety-critical systems software failure should be part of the fault-tree analysis. Sometimes, reaching a fail-safe state requires some redundancy in the hardware. In any case, the assertion failures should be extensively tested.</p>
<p>But this is really the best we can do.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/11/a-nail-for-a-fuse/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cute Creator</title>
		<link>http://embeddedgurus.com/state-space/2009/04/cute-creator/</link>
		<comments>http://embeddedgurus.com/state-space/2009/04/cute-creator/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 17:26:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/04/28/cute-creator/</guid>
		<description><![CDATA[For a long time I&#8217;ve been looking for a good cross platform development environment that would allow fast exploration and navigation of C/C++ source code, not just editing of individual files. For a while I though that Eclipse will fit the bill, but as I wrote previously, the CDT (C/C++ Development Tooling) was really disappointing [...]]]></description>
			<content:encoded><![CDATA[<p>For a long time I&#8217;ve been looking for a good cross platform development environment that would allow fast exploration and navigation of C/C++ source code, not just editing of individual files. For a while I though that Eclipse will fit the bill, but as I wrote <a href="http://www.embeddedgurus.net/state-space/2007/09/emperors-new-clothes.html">previously</a>, the CDT (C/C++ Development Tooling) was really disappointing for me.</p>
<p>In this post I&#8217;d like to tell you about my recent big hope for a truly productive IDE, which is the <a href="http://www.qtsoftware.com/products">Qt Creator</a> from <a href="">qtsoftware.com</a>. Qt Creator is based on the popular cross-platform Qt framework and runs natively on Windows, Linux, BSD, Mac OS X, and some embedded platforms. No Java (as in the case of Eclipse) means speed and snappy interface. Qt Software (previously Trolltech, acquired in 2008 by Nokia) offers free downloads of Qt Creator for all major platforms. </p>
<p>Qt Creator is primarily targeted as the IDE for Qt-related development. However, the recently released version 1.1 (April 23, 2009) supports external projects, so adding your embedded or any other projects unrelated to Qt is easy. </p>
<p>For example, I&#8217;ve created an embedded project for a &#8220;game&#8221; shown in the screen shot below (click on the image to see it full-size):</p>
<p><a href="http://embeddedgurus.net/state-space/uploaded_images/QtCreator-786389.JPG"><img style="margin:0 10px 10px 0;cursor:pointer;cursor:hand;width: 320px;height: 197px" src="http://embeddedgurus.net/state-space/uploaded_images/QtCreator-786384.JPG" border="0" alt="" /></a></p>
<p>The editing surface maximizes the screen real-estate for file viewing and supports sophisticated splitting, so that my favorite side-by-side code editing is easy.</p>
<p>As shown in the left pane, you can add to your project as many files in different directories as you like. Given this information, Qt Creator builds an internal database of all symbols in your code to allow you exploring and navigating through your source code quickly. For example, you can jump from symbol usage to its definition by pressing F2 (press Alt-back-arrow to jump back to the previous context).</p>
<p>Everything in the editor is designed to enhance quick navigation. For example, every editor pane has a drop-down list of functions and other elements in the file. The editor also supports selective viewing with collapsible/expandable code sections, so you can fit more information on the screen. To quickly view the collapsed section you can simply hover your mouse cursor over it.</p>
<p>I immensely like the support for project-wide searching (as well as search-and-replace), which is available at the bottom of the screen. This feature alone is worth installing the tool. </p>
<p>Even though it is so new, Qt Creator is already very interesting, free, cross-platform IDE with features comparable to Visual Studio 2008 and other best-in-class tools. Qt Software seems very committed to enhancing Qt Creator and I hope that Qt Creator will soon catch up with Eclipse as third-party plug-ins will be developed. One feature that I will be looking forward to is side-by-side code differencing. But already, it is a powerful, free, cross-platform tool that you should try.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/04/cute-creator/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Insects of the computer world</title>
		<link>http://embeddedgurus.com/state-space/2009/03/insects-of-the-computer-world/</link>
		<comments>http://embeddedgurus.com/state-space/2009/03/insects-of-the-computer-world/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 21:15:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/03/09/insects-of-the-computer-world/</guid>
		<description><![CDATA[The recent Jack Ganssle&#8217;s &#8220;Breakpoints&#8221; blog on Embedded.com makes an excellent point that the same forces (the Moore&#8217;s law), which drive down the prices of high-end processors open even more market opportunities at the low-end of the price spectrum. I also agree that the most deciding factor for the price of a single-chip microcontroller (MCU) [...]]]></description>
			<content:encoded><![CDATA[<p>The recent Jack Ganssle&#8217;s <a href="http://www.embedded.com/columns/breakpoint/215801305">&#8220;Breakpoints&#8221; blog</a> on <a href="http://www.embedded.com">Embedded.com</a> makes an excellent point that the same forces (the Moore&#8217;s law), which drive down the prices of high-end processors open even more market opportunities at the low-end of the price spectrum. I also agree that the most deciding factor for the price of a single-chip microcontroller (MCU) is the efficiency of its memory use, in other words, the code density. This becomes obvious when one looks at the silicon die of any MCU, which is completely dominated by the ROM and RAM blocks, the CPU being almost insignificant somewhere in the corner.</p>
<p>But, I would disagree with Jack&#8217;s statement that &#8220;tiny (8-bit) processors make more efficient use of memory&#8221;. From my experience with several single-chip MCUs I draw a different conclusion: the CPU size (8-, 16-, 32-bits) almost doesn&#8217;t matter for the code density. The deciding factor is how old a design is, whereas the newer instruction set architectures (ISAs) generally far outperform the older ISAs.</p>
<p>To support the point, I present below a table that shows the code size of a tiny state machine framework written in C (called QP-nano), which has been compiled for a dozen or so very different single-chip MCUs. The code consists of a small hierarchical state machine processor (called QEP-nano), and a tiny framework (called QF-nano). The QEP-nano consists mostly of a conditional logic to execute hierarchical state machines. QF-nano contains an event queue, a timer module, and a simple event loop. I believe that this code is quite representative to typical projects that run on these small MCUs.</p>
<pre>CPU type            C Compiler     QEP-nano  QF-nano                                    (bytes)  (bytes)---------------+-------------------+----------+---------PIC18               MPLAB-C18         3,214     2,072                (student edition)          ---------------+-------------------+----------+---------8051 (SiLabs)        IAR EW8051         952       603---------------+-------------------+----------+---------PSoC (M8C)        ImageCraft M8C      2,765     2,425---------------+-------------------+----------+---------68HC08          CodeWarrior HC(S)08     957       660---------------+-------------------+----------+---------AVR (ATmega)         IAR EWAVR          541       650---------------+-------------------+----------+---------AVR (ATmega)        WinAVR(GNU)         998       810---------------+-------------------+----------+---------MSP430               IAR EW430          552       460---------------+-------------------+----------+---------M16C                 HEW4/NC30          984       969---------------+-------------------+----------+---------TMS320C28x            C2000         369 words  331 words (Piccolo)                          738 bytes  662 bytes---------------+-------------------+----------+---------ARM7(ARM/THUMB)       IAR EWARM     588(THUMB) 1,112(ARM)---------------+-------------------+----------+---------ARM Cortex-M3         IAR EWARM         524       504  (THUMB2)                                    ---------------+-------------------+----------+---------
</pre>
<p>Interestingly, the winner is MSP430, which is a 16-bit architecture.<br />It seems that the 16-bit ISA hits somehow the &#8220;sweet spot&#8221; for the best code density, perhaps because the addresses are also 16-bit wide and are handled in a single instruction. In contrast, 8-bitters need multiple instructions to handle 16-bit addresses.</p>
<p>I would also point out the excellent code density (and C-friendliness) of the new ARM Cortex-M3, which is a modern 32-bit ISA, and still far outperforms all 8-bitters, including the good ol&#8217;8051.</p>
<p>On the other hand, the venerable PIC architecture is by far the worst (or, C un-friendly). That&#8217;s interesting, because this is the 8-bit market leader. I honestly don&#8217;t understand how Microchip makes money when their chips require the most silicon for given functionality. Clearly some other forces than just technical merits must be at work here.</p>
<p>In conclusion, I understand that my data is highly subjective and different code sets (and different compilers) could perhaps produce different results. However, I believe that the general trend is true and this is an <strong>important lesson</strong> for engineers selecting MCUs.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/03/insects-of-the-computer-world/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>RTOS Alternatives</title>
		<link>http://embeddedgurus.com/state-space/2009/01/rtos-alternatives/</link>
		<comments>http://embeddedgurus.com/state-space/2009/01/rtos-alternatives/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 23:15:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[RTOS Multithreading]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/01/07/rtos-alternatives/</guid>
		<description><![CDATA[As hundreds of commercial and other RTOS offerings can attest, the greatest demand for third-party software in the embedded systems community is for the RTOS. But this is perhaps because most embedded developers believe that traditional preemptive RTOS on one end of the complexity spectrum and the customary superloop (main+ISRs) on the other are the [...]]]></description>
			<content:encoded><![CDATA[<p>As hundreds of commercial and other RTOS offerings can attest, the greatest demand for third-party software in the embedded systems community is for the RTOS. But this is perhaps because most embedded developers believe that traditional preemptive RTOS on one end of the complexity spectrum and the customary superloop (main+ISRs) on the other are the only choices for the embedded software architecture.</p>
<p>However, a little less know alternative is *event-driven* software structure based on an event-driven framework and encapsulated state machines (called active objects in the UML). This active object-based architecture is not new, and in fact, has been in quite widespread use for at least two decades. Virtually all commercially successful design automation tools on the market today (Telelogic Rhapsody, Rose Real-Time, IAR visualSTATE, Mathworks StateFlow, and many others) are based on hierarchical state machines and incorporate internally a variant of an event-driven framework. For example, Rhapsody generates code either for the Object eXecution Framework (OXF) or the Interrupt-Driven Framework (IDF). OXF requires a traditional RTOS for preemptive scheduling, while IDF was created specifically to avoid the need for an RTOS.</p>
<p>Most developers are accustomed to the basic sequential control, in which a program (a task in an RTOS) waits for events in various places in its execution path by either actively polling for events or passively blocking on a semaphore or other such RTOS mechanism. Though this approach is functional in many situations, it doesn&#8217;t work very well when the system must timely react to multiple events whose arrival times and order one cannot predict. The fundamental problem is that while a sequential task is waiting on one kind of event, it is not doing any other work and is not *responsive* to other events.</p>
<p>Event-driven programming requires a distinctly different way of thinking than conventional sequential programs, such as &#8220;superloops&#8221; or tasks in a traditional RTOS. Event-driven systems are structured according to the Hollywood principle, which means &#8220;Don’t call us, we’ll call you&#8221;. So, an event-driven program is not in control while waiting for an event; in fact, it’s not even active. Only once the event arrives, the program is called to process the event and then it quickly relinquishes the control again. This arrangement allows an event-driven system to wait for many events in parallel, so the system remains *responsive* to all events it needs to handle.</p>
<p>This scheme has three important consequences. First, it implies that an event-driven system is naturally divided into the application, which actually handles the events, and the supervisory event-driven infrastructure (framework), which waits for events and dispatches them to the application. Second, the control resides in the event-driven infrastructure, so from the application standpoint, the control is inverted compared to a traditional sequential program. And third, the event-driven application must return control after handling each event, so the execution context cannot be preserved in the stack-based variables and the program counter as it is in a sequential task. Instead, the event-driven application becomes a *state machine*, or actually a set of collaborating state machines that preserve the context from one event to the next in the static variables.</p>
<p>Traditionally, event-driven programming was done with a specific design-automation tool, such as Rose-RT or Rhapsody (now both acquired by IBM). But recently, lightweight, open source event-driven frameworks became available. The lightweight frameworks allow direct coding of hierarchical state machines (UML statecharts) in C or C++ and then combining multiple concurrent state machines into systems, all without big tools (e.g., see <a href="http://www.state-machine.com/">www.state-machine.com</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/01/rtos-alternatives/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Make the most of side-by-side code differencing</title>
		<link>http://embeddedgurus.com/state-space/2008/06/make-the-most-of-side-by-side-code-differencing/</link>
		<comments>http://embeddedgurus.com/state-space/2008/06/make-the-most-of-side-by-side-code-differencing/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 15:36:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2008/06/11/make-the-most-of-side-by-side-code-differencing/</guid>
		<description><![CDATA[I&#8217;m constantly amazed how many developers shoot themselves in the foot by defeating the benefits of side-by-side source code differencing, which is perhaps the most routinely used technique in daily code development and maintenance with any VCS (Version Control System). In this post, I&#8217;d like to share a few tips for making the most of [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m constantly amazed how many developers shoot themselves in the foot by defeating the benefits of side-by-side source code differencing, which is perhaps the most routinely used technique in daily code development and maintenance with any VCS (Version Control System). In this post, I&#8217;d like to share a few tips for making the most of side-by-side differencing, which in my view should be adopted into every coding standard.</p>
<p>First of all, to benefit from side-by-side diff you need to limit the width of your lines so that you don&#8217;t need to scroll horizontally to see all the code. Countless bugs slip into a VCS, because they are hidden off screen during the final merge and people are simply tired of constantly scrolling back and forth. (All GUI usability studies agree that horizontal scrolling of text is always a bad idea.)</p>
<p>Granted, the modern high-resolution wide screens offer a lot of horizontal pixels, but ultimately you&#8217;ll always run out of the screen real estate if you allow lines to go on for miles. The column width must obviously allow comfortable viewing two code listings side-by-side, but you should also budget some horizontal space for the directory-tree view, vertical sliders, line numbers, and line margins, as shown in the screen shot below. I&#8217;ve been using the column width limit of no more than 78 characters. Your limit could perhaps be higher, but you <b>must</b> set such a limit and then enforce it without exceptions.</p>
<p><img src="http://www.state-machine.com/resources/side_by_side_diff.jpg" alt="side-by-side diff" vspace="10">  </p>
<p>I can see two main reasons why people write very long lines. The first is long strings in the code. But C or C++ allow writing wide string constants in the following way:</p>
<pre>char const s1[] =    "This long string is acc\eptable to all C compilers.";char const s2[] =    "This long string is permissible "    "in ANSI C.";</pre>
<p>&nbsp; </p>
<p>In other words, you can either use a backslash &#8216;\&#8217; to terminate a string and continue in the next line, or you can terminate a string normally with a double quote &#8216;&#8221;&#8216;, and an ANSI C compiler will concatenate such adjacent strings into a single zero-terminated string.</p>
<p>The second reason for long lines are preprocessor macros. Here again, you can use the backslash &#8216;\&#8217; to break up a longer macro into lines. For example:</p>
<pre>#define err(flag, msg) if (flag) \   printf(msg)</pre>
<p>&nbsp; </p>
<p>is the same as</p>
<pre>#define err(flag, msg) if (flag) printf(msg)</pre>
<p>&nbsp; </p>
<p>The use of a backslash for breaking up longer lines brings up the issue of the end-of-line convention and the use of white space in your source code in general.</p>
<p>Let me start with the end-of-line convention. The issue here is that the backslash continuation won&#8217;t work unless the &#8216;\&#8217; character is <b>immediately</b> followed by the end-of-line. Unfortunately, at lest two incompatible end-of-line conventions are in widespread use. The DOS/Windows end-of-line convention consists of the pair of characters CR-LF (0&#215;0D, 0&#215;0A in hex) to terminate lines. In contrast the UNIX&trade; end-of-line convention uses only one LF character (0&#215;0A). As it turns out, Unix-like machines (e.g. Linux) are confused by the DOS end-of-line convention and will <b>not</b> correctly recognize the backslash-continuation, which looks like &#8216;\&#8217;-CR-LF (0&#215;5C, 0&#215;0D, 0&#215;0A), instead of &#8216;\&#8217;-LF (0&#215;5C, 0&#215;0A).</p>
<p>My recommendation is to use consistently only the UNIX end-of-line convention, even on Windows machines. In my experience all Windows-based compilers have no problems with the UNIX convention, including the ancient tools from the DOS-era. As I mentioned, the converse is not true.   </p>
<p>And finally, let me talk about the use of white space (spaces, tabs, end-of-line) in general. Obviously, to benefit from source code differencing you&#8217;d like to see only the relevant differences and differences in white space only are typically not relevant. Many code-differencing tools offer an option to ignore white space, but I would not recommend relying on it. Are files with different sizes really identical? And also, as I said before, extra spaces or tabs after the backslash, but before the end-of-line, are not allowed.</p>
<p>As far as tabs are concerned, I&#8217;d strongly recommend <b>not</b> to use them at all. Tabs are rendered differently by different editors and printers and bring only insignificant memory savings. Preferably, you should disable tabs at the editor level. At the very least, you should replace all tabs by spaces (&#8220;untabify&#8221;) before saving the file. As for spaces, I recommend removing any trailing spaces that precede the end-of-line character (LF). </p>
<p>Obviously, you can and should automate the source code cleanup. I use the QCLEAN utility (available <a href="http://www.state-machine.com/resources/qclean.zip">here</a> under the GPL license) for cleaning up the code from tabs, trailing blanks, and to enforce the Unix end-of-line convention. The simple console QCLEAN Windows executable scanns recursively all source files (.C, .CPP, .H, .ASM, .S, Makefile, etc.) down from the directory in which it is invoked. The following two listings show a code snippet before and after cleanup with the QCLEAN utility (spaces are shown as dots, tabs as \t, DOS end-of-lines as \r\n, UNIX end-of-lines as \n).</p>
<p>before cleanup:
<pre>.\t...\r\nclass.Foo.:.public.Bar.{...\npublic:.\r\n\tFoo(int8_t.x,.int16_t.y,.int32_t z).//..ctor..\n....:.Bar(x,.y),.m_z(z)....\n....{}.............\n.\t..\n....virtual.~Foo();\t... //.xtor........\r\n....virtual int32_t doSomething(int8_t.x);.//.method..\r\n</pre>
<p>&nbsp; </p>
<p>after cleanup with QCLEAN:
<pre>\nclass.Foo.:.public.Bar.{\npublic:\n....Foo(int8_t.x,.int16_t.y,.int32_t z).//..ctor\n....:.Bar(x,.y),.m_z(z)\n....{}\n\n....virtual.~Foo();... //.xtor\n....virtual int32_t doSomething(int8_t.x);.//.method\n</pre>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2008/06/make-the-most-of-side-by-side-code-differencing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Object-based programming in C</title>
		<link>http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/</link>
		<comments>http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/#comments</comments>
		<pubDate>Mon, 21 Jan 2008 00:11:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2008/01/21/object-based-programming-in-c/</guid>
		<description><![CDATA[Embedded developers abandon C++ in droves. According to the 2007 survey published in the ESD magazine, the C++ use declined by one-third compared to year before, which was offset by an equal rise in popularity of C&#8212;the only viable alternative in embedded.
Even though the last year was most dramatic, the trend has been actually continuing [...]]]></description>
			<content:encoded><![CDATA[<p>Embedded developers abandon C++ in droves. According to the <a href="http://www.embedded.com/design/opensource/201803499">2007 survey</a> published in the ESD magazine, the C++ use declined by one-third compared to year before, which was offset by an equal rise in popularity of C&mdash;the only viable alternative in embedded.</p>
<p>Even though the last year was most dramatic, the trend has been actually continuing for a number of years. This couldn&#8217;t go unnoticed by UML tool vendors, who desparately have been trying to cater to C programmers. For example, you can check out the DDJ article &#8220;<a href="http://www.ddj.com/web-development/184401948">UML for C Programmers</a>&#8221; (which seems to be pretty exact re-print of the Embedded Systems Conference paper &#8220;<a href="https://www.cmpevents.com/ESCw08/a.asp?option=C&amp;V=11&amp;SessID=6716">UML for C-Based Embedded Systems</a>&#8220;). To my surprise, nether this article, nor the ESC class mention any well-known techniques of mapping objects and classes to C. I’m sure that it is not what UML vendors like. After all, UML is crippled without objects. (The only real meat remaining are state machines.) But I suppose that the marketing departments of I-Logix/Telelogic have done their homework. Apparently <b>embedded developers</b> don’t like to hear about objects anymore.</p>
<p>I find this really disturbing. It seems that &#8220;object&#8221; and (pardon my language) &#8220;class&#8221; are becoming dirty words in the embedded circles. C++ decline is one thing. But abandoning objects is a different story. Aren’t we throwing out the baby with the bath water?</p>
<p>One would assume that the 21st-century software developers have objects in their bones and everyone knows how to program with objects in any language, including C. Apparently increasing number of us don’t know that object technology is a <b>way of design</b>, not the use of any particular language or tool. Most design and implementation techniques now associated with C++, Smalltalk, or Java, actually long predate these languages.</p>
<p>So here is how you implement a Point class in C (a Point that you can put on a screen):</p>
<pre>typedef struct PointTag {    int16_t x;   /* x-coordinate */    int16_t y;   /* y-coordinate */} Point;

void Point_ctor(Point *me, int16_t x, int16_t y) {    me-&gt;x = x;    me-&gt;y = y;}

void Point_move(Point *me, int16_t dx, int16_t dy) {    me-&gt;x += dx;    me-&gt;y += dy;}

int16_t Point_dist(Point const *me, Point const *other) {    int16_t dx = me-&gt;x – other-&gt;x;    int16_t dy = me-&gt;y – other-&gt;y;    return (int16_t)sqrt(dx*dx + dy*dy);}. . .

/* example of using Point objects */Point foo, bar, tar;  /* multiple instances of Point */int16_t dist;

Point_ctor(&amp;foo, 0, 0);Point_ctor(&amp;bar, 1, 1);Point_ctor(&amp;tar, -1, 2);

dist = Point_dist(&amp;foo, &amp;bar);Point_move(&amp;tar, 2, 4);dist = Point_dist(&amp;bar, &amp;tar);. . .</pre>
<p>&nbsp;</p>
<p>You can create any number of Point objects as instances of the Point struct. You need to initialize each point with the &#8220;constructor&#8221; Point_ctor(). You manipulate the Points only through the provided functions, which take the pointer &#8220;me&#8221; as the first argument. The &#8220;me&#8221; pointer corresponds directly to the implicit &#8220;this&#8221; pointer in C++.</p>
<p>Moreover, you can as easily implement single inheritance. Assume for example, that you need to add a color attribute to Points. Instead of developing such a colored-Point from scratch, you can <b>inherit</b> most what’s common from Point and add only what’s different. Here’s how you do it:</p>
<pre>typedef struct ColoredPointTag {    Point super;    /* derives from Point */    uint16_t color; /* 16-bit color */} ColoredPoint;

void ColoredPoint_ctor(ColoredPoint *me, int16_t x, int16_t y, uint16_t color) {    Point_ctor(&amp;me-&gt;super, x, y); /* call superclass’ ctor */    me-&gt;color = color;}

.../* example of using ColoredPoint objects */ColoredPoint p1, p2;int16_t dist;

ColoredPoint_ctor(&amp;p1, 0, 2, RED);ColoredPoint_ctor(&amp;p2, 0, 2, BLUE);

/* re-use inherited function */dist = Point_dist((Point *)&amp;p1, (Point *)&amp;p2);</pre>
<p>&nbsp;</p>
<p>As you can see, you implement inheritance by literally embedding the superclass (Point) as the first member of the subclass (ColoredPoint). Such nesting of structures always aligns the first data member &#8217;super&#8217; at the beginning of every instance of the derived structure. This alignment is guaranteed by the C standard. Specifically, WG14/N1124 Section 6.7.2.1.13 says: &#8220;&#8230; A pointer to a structure object, suitably converted, points to its initial member. There may be unnamed padding within a structure object, but not at its beginning&#8221;. This alignment lets you treat a pointer to the derived ColoredPoint struct as a pointer to the Point base struct. All this is legal, portable, and blessed by the Standard.</p>
<p>With this arrangement, you can always safely pass a pointer to ColoredPoint to any C function that expects a pointer to Point. Consequently, all functions designed for the Point structure are automatically available to the ColoredPoint structure. They are all <b>inherited</b>.</p>
<p>There is really nothing to it.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Is Eclipse The Emperor&#8217;s New Clothes?</title>
		<link>http://embeddedgurus.com/state-space/2007/09/is-eclipse-the-emperors-new-clothes/</link>
		<comments>http://embeddedgurus.com/state-space/2007/09/is-eclipse-the-emperors-new-clothes/#comments</comments>
		<pubDate>Wed, 26 Sep 2007 16:59:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2007/09/26/is-eclipse-the-emperors-new-clothes/</guid>
		<description><![CDATA[&#8220;Many years ago there was an Emperor so exceedingly fond of new clothes&#8230;
&#8230;one day came two swindlers. They let it be known they were weavers, and they said they could weave the most magnificent fabrics imaginable. Not only were their colors and patterns uncommonly fine, but clothes made of this cloth had a wonderful way [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Many years ago there was an Emperor so exceedingly fond of new clothes&#8230;</p>
<p>&#8230;one day came two swindlers. They let it be known they were weavers, and they said they could weave the most magnificent fabrics imaginable. Not only were their colors and patterns uncommonly fine, but clothes made of this cloth had a wonderful way of becoming invisible to anyone who was unfit for his office, or who was unusually stupid.</p>
<p>&#8230;so off went the Emperor in his new clothes that were nothing at all. Everyone in the streets and the windows said, &#8220;Oh, how fine are the Emperor&#8217;s new clothes! Don&#8217;t they fit him to perfection? And see his long train!&#8221; Nobody would confess that he couldn&#8217;t see anything, for that would prove him either unfit for his position, or a fool. No costume the Emperor had worn before was ever such a complete success.&#8221;</p>
<p>&#8211;Hans Christian Andersen, &#8220;The Emperor&#8217;s New Clothes&#8221;</p>
<p>To me this little story has a lot to do with Eclipse (www.eclipse.org), which apparently is taking our industry by storm. Obviously, I must be the poor fool, unfit to see the remarkable benefits of Eclipse, but as an embedded developer I really, honestly don’t.</p>
<p>Admittedly, I&#8217;m a very naïve user of Eclipse, with experience limited just to two tools: the Altera Nios II Integrated Development Environment (IDE) and the Texas Instruments Code Composer Essentials for MSP430. Both these tools are based on Eclipse, and because of this both are just terrible.</p>
<p>I&#8217;m really not impressed with the CDT (C/C++ Development Tooling). The CDT workspaces, project files, and makefiles are notoriously difficult to move from one development workstation to another because they contain absolute paths. Even for the simplest project the CDT manages somehow to produce hundreds of files in a directory tree 3-level deep. You tell me how am I supposed to save this in any VCS (Version Control System).</p>
<p>The make process takes ages.</p>
<p>But probably, the worst part is the GDB interface to the remote target. Not only is the connection flaky and dreadfully slow (no comparison at all to other commercial offerings.) The target connectivity spawns some GDB server processes that tend to be &#8220;pigs&#8221; (i.e., take 100% of your host CPU, even if not talking to the target.) This isn&#8217;t the highest level of professionalism&#8230;</p>
<p>Sure, the CDT allows you to forego the automatic makefiles generation and use external Makefiles instead (which I would actually recommend). In principle, I could also go ahead and fix any problems in Eclipse, the CDT plugin, or the GDB server, because they are all available as open source. But, then I must ask if Eclipse is really such a great productivity booster? Don&#8217;t I really have a bigger fish to fry than fighting the tool?</p>
<p>So, as it stands, the Eclipse Emperor is naked for me.</p>
<p>What do you think? What are your experiences with Eclipse in the embedded system space?</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2007/09/is-eclipse-the-emperors-new-clothes/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Embedded Software Crisis or Embedded Software Glut?</title>
		<link>http://embeddedgurus.com/state-space/2007/06/embedded-software-crisis-or-embedded-software-glut/</link>
		<comments>http://embeddedgurus.com/state-space/2007/06/embedded-software-crisis-or-embedded-software-glut/#comments</comments>
		<pubDate>Sat, 23 Jun 2007 02:47:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2007/06/23/embedded-software-crisis-or-embedded-software-glut/</guid>
		<description><![CDATA[I’ve been listening to the recent webcast &#8220;Solving the Embedded Software Crisis&#8221; (see also Rich Nass’ column &#8220;The need for more programmers&#8221; in the May issue of the ESD magazine). Of course, the main thrust of this particular webcast (as well as the ESD column) was the use of code generating tools (such as LabView [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been listening to the recent webcast &#8220;<a href="http://seminar2.techonline.com/s/esd_jun1907">Solving the Embedded Software Crisis</a>&#8221; (see also Rich Nass’ column &#8220;<a href="http://www.embedded.com/showArticle.jhtml?articleID=199202706">The need for more programmers</a>&#8221; in the May issue of the ESD magazine). Of course, the main thrust of this particular webcast (as well as the ESD column) was the use of code generating tools (such as LabView from National Instruments, the sponsor of this webcast) to alleviate the allegedly looming crisis.</p>
<p>But tools or no tools, the real problem in my view is not so much with creating new code, as it is in <b>getting rid</b> of the old code.</p>
<p>In every company I worked for, we had to maintain just one broad code base for all products of that particular division of the company. We only kept adding to this code base, as new features, product variants, and entirely new products were released. But we never removed anything. Needless to say, the code was a kitchen sink of everything that the company ever did, including prototypes and dead ends. Most of the stuff was long obsolete, but it lived on in our code forever.</p>
<p>Adding code is easy. Removing dead code (without breaking the actually used parts of the code) is hard. But without the mechanisms for dropping the old baggage, we face a <b>real</b> Software Crisis.</p>
<p>Yet most managers don’t get it. I remember one day my boss came to my desk wanting to know how much code I have just cranked out. I proudly showed him that I managed to actually remove an ugly function. He was clearly disappointed in my negative productivity.</p>
<p>From all my experience, I’m convinced that getting rid of code is more important than creating new code. As I said, it’s not easy, but rather requires careful planning and actual design for obsolescence. In the future installments of this blog, I plan to provide a few concrete design strategies to allow easy (or at least easier) removing of obsolete code. Stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2007/06/embedded-software-crisis-or-embedded-software-glut/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
