Practical UML statecharts in C C event driven programming for embedded systems 2nd Edition Miro Samek pdf download
Practical UML statecharts in C C event driven programming for embedded systems 2nd Edition Miro Samek pdf download
https://ebookname.com/product/practical-uml-statecharts-in-c-c-
event-driven-programming-for-embedded-systems-2nd-edition-miro-
samek/
https://ebookname.com/product/programming-embedded-systems-with-
c-and-gnu-development-tools-2nd-edition-michael-barr/
https://ebookname.com/product/test-driven-development-for-
embedded-c-1st-edition-james-w-grenning/
https://ebookname.com/product/practical-c-programming-2nd-
edition-steve-oualline/
https://ebookname.com/product/inhibitors-of-cyclin-dependent-
kinases-as-anti-tumor-agents-enzyme-inhibitors-series-1st-
edition-paul-j-smith/
Recursive Macroeconomic Theory 4th Edition Lars
Ljungqvist
https://ebookname.com/product/recursive-macroeconomic-theory-4th-
edition-lars-ljungqvist/
https://ebookname.com/product/dying-right-the-death-with-dignity-
movement-1st-edition-daniel-hillyard/
https://ebookname.com/product/half-a-century-of-music-in-
england-1837-1887-essays-towards-a-history-francis-hueffer/
https://ebookname.com/product/engineering-wireless-based-
software-systems-and-applications-1st-edition-jerry-zeyu-gao/
https://ebookname.com/product/who-guidelines-for-the-management-
of-postpartum-haemorrhage-and-retained-placenta-1st-edition-
world-health-organization/
Applying Wittgenstein First Edition By Rupert Read
https://ebookname.com/product/applying-wittgenstein-first-
edition-by-rupert-read/
Preface
To create a usable piece of software, you have to fight for every fix, every feature, every little
accommodation that will get one more person up the curve. There are no shortcuts. Luck is involved, but
you don’t win by being lucky, it happens because you fought for every inch.
—Dave Winer
For many years, I had been looking for a book or a magazine article that would describe
a truly practical way of coding modern state machines (UML1 statecharts) in a
mainstream programming language such as C or C++. I have never found such a
technique.
In 2002, I wrote Practical Statecharts in C/C++: Quantum Programming for
Embedded Systems (PSiCC), which was the first book to provide what had been missing
thus far: a compact, efficient, and highly maintainable implementation of UML state
machines in C and C++ with full support for hierarchical nesting of states. PSiCC was
also the first book to offer complete C and C++ source code of a generic, state machine-
based, real-time application framework for embedded systems.
To my delight, PSiCC continues to be one of the most popular books about
statecharts and event-driven programming for embedded systems. Within a year of
its publication, PSiCC was translated into Chinese, and a year later into Korean.
I’ve received and answered literally thousands of e-mails from readers who successfully
used the published code in consumer, medical, industrial, wireless, networking,
research, defense, robotics, automotive, space exploration, and many other
applications worldwide. In 2003 I started to speak about the subject matter at
1
UML stands for Unified Modeling Language and is the trademark of Object Management Group.
www.newnespress.com
xviii Preface
the Embedded Systems Conferences on both U.S. coasts. I also began to consult to
companies. All this gave me additional numerous opportunities to find out firsthand
how engineers actually use the published design techniques in a wide range of
application areas.
What you’re holding in your hands is the second edition of PSiCC. It is the direct result
of the plentiful feedback I’ve received as well as five years of the “massive parallel
testing” and scrutiny that has occurred in the trenches.
New Code
First of all, this book presents an entirely new version of the software, which is now
called Quantum Platform (QP) and includes the hierarchical event processor (QEP) and
the real-time framework (QF) as well as two new components. QP underwent several
quantum leaps of improvement since the first publication six years ago. The
enhancements introduced since the first edition of PSiCC are too numerous to list here,
but the general areas of improvements include greater efficiency and testability and
better portability across different processors, compilers, and operating systems. The two
new QP components are the lightweight, preemptive, real-time kernel (QK) described
in Chapter 10 and the software-tracing instrumentation (QS) covered in Chapter 11.
Finally, I’m quite excited about the entirely new, ultralight, reduced-feature version of
QP called QP-nano that scales the approach down to the lowest-end 8- and 16-bit
MCUs. I describe QP-nano in Chapter 12.
www.newnespress.com
Preface xix
More Examples
Compared to the first edition, this book presents more examples of event-driven
systems and the examples are more complete. I made a significant effort to come up
with examples that are not utterly trivial yet don’t obscure the general principles in too
many details. I also chose examples that don’t require any specific domain knowledge,
so I don’t need to waste space and your attention explaining the problem specification.
www.newnespress.com
xx Preface
Testing Support
A running application built of concurrently executing state machines is a highly
structured affair where all important system interactions funnel through the event-
driven framework that ties all the state machines together. By instrumenting just this
tiny “funnel” code, you can gain unprecedented insight into the live system. In fact, the
software trace data from an instrumented event-driven framework can tell you much
more about the application than any traditional real-time operating system (RTOS)
because the framework “knows” so much more about the application.
Chapter 11 describes the new QS (“spy”) component that provides a comprehensive
software-tracing instrumentation to the QP event-driven platform. The trace data
produced by the QS component allows you to perform a live analysis of your running
real-time embedded system with minimal target system resources and without stopping
or significantly slowing down the code. Among other things, you can reconstruct
complete sequence diagrams and detailed, timestamped state machine activities for all
active objects in the system. You can monitor all event exchanges, event queues,
event pools, time events (timers), and preemptions and context switches. You can also
use QS to add your own instrumentation to the application-level code.
www.newnespress.com
Preface xxi
2
At the time of this writing, the EKIEV-LM3S811 kit was available for $49 (www.luminarymicro.com).
www.newnespress.com
xxii Preface
Intended Audience
This book is intended for the following software developers interested in event-driven
programming and modern state machines:
Embedded programmers and consultants will find a complete, ready-to-use,
event-driven infrastructure to develop applications. The book describes both
state machine coding strategies and, equally important, a compatible real-time
framework for executing concurrent state machines. These two elements are
synergistically complementary, and one cannot reach its full potential without
the other.
Embedded developers looking for a real-time kernel or RTOS will find that the
QP event-driven platform can do everything one might expect from an RTOS
and that, in fact, QP actually contains a fully preemptive real-time kernel as
well as a simple cooperative scheduler.
Designers of ultra low-power systems, such as wireless sensor networks, will
find how to scale down the event-driven, state machine-based approach to fit the
tiniest MCUs. The ultra-light QP-nano version (Chapter 12) combines a
hierarchical event processor, a real-time framework, and either a cooperative or
a fully preemptive kernel in just 1–2KB of ROM.
On the opposite end of the complexity spectrum, designers of very large-scale,
massively parallel server applications will find that the event-driven approach
combined with hierarchical state machines scales up easily and is ideal for
managing very large numbers of stateful components, such as client sessions.
As it turns out, the “embedded” design philosophy of QP provides the critical
per-component efficiency both in time and space.
The open-source community will find that QP complements other open-source
software, such as Linux or BSD. The QP port to Linux (and more generally to
POSIX-compliant operating systems) is described in Chapter 8.
www.newnespress.com
Preface xxiii
GUI developers and computer game programmers using C or C++ will find that
QP very nicely complements GUI libraries. QP provides the high-level “screen
logic” based on hierarchical state machines, whereas the GUI libraries handle
low-level widgets and rendering of the images on the screen.
System architects might find in QP a lightweight alternative to heavyweight
design automation tools.
Users of design automation tools will gain deeper understanding of the inner
workings of their tools. The glimpse “under the hood” will help them use the
tools more efficiently and with greater confidence.
Due to the code-centric approach, this book will primarily appeal to software
developers tasked with creating actual, working code, as opposed to just modeling.
Many books about UML already do a good job of describing model-driven analysis
and design as well as related issues, such as software development processes and
modeling tools.
This book does not provide yet another CASE tool. Instead, this book is about practical,
manual coding techniques for hierarchical state machines and about combining state
machines into robust event-driven systems by means of a real-time framework.
To benefit from the book, you should be reasonably proficient in C or C++ and have a
general understanding of computer architectures. I am not assuming that you have
prior knowledge of UML state machines, and I introduce the underlying concepts in
a crash course in Chapter 2. I also introduce the basic real-time concepts of
multitasking, mutual exclusion, and blocking in Chapter 6.
www.newnespress.com
xxiv Preface
www.newnespress.com
Acknowledgments
First and foremost, I’d like to thank my wonderful family for the unfading support over
the years of creating the software and the two editions of this book.
I would also like to thank the team at Elsevier, which includes Rachel Roumeliotis and
Heather Scherer, and John (Jay) Donahue.
Finally, I’m grateful to all the software developers who contacted me with thought-
provoking questions, bug reports, and countless suggestions for improvements in the
code and documentation. As a rule, a software system only gets better if it is used and
scrutinized by many people in many different real-life projects.
www.newnespress.com
Newnes is an imprint of Elsevier
30 Corporate Drive, Suite 400, Burlington, MA 01803, USA
Linacre House, Jordan Hill, Oxford OX2 8DP, UK
Permissions may be sought directly from Elsevier’s Science & Technology Rights
Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333,
E-mail: [email protected]. You may also complete your request online
via the Elsevier homepage (http://elsevier.com), by selecting “Support & Contact”
then “Copyright and Permission” and then “Obtaining Permissions.”
ISBN: 978-0-7506-8706-5
08 09 10 11 10 9 8 7 6 5 4 3 2 1
Almost all computer systems in general, and embedded systems in particular, are event-
driven, which means that they continuously wait for the occurrence of some external or
internal event such as a time tick, an arrival of a data packet, a button press, or a mouse click.
After recognizing the event, such systems react by performing the appropriate computation
that may include manipulating the hardware or generating “soft” events that trigger other
internal software components. (That’s why event-driven systems are alternatively called
reactive systems.) Once the event handling is complete, the software goes back to waiting for
the next event.
You are undoubtedly accustomed to the basic sequential control, in which a program
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 operating system
mechanism. Though this approach to programming event-driven systems is functional
in many situations, it doesn’t work very well when there are multiple possible
sources of events whose arrival times and order you cannot predict and where it is
important to handle the events in a timely manner. The problem is that while a
sequential program is waiting for one kind of event, it is not doing any other work and
is not responsive to other events.
Clearly, what we need is a program structure that can respond to a multitude of possible
events, any of which can arrive at unpredictable times and in an unpredictable sequence.
Though this problem is very common in embedded systems such as home appliances,
cell phones, industrial controllers, medical devices and many others, it is also very
common in modern desktop computers. Think about using a Web browser, a word
processor, or a spreadsheet. Most of these programs have a modern graphical user
interface (GUI), which is clearly capable of handling multiple events. All developers of
www.newnespress.com
xxviii Introduction
modern GUI systems, and many embedded applications, have adopted a common program
structure that elegantly solves the problem of dealing with many asynchronous events
in a timely manner. This program structure is generally called event-driven programming.
Inversion of Control
Event-driven programming requires a distinctly different way of thinking than
conventional sequential programs, such as “superloops” or tasks in a traditional RTOS.
Most modern event-driven systems are structured according to the Hollywood principle,
which means “Don’t call us, we’ll call you.” 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.
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, 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 program. 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.
www.newnespress.com
Introduction xxix
www.newnespress.com
xxx Introduction
Most important, though, no tool can replace conceptual understanding. For example,
determining which exit and entry actions fire in which sequence in a nontrivial state
transition is not something you should discover by running a tool-supported animation
of your state machine. The answer should come from your understanding of the
underlying state machine implementation (discussed in Chapters 3 and 4). Even if
you later decide to use a design automation tool and even if that particular tool would
use a different statechart implementation technique than discussed in this book, you
will still apply the concepts with greater confidence and more efficiency because of
your understanding of the fundamental mechanisms at a low level.
In spite of many pressures from existing users, I persisted in keeping the QP event-
driven platform lean by directly implementing only the essential elements of the bulky
UML specification and supporting the niceties as design patterns. Keeping the core
implementation small and simple has real benefits. Programmers can learn and deploy
QP quickly without large investments in tools and training. They can easily adapt
and customize the framework’s source code to the particular situation, including
to severely resource-constrained embedded systems. They can understand, and indeed
regularly use, all the provided features.
www.newnespress.com
Introduction xxxi
Object Orientation
Even though I use C as the primary programming language, I also extensively use
object-oriented design principles. Like virtually all application frameworks, QP uses the
basic concepts of encapsulation (classes) and single inheritance as the primary
mechanisms of customizing, specializing, and extending the framework to a particular
application. Don’t worry if these concepts are new to you, especially in C. At the C
language level, encapsulation and inheritance become just simple coding idioms, which
I introduce in Chapter 1. I specifically avoid polymorphism in the C version
because implementing late binding in C is a little more involved. Of course, the C++
version uses classes and inheritance directly and QP/C++ applications can use
polymorphism.
More Fun
When you start using the techniques described in this book, your problems will change.
You will no longer struggle with 15 levels of convoluted if–else statements, and you
will stop worrying about semaphores or other such low-level RTOS mechanisms.
Instead, you’ll start thinking at a higher level of abstraction about state machines,
events, and active objects. After you experience this quantum leap you will find,
as I did, that programming can be much more fun. You will never want to go back to
the “spaghetti” code or the raw RTOS.
How to Contact Me
If you have comments or questions about this book, the code, or event-driven
programming in general, I’d be pleased to hear from you. Please e-mail me at
[email protected].
www.newnespress.com
www.CartoonStock.com
www.newnespress.com
2 Part I
Chapter 2 introduces state machine concepts and the UML notation. Chapter 3 shows
the standard techniques of coding state machines, and Chapter 4 describes a generic
hierarchical event processor. Part I concludes with Chapter 5, which presents a mini-
catalogue of five state design patterns. You will learn that UML state machines are a
powerful design method that you can use, even without complex code-synthesizing
tools.
www.newnespress.com
CHAPTER 1
It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all,
try something.
—Franklin D. Roosevelt
This chapter presents an example project implemented entirely with UML state
machines and the event-driven paradigm. The example application is an interactive
“Fly ‘n’ Shoot”-type game, which I decided to include early in the book so that you can
start playing (literally) with the code as soon as possible. My aim in this chapter is
to show the essential elements of the method in a real, nontrivial program, but without
getting bogged down in details, rules, and exceptions. At this point, I am not trying
to be complete or even precise, although this example as well as all other examples in
the book is meant to show a good design and the recommended coding style. I don’t
assume that you know much about UML state machines, UML notation, or event-driven
programming. I will either briefly introduce the concepts, as needed, or refer you to
the later chapters of the book for more details.
The example “Fly ‘n’ Shoot” game is based on the Quickstart application provided in source
code with the Stellaris EV-LM3S811 evaluation kit from Luminary Micro [Luminary 06].
I was trying to make the “Fly ‘n’ Shoot” example behave quite similarly to the original
Luminary Micro Quickstart application so that you can directly compare the event-driven
approach with the traditional solution to essentially the same problem specification.
www.newnespress.com
4 Chapter 1
NOTE
Although in the text I mostly concentrate on the C implementation, the accompanying Web-
site also contains the equivalent C++ version of virtually every element available in C. The
C++ code is organized in exactly the same directory tree as the corresponding C code, except
you need to look in the <qp>\qpcpp\. . . directory branch.
Specifically to the “Fly ‘n’ Shoot” example, the companion code contains two versions1
of the game. I provide a DOS version for the standard Windows-based PC (see
Figure 1.1) so that you don’t need any special embedded board to play the game and
experiment with the code.
NOTE
I’ve chosen the legacy 16-bit DOS platform because it allows programming a standard PC at
the bare-metal level. Without leaving your desktop, you can work with interrupts, directly
manipulate CPU registers, and directly access the I/O space. No other modern 32-bit devel-
opment environment for the standard PC allows this much so easily. The ubiquitous PC run-
ning under DOS (or a DOS console within any variant of Windows) is as close as it gets to
emulating embedded software development on the commodity 80x86 hardware. Addition-
ally, you can use free, mature tools, such as the Borland C/C++ compiler.
1
The accompanying code actually contains many more versions of the “Fly ‘n’ Shoot” game, but they are
not relevant at this point.
2
At the time of this writing the EV-LM3S811 kit was available for $49 (www.luminarymicro.com).
www.newnespress.com
Getting Started with UML State Machines and Event-Driven Programming 5
versions use the exact same source code for all application components and differ only
in the Board Support Package (BSP).
www.newnespress.com
6 Chapter 1
the “Game Over” screen changes back to the demo screen, where the game waits to be
started again.
Additionally the application contains a screen saver because the OLED display of the
original EV-LM3S811 board has burn-in characteristics similar to a CRT. The screen
saver only becomes active if 20 seconds elapse in the demo mode without starting
the game (i.e., the screen saver never appears during game play). The screen saver is
a simple random pixel type rather than the “Game of Life” algorithm used in the
original Luminary Quickstart application. I’ve decided to simplify this aspect of the
implementation because the more elaborate pixel-mixing algorithm does not contribute
any new or interesting behavior.
After a minute of running the screen saver, the display turns blank and only a single
random pixel shows on the screen. Again, this is a little different from the original
Quickstart application, which instead blanks the screen and starts flashing the User
LED. I’ve changed this behavior because I have a better purpose for the User LED (to
visualize the activity of the idle loop).
Figure 1.1: The “Fly ‘n’ Shoot” game running in a DOS window under Windows XP.
www.newnespress.com
Getting Started with UML State Machines and Event-Driven Programming 7
Figure 1.2: The “Fly ‘n’ Shoot” game running on the Stellaris EV-LM3S811
evaluation board.
As you can see in Figure 1.1, the DOS version uses simply the standard VGA text mode
to emulate the OLED display of the EV-LM3S811 board. The lower part of the DOS screen
www.newnespress.com
8 Chapter 1
NOTE
I strongly recommend that you install the Turbo C++ 1.01 toolset into the directory
C:\tools\tcpp101\. That way you will be able to directly use the provided project files
and make scripts.
Perhaps the easiest way to experiment with the “Fly ‘n’ Shoot” code is to launch the Turbo
C++ IDE (TC.EXE) and open the provided project file GAME-DBG.PRJ, which is located
in the directory <qp>\qpc\examples\80x86\dos\tcpp101\l\game\. You can
modify, recompile, execute, and debug the program directly from the IDE. However, you
should avoid terminating the program stopped in the debugger, because this will not restore
the standard DOS interrupt vectors for the time tick and keyboard interrupts. You should
always cleanly exit the application by letting it freely run and pressing the Esc key.
The next section briefly describes how to run the embedded version of the game. If you
are not interested in the Cortex-M3 version, feel free to skip to Section 1.3, where I start
explaining the application code.
www.newnespress.com
Getting Started with UML State Machines and Event-Driven Programming 9
The sample code for the Stellaris EV-LM3S811 board is located in the
<qp>\qpc\examples\cortex-m3\vanilla\iar\game-ev-lm3s811\ directory,
where <qp> stands for the root directory in which you chose to install the
accompanying software.
The code for the Stellaris kit has been compiled with the 32KB-limited Kickstart edition
of the IAR Embedded Workbench for ARM (IAR EWARM) v 5.11, which is provided
with the Stellaris EV-LM3S811 kit. You can also download this software free of charge
directly from IAR Systems (www.iar.com)after filling out an online registration.
The installation of IAR EWARM is quite straightforward, since the software comes
with the installation utility. You also need to install the USB drivers for the hardware
debugger built into the EV-LM3S811 board, as described in the documentation of
the Stellaris EV-LM3S811 kit.
NOTE
I strongly recommend that you install the IAR EWARM toolset into the directory C:\tools
\iar\arm_ks_5.11. That way you will be able to directly use the provided EWARM work-
space files and make scripts.
Before you program the “Fly ‘n’ Shoot” game to the EV-LM3S811 board, you might
want to play a little with the original Quickstart application that comes preprogrammed
with the EV-LM3S811 kit.
To program the “Fly ‘n’ Shoot” game to the Flash memory of the EV-LM3S811 board,
you first connect the EV-LM3S811 board to your PC with the USB cable provided in the
kit and make sure that the Power LED is on (see Figure 1.2). Next, you need to launch the
IAR Embedded Workbench and open the workspace game-ev-lm3s811.eww located
in the <qp>\qpc\examples\cortex-m3\vanilla\iar\game-ev-lm3s811\
directory. At this point your screen should look similar to the screenshot shown in
Figure 1.3.
The game-ev-lm3s811 project is set up to use the LMI FTDI debugger, which is the
piece of hardware integrated on the EV-LM3S811 board (see Figure 1.2). You can
verify this setup by opening the “Options” dialog box via the Project | Options menu.
Within the “Options” dialog box, you need to select the Debugger category in the panel
on the left. While you’re at it, you could also verify that the Flash loading is enabled
by selecting the “Download” tab. The checked “Use flash loader(s)” check box means
www.newnespress.com
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of The Angel
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Language: English
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com