You are on page 1of 40













 








Leading Embedded
Development Tools

The complete development environment


for ARM®, Cortex™, 8051, and C166
microcontroller designs.

1-800-348-8051 www.keil.com
The INTEGRITY RTOS ®

Certified and Deployed Technology

The INTEGRITY RTOS is deployed and certified to:


Railway: EN 50128 SWSIL 4, certified: 2010
Security: EAL6+ High Robustness, certified: 2008
Medical: FDA Class III, approved: 2007
Industrial: IEC 61508 SIL 3, certified: 2006
Avionics: DO-178B Level A, certified: 2002

www.ghs.com

Copyright © 2011 Green Hills Software, Inc. Green Hills, the Green Hills logo and INTEGRITY are trademarks of Green Hills Software, Inc. in the U.S.and/or
internationally. All other trademarks are the property of their respective owners.
Find It Here. Faster.

The Newest Products for Your Newest Designs®

Scan Here
to Watch Video

Authorized distributor for the most advanced


semiconductors and electronic components.
Get What’s Next. Right now at mouser.com.

Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc.
T H E O F F I C I A L P U B L I C AT I O N O F T H E E M B E D D E D S Y S T E M S C O N F E R E N C E S A N D E M B E D D E D. C O M

COLUMNS
barr code 11
How to enforce coding
standards automatically
BY MICHAEL BARR
Too many well-intentioned coding
standards are ineffective and gather
more dust than followers. Automatic
EMBEDDED SYSTEMS DESIGN enforcement points the way to greater
compliance.
VOLUME 24, NUMBER 6
JULY/AUGUST 2011 break points 33
Assume nothing
BY JACK G. GANSSLE

16
An engineer’s duty is to assume noth-
ing, think of everything, and be hum-
ble. Yes, humble.

DEPARTMENTS
#include 5
Dumbing down embedded design
BY RON WILSON
Like it or not, the abstraction in
embedded systems design is
changing, again.

parity bit 7
History repeats itself

Cover Feature: IN PERSON


ESC Boston—September 26–29, 2011
Waking up a capacitive touch-sensing device http://esc-boston.techinsightsevents.com/
with an MCU peripheral ARM TechCon 2011
October 25–27, 2011
BY NITHIN KUMAR MADA AND HARSHA JAGADISH http://e.ubmelectronics.com/armtechcon/
When a capacitive touch screen goes into sleep or standby mode
to save energy, how can you design the system to wake up quickly DesignCon 2012
January 20–February 2, 2012
without degrading its performance or burning a lot of power.
http://designcon.techinsightsevents.com/
Here are two options: a traditional method and a new MCU-
based method. ESC Silicon Valley
March 16–29, 2012
http://esc.eetimes.com/siliconvalley/

27 Designing with core-based high-density FPGAs


BY ROBERT S. GRIMES
One engineer’s adventures designing with microprocessor-based
FPGAs.
ONLINE
www.embedded.com

EMBEDDED SYSTEMS DESIGN (ISSN 1558-2493) print; (ISSN 1558-2507 PDF-electronic) is published 10 times a year as follows: Jan/Feb, March, April, May, June,
July/August, Sept., Oct., Nov., Dec. by the EE Times Group, 600 Harrison Street, 5th floor, San Francisco, CA 94107, (415) 947-6000. Please direct advertising and editorial
inquiries to this address. SUBSCRIPTION RATE for the United States is $55 for 10 issues. Canadian/Mexican orders must be accompanied by payment in U.S. funds with addi-
tional postage of $6 per year. All other foreign subscriptions must be prepaid in U.S. funds with additional postage of $15 per year for surface mail and $40 per year for
airmail. POSTMASTER: Send all changes to EMBEDDED SYSTEMS DESIGN, EE Times/ESD, PO Box #3609, Northbrook, IL 60065-3257, embedsys@omeda.com. For cus-
tomer service, telephone toll-free (847) 559-7597. Please allow four to six weeks for change of address to take effect. Periodicals postage paid at San Francisco, CA and additional
mailing offices. EMBEDDED SYSTEMS DESIGN is a registered trademark owned by the parent company, EE Times Group. All material published in EMBEDDED SYSTEMS
DESIGN is copyright © 2010 by EE Times Group. All rights reserved. Reproduction of material appearing in EMBEDDED SYSTEMS DESIGN is forbidden without permission.
INDUSTRIAL AEROSPACE SYSTEM ON A CHIP

MEDICAL AVIATION CONSUMER

THREADX: WHEN IT
REALLY COUNTS
When Your Company’s Success, And Your Job, Are On The Line -
You Can Count On Express Logic’s ThreadX® RTOS
Express Logic has completed 14 years simply must succeed. Its royalty-free
of successful business operation, licensing model helps keep your BOM low,
and our flagship product, ThreadX, T H R E A D and its proven dependability helps keep
has been used in over 800 million your support costs down as well. ThreadX
electronic devices and systems, repeatedly tops the time-to-market results
ranging from printers to smartphones, from single-chip reported by embedded developers like you. All the while,
SoCs to multiprocessors. Time and time again, when Express Logic is there to assist you with enhancements,
leading manufacturers put their company on the line, training, and responsive telephone support.
when their engineering team chooses an RTOS for their
next critical product, they choose ThreadX. Join leading organizations like HP, Apple, Marvell, Philips, NASA,
and many more who have chosen ThreadX for use in over 800
Our ThreadX RTOS is rock-solid, thoroughly field-proven, million of their products – because their products are too
and represents not only the safe choice, but the most important to rely on anything but the best. Rely on ThreadX,
cost-effective choice when your company’s product when it really counts!

Contact Express Logic to find out more about our ThreadX RTOS, FileX® file system, NetX™ Dual IPv4/IPv6 TCP/IP stack, USBX™
USB Host/Device/OTG stack, and our new PrismX™ graphics toolkit for embedded GUI development. Also ask about our TraceX®
real-time event trace and analysis tool, and StackX™, our patent-pending stack size analysis tool that makes stack overflows a
thing of the past. And if you’re developing safety-critical products for aviation, industrial or medical applications, ask Newnes

about our new Certification Pack™ for ThreadX.


n
Second Editio
E
REAL-TIM
ED
EMBEDD ADING
RE
MULTITH
adX for ARM, Coldfire,
With Thre ices
append
Now with architectures
PowerPC
MIPS and

For a free evaluation copy, visit www.rtos.com • 1-888-THREADX


M
CD-RO
INCLU DED

Copyright © 2010, Express Logic, Inc. Edward


L. Lamie

ThreadX, FileX, and TraceX are registered trademarks, and NetX, USBX, PrismX, StackX, and Certification Pack are trademarks of Express Logic, Inc.
All other trademarks are the property of their respective owners.
EMBEDDED SYSTEMS DESIGN BY Ron Wilson#include
Editorial Director
Ron Wilson
(415) 947-6317
ron.wilson@ubm.com
Dumbing down embedded
Managing Editor
Susan Rambo
(415) 947-6675
susan.rambo@ubm.com
design
Acquisitions/Newsletter Editor,
ESD and Embedded.com
Bernard Cole
(928) 525-9087
bccole@acm.org
Contributing Editors
W hen John Bruggeman left Wind
River to become chief market-
ing officer at Cadence Design
Systems, he didn’t leave the embedded
community so much as he shifted to a
This may sound infeasible and un-
desirable. But please remember that
we’ve seen this shift before. Skilled as-
sembly-level programmers objected—
rightly, but irrelevantly—that compil-
Michael Barr
Jack W. Crenshaw new phase of the industry’s evolution. ers could never generate the code
Jack G. Ganssle Neither did he leave behind his ear for a quality they could for embedded sys-
Dan Saks
great sound bite or his ability to spot tems. Crafters of bare-metal code and
Art Director
Debee Rommel the trend behind the noise. application-specific kernels railed—
debee.rommel@ubm.com At the Design Automation Confer- with equal justification and effect—
Production Director ence this June, Bruggeman showcased that no off-the-shelf RTOS could be as
Donna Ambrosino
dambrosino@ubm-us.com both these traits in one statement. We efficient and reliable as their creations.
Article submissions
were discussing the struggle to increase All were swept away into niches where
After reading our writer’s guidelines, send the level of abstraction in embedded their expertise was defensible. Today
article submissions to Bernard Cole at
bccole@acm.org
systems design, and he remarked, “This there are few surviving practitioners of
whole fragmented, RTOS-tied world is either assembly-language program-
Subscriptions/RSS Feeds/Newsletters
www.eetimes.com/electronics-subscriptions shrinking. We are coming to the point ming or proprietary kernel develop-
Subscriptions Customer Service (Print) where only a handful of mission-critical ment who are not working for an
Embedded Systems Design applications will use an RTOS and code RTOS vendor or—increasingly—a
PO Box # 3609
Northbrook, IL 60065- 3257 developed in C/C++. Everything else is semiconductor company. “Between
embedsys@omeda.com going to the Linux/Android world.” Portland and Alameda, Intel alone has
(847) 559-7597
Bruggeman’s concept is that the about three thousand software devel-
Article Reprints, E-prints, and
Permissions Linux port, libraries, drivers, and tasks opers,” Bruggeman observed.
Mike Lander with hard deadlines are becoming the So what is the future for skilled
Wright’s Reprints
(877) 652-5295 (toll free) responsibilities of the IC vendors, not craftspeople who know an RTOS or
(281) 419-5725 ext.105 the embedded systems developers. All three inside-out, are black-belts in C or
Fax: (281) 419-5712
www.wrightsreprints.com/reprints/index.cfm this work gets done once per chip fami- C++, and can deploy linked-list struc-
?magid=2210 ly, before a new MCU line or SoC is in- tures, hash tables, complex interrupt
Publisher troduced—not once per application. schemes, and similar joys to actually
David Blaza save memory and slash energy con-
(415) 947-6929
When an embedded design team selects
david.blaza@ubm.com a chip, the IC comes with a platform sumption? You need a strategy.
Associate Publisher, ESD and EE Times such as Android or AUTOSAR (the AU- One approach would be to embrace
Bob Dumas Tomotive Open System ARchitecture, if the future: use your skills to become a
(516) 562-5742
bob.dumas@ubm.com you haven’t been following that indus- black belt in Android development, or
try) already running. The embedded an AUTOSAR guru. Another would be
systems design team writes their appli- to find markets likely to be late adopters
cation in Java, just as if they were writ- because of hardware or legacy-code
ing an iPad app. All of the complexity limitations, power constraints, or cul-
Corporate—UBM Electronics of machine-dependent and time-criti- tural isolation. This can delay the in-
Paul Miller Chief Executive Officer
David Blaza Vice President cal code is encapsulated by the chip evitable, but it has about it a bit of
Karen Field Senior Vice President, Content
Felicia Hamerman Vice President, Marketing maker. striping the road in front of the steam-
Brent Pearson Chief Information Officer
Jean-Marie Enjuto Vice President, Finance
roller. Or you can join a semiconductor
Amandeep Sandhu Director of Audience Engagement &
Analytics
Ron Wilson is now edi- company. But I don’t suggest denial.
Barbara Couchois Vice President, Partner Services & tor-at-large on EDN Whatever you decide, don’t just sit
Operations
magazine. This is his last
Corporate—UBM LLC #include as the editorial there.
Marie Myers Senior Vice President,
Manufacturing
director of Embedded
Pat Nohilly Senior Vice President, Strategic Systems Design. You
Development and Business
Administration
may reach him at
ron.wilson@ubm.com.
www.embedded.com | embedded systems design | JULY/AUGUST 2011 5
INNOVATOrs buIld NeTwOrks wITh explOsIVe speed
ANd excepTIONAl INTellIGeNce.

How do innovators build networks of stunning speed and intelligence, while keeping costs squarely under control?
They work with Wind River. Our advanced networking solutions give leading network equipment manufacturers the
packet acceleration, hardware optimization, and system reliability they need to deliver breakthrough performance and
greater value—from the core to the consumer and everywhere in between. All while reducing their costs and cutting
their time-to-market so they can focus on innovation to create a truly competitive edge.

Please visit www.windriver.com/customers to see how Wind River


customers have delivered breakthrough performance and greater value. INNOVATOrs sTArT here.
parity bit
History repeats itself
T here are no really new ideas here
(“Making hardware more like soft-
ware,” Mario Khalaf and Ajay Jag-
tiani, June 2011, www.eetimes.com/
4216418). Xilinx played with this sort
cad, to run the math behind the filter
coefficients I was using. My classmates,
who were well aware of my difficulties
with the subject, were amazed at how
quickly I was able to complete my
of thing at least a decade ago. Several homework, with nice printouts of my
other companies have toyed with this results! The prof was really impressed
stuff. It was too complicated, too ex- when I had a design for a three ele-
pensive, poorly understood, and didn’t ment coupled line filter that worked,
deliver enough advantage (gates) per and the math was completely and ut-
buck. terly wrong, but gave the correct re-
That said, thanks to Moore’s law, sults! I LOVED Mathcad!
the possibilities have vastly increased —Charlie Edmondson
over the last few years and the potential
audience of designers looking for an You should check out wxMaxima, a
edge has increased, too (albeit not in GUI version of Maxima which in turn
countries where manufacturing is in is an Open Source version of MIT
decline, such as England). Macsyma. It does do the symbolic
Additionally the arrival of some math, of course: check out the screen-

!
very sophisticated free-ware packages shots at http://sourceforge.net/project/
like Eclipse that can be tweaked to pull
Twenty years ago the screenshots.php?group_id=126731.
the various tools together should reduce big buzz was making —przemek
the cost-of-entry for small teams want-
ing to add their contribution to the
ecology in this niche.
I’m sure there’s business in here but
! software more like
hardware. Anyone
These days there seems to be growing
interest in using the python Scipy,
Numpy, and Sage for numerical pro-
not as we know it.

How things change!


—chipmnk24

Twenty years ago the big buzz was


! remember the “soft-
ware IC” concept?
cessing. Seems to do pretty much
everything Matlab can as well as
giving you a full-blown programming
language.
—cdhmanning
making software more like hardware. calculate the most simple formula that
Anyone remember the “software IC” you want to stop working on it. Forget about it
concept? —Himanshu_Gupta Collision avoidance as Ron Wilson de-
—cdhmanning scribes (“The gulf between measuring
Many moons ago, I was in my first year and understanding,” Ron Wilson, June
Mathcad upgrades of grad school (and my second year of 2011, www.eetimes.com/4216531)?
I’ve used Mathcad in my previous or- taking EE!) and I had a course in mi- More complex, expensive, more failure
ganization and I also have love/hate re- crowave filter theory, by Matthai. I was prone. Also a great excuse to do your
lationship with it (“The changing face still feeling my way through solving text messaging and let the car do the
of Mathcad,” Jack Crenshaw, June 2011, microwave filters, but I found a system work. Let’s not go overboard with au-
www.eetimes.com/4216405). Most that worked. I used two computers side tomation when the human brain and
times, it’s most sensible to work on it by side. On one I was running Touch- body is best suited to do the work. The
due to its scientific nature while at oth- stone to simulate the filters I was de- brain, use it or lose it.
er times, it’s so slow and sluggish to signing. On the second, I had Math- —KJM

www.embedded.com | embedded systems design | JULY/AUGUST 2011 7


Introducing ZYNQ, the new element in processing.

Finally, the processor comes together with the FPGA in a fully extensible
processing platform called Zynq.™ More intuitive to program in the way
you already know. Fully customizable to your requirements. Faster to
®
implement and get to market. As a software engineer, if you know ARM Cortex,™ you already
know Zynq. And if you know Xilinx, you already know this is innovation you can count on.
Visit us at www.xilinx.com

© Copyright 2011. Xilinx, Inc. XILINX, the Xilinx logo, Zynq, and other designated brands included herein are trademarks of Xilinx in the United States and other countries. All other trademarks are the property of their respective owners.

ARM is the registered trademark of ARM Limited in the EU and other countries. Cortex is the trademark of ARM Limited in the EU and other countries.
I would not use your brain core like that of Star Trek, but it looks like tion of the middle class and greater sep-
temperature example as one of sensor the first ones to go the stars are the aration between the wealthy and the
fusion, but more a case of simulated technology rather than us human. I poor. Elimination of labor, in general,
plant state where we create a simulation wonder if smart robots will go first in does not necessarily help people psy-
of the thermal functioning of the brain to a 50-year voyage into the far, far, and chologically. We want to have a sense of
to create a model of temperatures we away part of the galaxy. It surprised me accomplishment and relevance. Being
cannot measure due to lack of access. to think about the other possible result free to paint, write music, smoke dope,
In the circles I’ve moved in, sensor from a robot boom... “kill all the engi- or watch TV 24 hours a day does not
fusion is far more about using tech- neers”? Yikes! I surely hope that doesn’t make for happy, well-adjusted citizens.
niques like Kalman filters to take meas- become a reality. I’ve been reading All it does is provoke an entitlement
urements from multiple different sen- much of our problem with oil shortages mentality that ultimately results in vio-
sor types and combining them so that and the need for new energy resources lence when the goodies run out.
we can synthesize a set of measure- but to consider now that we have to Why do so many men (particularly) die
ments that provide an accurate meas- tame the technology development for soon after retirement? They lost a sense
urement. For example, accelerometers of purpose—in general, those who sur-
and gyros both have their shortcom- vive are those who have found some-
ings, but sensor fusion allows us to
mash these together to get the useful
info while sidestepping the limitations.
——cdhmanning
! “Kill all the engineers”?
Yikes!
thing to give to others—a sense of be-
ing needed, and accomplishment of
something that matters.
Outside of a few specialties, such as
our own sake adds another burden. It very dangerous working environments
As has been mentioned in the article, it’s looks like humanity has now to evolve and things like self-driving cars, I think
not just the state machine but some- and become more of an adult as we that ultimately robots will benefit only
thing like artificial intelligence, applying need to perhaps stop doing things for those who own the manufacturing sys-
the interpolation and extrapolation our own benefit and not just do be- tems. As robots become more “aware”
techniques, similar to what is being ap- cause we can. That’s maturity. Does hu- they may decide, as some sci-fi writers
plied in robotics. This is OK for robots man history resemble that of a life of a have warned, that people are just get-
to do these kind judgments based upon human being? ting in the way...
the surrounding situation but in an au- —Luis Sanchez —NevadaDave
tomotive situation such inferior dupli-
cation of what a common driver’s hu- Absolutely fascinating, Jack! This edito- Thanks for the article! There is just one
man mind can do in a split second is an rial brings to mind several things: Wolf error, the refresh rate of the screen is
unnecessary addition to already over- and Iron, a book by Gordon Dickson, in not once per second, this only occurs if
crowded electronics in the automobile. which the world’s economic system un- the trigger is not properly set. My guess
—prabhakar_deosthali dergoes a sort of “soft” collapse, and is that the trigger level was not adjusted
those who can actually “do” things (as to the center of the waveform. Once
Situational awareness opposed to those who shuffle money triggered, you will find that the screen
Although of great interest and noble around) are the ones who survive. Sec- refresh is actually very fast (up to 32Hz
goals (“Sensor fusion brings situational ond, regarding Star Trek—one thing depending on the settings). A printable
awareness to health devices,” Supreet that I constantly find fascinating is how manual will be available soon.
Oberoi, www.eetimes.com/design/embed- early sci-fi writers virtually never “got” —ganzziani
ded/4216526) with a potential to benefit how computer technology would shape Gabriel Anzziani
medical care delivery, the implementa- the future societies. In reality, the Enter- Gabotronics
tion [of situational awareness] will al- prise would be run by mind commands
ways have the burden of contemporary from just a few individuals—more like The Gabotronics breadboard oscillo-
medicine—patient compliance with Carl Sagan’s “spaceship” in Cosmos. scope is indeed a really nice piece of
medication / sensor(s). We’re getting close to mentally con- work, and at a great price! Another
—ReneCardenas trolled systems now. similar product is the also open-
I fully expect to see self-steering source Seeed Studio DSO-Nano. It’s a
Creative writing cars available in not too many years. As bit more expensive ($89), and only
I almost got goosebumps reading about far as social attitudes and conse- single channel, but is in a field-ready
slaves (“Of slaves and scopes,” Jack quences—“Them that’s got shall get, enclosure. (It has a different product
Ganssle, June 2011, www.eetimes.com/ them that’s not shall lose...” We will see slant—field versus breadboard use.)
4216410)! I hope the future becomes the continuing trend toward elimina- —Mark Moulding

www.embedded.com | embedded systems design | JULY/AUGUST 2011 9


By Michael Barr
barr code
How to enforce coding standards
automatically
I t’s an unfortunate fact but
a hard truth: enforcement
of coding standards too
often depends on program-
mers already working long
supposed to do, (2) whether
it does so safely and correctly,
and (3) whether the code and
comments taken together are
easily understood by every-
hours and under deadline one on the team.
pressure to be disciplined One of the best ways we,
while they code and to make at Netrino, have found to in-
time to perform peer code re- crease compliance with our
views. And when peer reviews Embedded C Coding Standard
are done in this scenario, they is by configuring static analy-
too easily devolve into stan- sis tools to automatically en-
dards-compliance discussions force individual rules.
that focus on the trees (Is this If your project has a large
line formatted the way we tools budget, the simplest
like?) rather than the forest and most effective option is
(Is this the right code and is it generally to use a sophisticat-
bug free?). ed commercial static-analysis
To ensure whatever cod- tool that includes built-in
ing standard you adopt is fol-
lowed—and thus effective in
keeping bugs out—your team
! Coding standards are an important
tool for fighting bugs. Unfortunately,
support for your chosen cod-
ing standard as well as the
ability to be customized with
should find as many auto-
mated ways to enforce as
many of its rules as possible. ! too many well-intentioned coding
standards gather more dust than
project-specific rule exten-
sions. For example, LDRA
Technology’s static analysis

!
You should make automated engine, a screenshot from
rule checking part of the
followers. Automatic enforcement which is shown in Figure 1,
everyday software build points the way to greater compliance. comes preconfigured with
process. Ideally, you would support for more than a
restrict version control dozen popular coding stan-
check-ins to accept only code that has passed all automat- dards applicable to development of real-time embedded
ed checks. software, including those from JPL, MISRA, and Netrino.
Likewise, no code that violates any automatically-en- For example, out of the box, LDRA’s static analysis en-
forceable rule should be allowed into a peer code review. gine is able to automatically enforce about 80% of the
That way, human code reviewers can focus their limited rules in the Embedded C Coding Standard (Michael Barr,
time and attention on (1) what the module or function is 2009, Netrino). Some coding standard rules, such as those
regarding the names of variables and functions or the con-
tents of comments, can only be enforced by human code
Michael Barr is the author of three books and over reviewers.
60 articles about embedded systems design, as well Teams with smaller budgets should consider using in-
as a former editor in chief of this magazine. He is a
popular speaker at the Embedded Systems expensive tools they may already have. Each such tool will
Conference, a former adjunct professor at the only be capable of enforcing a subset of the rules automat-
University of Maryland, and the president of Netrino. ically, but used together they may be able to enforce the
You may reach him at mbarr@netrino.com or read
his blog at www.embeddedgurus.net/barr-code. majority of the more common rules. The following sec-

www.embedded.com | embedded systems design | JULY/AUGUST 2011 11


barr code
LDRA’s static analysis engine enforces coding standards automatically.

! If your project has an


adequate tools budget, the

! simplest and most effective


option is generally to use a

! sophisticated commercial
static-analysis tool.

Figure 1

tions look at the configuration settings available in a pair of 2.1.b Comments shall never be nested.
widely-used static analysis tools: PC-Lint and RSM.
The relevant PC-Lint configuration generates an error
PC-LINT whenever nested comments are found in the code:
Gimpel Software’s PC-Lint (www.gimpel.com) is a widely
used and inexpensive static-analysis tool for C and C++ pro- +e602
grams that has been continuously maintained for more than
25 years. Pricing depends on the number of users and host PC-Lint can also be used as an aid to clean up nested
operating system but starts at just $389. (For those develop- header file inclusions to comply with this rule:
ing software on Linux/Mac/Unix rather than a “PC”, there is
a version called FlexeLint, which starts at $998.) 4.2.d No header file shall contain a #include statement.
In general terms, PC-lint is a “static analysis tool that will
check your C/C++ source code and find bugs, glitches, in- To configure the tool to highlight header files that aren’t
consistencies, nonportable constructs, redundant code, and actually being used by the source modules that (directly or
much more. It looks across multiple modules, and so, enjoys indirectly) include them, use these settings:
a perspective your compiler does not have.”1 The current ver-
sion is 9.00. In the context of automatically enforcing coding +e766 // Included header file not used in module.
standards, a number of PC-Lint’s configuration settings are +e966 // Indirectly included header not used.
of interest.
For example, suppose you want to enforce a coding rule A complete PC-Lint/FlexeLint 9.00 configuration file to
such as: automatically enforce numerous rules from the Embedded C
Coding Standard is available free online at netrino.com/files/
1.7.c The goto keyword shall not be used.2 pclint_netrino.lnt. Comments in the file make clear which
numbered rule(s) each group of configuration settings
PC-Lint can be configured to generate a warning message enforces.
each time the goto keyword appears in your C/C++ code by
including: RSM
M Squared Technology’s RSM (short for “Resource Standard
-deprecate( keyword, goto, violates coding standard ) Metrics”) is another inexpensive static-analysis tool for pro-
grams written in C/C++ (and similar languages). Pricing de-
in your local .lnt configuration file. pends on the number of users and host operating system but
Here’s another example of a rule that can be automatical- starts at under $200. Versions of the tool are available for
ly enforced this way: non-PC development platforms as well.

12 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


Wherever You Go,
We Won’t Stick Out

5W folding blade adapters

Phihong has the most products


that comply with:
More energy-efficient thin/small adapters from Phihong
California Energy Commission With the smallest footprint and lightest weight adapters available on the market,
European EuP Phihong adapters meet the power, performance and packaging needs for today’s tablet
China Energy Council computers, mobile phones, PDAs, e-readers and other portable devices. And with full
Australian Green House compliance to energy efficiency directives, they are the adapters of choice for charging
EISA today’s portable products. Choose Phihong adapters - we stand out, we don’t stick out.

For information on our low-profile adapters, visit www.phihong.com/small


For smaller ideas to power your next design, call 1-888-PHIHONG (744-4664)
www.phihong.com
Get in.
Buckle up.
The ultimate electronics road trip
has begun!

DRIVEFORINNOVATION
12 months. 10,000 miles. Many technology stops.
Join us on the ultimate electronics road trip. Learn new technologies and
supply chain options, access tools, industry icons and innovators along the way.

Enter for your chance to win


an electric car and other prizes.

driveforinnovation.com
RSM configuration options to enforce the Netrino’s Embedded C Coding Standard.
Rule # Brief rule description Configuration notes
1.2.a Line length limited to 80 characters. Quality Notice 1
1.3.a Braces surround all blocks of code. Quality Notice 22
1.7.c Keyword goto not used. Quality Notice 9
1.7.d Keyword continue not used. Quality Notice 43
1.7.e Keyword break not used outside switch. Quality Notice 44
2.2 Location and content of comments. Quality Notices 17, 20, 51; Options -Es -Ec -EC
3.1 Use of white space. Quality Notices 16, 19
3.5.a No tab characters. Quality Notice 30; Option -Dt
3.6.a UNIX-style (single-character) linefeeds. Option -Du
4.1.a-d Module naming conventions. Option -Rn
4.2.a Precisely one header file per source file. Option -Rn
6.1.a-e Precisely one header file per source file. Quality Notice 2; Option -l
6.2 Cyclomatic complexity of functions. Quality Notices 10, 18, 27; Option -c
6.3.b.i-iii Preprocessor macro safety mechanisms. Option -m
8.2.d If-else if statements always have else. Quality Notice 22
8.3.b Switch statements always have default. Quality Notices 13, 14, 56
8.5.a No unconditional jumps. Quality Notices 9, 43, 444
Table 1

In general terms, RSM is a “source code metrics and Table 1 identifies other coding standard rules that can be
quality analysis tool.”3 The current version is 7.75. Among enforced by RSM as well as the specific quality notices and/or
other things, RSM counts numbers of lines of code vs. white options that apply to each.
space and comments, number of function points, and com- A complete RSM 7.75 configuration file to automatically
putes the cyclomatic complexity of individual functions. enforce numerous rules from the Embedded C Coding Standard
And oh so much more, including lint-like features. In the is available free online at http://netrino.com/files/rsm_netrino.cfg.
context of automatically enforcing coding standards, a Comments in the file make clear which numbered rule(s) each
handful of RSM’s configuration settings are of interest. group of configuration settings enforces.
For example, suppose you want to be notified about lines Remember, it is always cheaper and easier to prevent a
of code that exceed a certain maximum acceptable line length bug from creeping into code than it is to find and kill it after
as in the rule: it has entered. A key strategy in this fight is to write code in
which the compiler, linker, or a static-analysis tool can detect
1.2.a The length of all lines in a program shall be limited to a bugs automatically—in other words, before the code is al-
maximum of 80 characters. lowed to execute.
To be effective, coding standards must be enforceable as
The RSM Quality Analysis feature set always checks code well as actually enforced. Thus, regardless of the coding
for certain signs of quality. Among those is the following: standard you choose to follow, tools and techniques like
those described here should be part of your team’s bug-
Quality Notice No. 1: Emit a quality notice when the physical killing toolbox. ■
line length is greater than the specified number of characters.
ENDNOTES:
Configuration “options” can be also applied. For exam- 1. See http://www.gimpel.com/html/products.htm for other general infor-
ple, to enforce: mation about PC-Lint and FlexeLint features.
2. This and the other numbered rules in this article are excerpted from
3.5.a The tab character shall never appear within any module. the book Embedded C Coding Standard, which is available in print and
electronic editions from http://netrino.com/coding-standard/, Ama-
just add option ‘Dt’ as follows: zon.com, and other booksellers.
3. See http://msquaredtechnologies.com/m2rsm/ for other general infor-
mation about RSM features.
-Dt

www.embedded.com | embedded systems design | JULY/AUGUST 2011 15


cover feature

When a capacitive touch screen goes into sleep or standby mode to


save energy, how can you design the system to wake up quickly without
degrading its performance or burning a lot of power. Here are two
options: a traditional method and a new MCU-based method.
Waking up a
capacitive touch-sensing
device with an MCU
peripheral
BY NITHIN KUMAR MADA AND HARSHA JAGADISH

T ouch-sense keys are gaining popularity with both end users and de-
velopers of everyday human-interface applications because the
technology is aesthetically appealing, easy to use, and avoids any
mechanical design. In particular for developers, capacitive touch
sensors are popular because they can be implemented using a cop-
per pad as part of the standard printed circuit board’s design.

Employed as a user interface to


electronic equipment, capacitive touch
sensors may be arranged in a keypad
matrix and are activated (controls a
signal indicating activation) by a
change (see sidebar on page 22 for de-
tails).
Generally, the keypad matrix of
capacitive touch sensors is fabricated
on a substrate with a protective cover-
change in capacitance of the capacitive ing, such as glass or a clear plastic
touch sensor when an object, usually a resin cover, over the capacitive touch
user’s fingertip, causes the capacitance sensors. The protective covering may
of the capacitive touch sensor to also have alpha-numeric characters

www.embedded.com | embedded systems design | JULY/AUGUST 2011 17


thereon, to identify the purpose of logic circuits of an electronic device
each of the associated capacitive touch are in a run, idle, or sleep mode. Being
sensors. able to scan and control the capacitive
When an object having capaci- touch sensors of the keypad matrix
tance, such as a user’s fingertip, comes will allow the power-consuming logic
in close proximity to the sensor ele- circuits of an electronic device to re-
ment, the capacitance value of the sen- main in the low-power sleep mode un-
sor element changes. This capacitance til awakened for processing data or
change is electronically detected so as controlling a function. Not having to
to generate a signal indicating activa- program for the various power modes
tion of that capacitive touch sensor by of the electronic device simplifies the
the object in code in the user
close proximity
thereto. This
electronic detec- ! What is needed is a way
to provide automated
software
(firmware) appli-
cation.

!
tion must be per- This article
formed by an scan and control of describes two ap-
electronic device, capacitive keypads— proaches, both
which requires based on voltage
power to operate.
But there is a
problem. Current
technology re-
! irrespective of power-
consuming mode.
variation, that can
be used for imple-
menting capaci-
tive touch sensing.
quires that the The first ap-
electronic device, when in a sleep proach is implemented with a charge
mode, be awakened before it scans the time measurement unit (CTMU) pe-
keypad matrix of capacitive touch sen- ripheral that can be implemented on-
sors. When the electronic device is in a chip with the microcontroller. Cap-
low-power standby or sleep mode, one touch solutions using the CTMU
of two things occur: either response peripheral will have a faster response,
time to the detection of the capaci- as it has different ranges of current
tance degrades or power consumption source that help to charge the analog
of the electronic device suffers. channels at a faster rate—thereby im-
Clearly, what is needed is a way to proving the response time of the cap-
provide automated scan and control of touch system.
capacitive keypads—irrespective of The second approach is the more
whether the major power-consuming traditional one which uses the capaci-

A block diagram of capacitance voltage division (CVD).

VDD

ADC
+
ANX Input VCHOLD
CHOLD

CSENSORn
Sensor N

Figure 1

18 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


tance voltage division (CVD) tech-
nique, which uses a microcontroller’s
• After the sensor is grounded, it
must be made an input again.
on-chip analog-to-digital (A/D) con-
verter and doesn’t need a dedicated
• Immediately after it’s made an in-
put, the A/D converter channel is
capacitive-sensing peripheral. The switched to the sensor.
CVD technique is widely used, since it
can be implemented with any micro- This puts the sample and hold cap,
controller that has an A/D converter. CHOLD, in parallel with the sensor ca-
However, the response time is slower pacitor, creating a voltage divider be-
when compared with implementations tween the two. Thus, the voltages on
using a CTMU. the sensor capacitor are the same on
the sample and
USING THE
CVD METHOD
CVD is most of-
ten the tech-
! The CVD method uses the
A/D converter to take a
hold capacitor. The
A/D converter
should be sampled,
and the reading
nique of choice
in low-cost ca-
pacitive touch-
! voltage-based measure-
ment by comparing the
represents a ratio
between caps. With
the addition of a
sensing designs,
to produce an
output voltage
that is a fraction
! known capacitor with the
unknown capacitive sensor.
finger touching the
sensor, the capaci-
tance of the sensor
will increase. As a
of its input volt- result, the voltage
age. It’s commonly used to create a on the sensor will be lower. The A/D
reference voltage or to get a low-volt- converter readings will increase.
age signal proportional to the voltage For capacitive touch sensing, an
to be measured. absolute capacitance reading is not re-
The CVD method uses only the quired, because all decoding decisions
A/D converter to take a voltage-based are related to baseline readings.
measurement by comparing the
known, fixed internal sample-and- THE CTMU APPROACH
hold capacitor with the unknown, Alternatively, the CTMU technique (il-
variable capacitive sensor. lustrated in Figure 2) is based on the
Sensor construction for the CVD is use of a flexible analog module
the same as a typical sensor; a sensor is (CTMU) that incorporates the follow-
an area of copper on a PCB or similar ing elements:
conductive pad for sensing. The sensor
will be tied directly to an A/D converter • A pulse generator.
channel. The rest of the process is done • An on-chip current source.
by configuring the A/D converter and • Edge input signal sources.
I/O in a specific manner.
The basic principle for using the
• Polarity control for each edge
source.
CVD method is as follows: • Edge logic for control edge
sequences and responses to the
• It starts with one A/D converter edges.
channel charging the internal
sample-and-hold cap for the A/D
• A/D converter interface control
logic.
converter to VDD (shown in • Control registers.
Figure 1). • Channels (up to 27) for capacitive
• The sensor channel is then
grounded, to bring it to a known
or time measurement.

state. At the heart of the CTMU is a pre-

www.embedded.com | embedded systems design | JULY/AUGUST 2011 19


cover feature
Block diagram of a microcontroller’s on-chip CTMU peripheral.
CTMUCON

EDGEN CTMUICON
EDGSEQEN
EDG1SELx
EDG1POL ITRIM<5:0> TGEN
EDG2SELx IRNG<1:0> IDISSEN
EDG2POL EDG1STAT CTTRIG
EDG1MOD EDG2STAT Current source
EDG2MOD

CTEDG1 Edge CTMU


control control A/D trigger
CTEDG2 logic logic
Current
control

Timer1
Pulse
generator CTPLS
OC1 A/D Comparator 2
converter input

Comparator 2
output
Note 1: Refer to the specific device data sheet to determine which registers are available on your particular device.

Figure 2

cision current source, designed to pro-


vide a constant reference for measure-
ments. The level of current is user-se-

Embedded lectable across three ranges, or a total


of two orders of magnitude, with the
ability to trim the output in ±2% in-

smxWiFi ™ crements (nominal).


As shown in Figure 3, the CTMU is
designed to work with an A/D convert-
untethers er for precise measurement of capaci-
tance. The CTMU contains a constant
your designs. current source connected to the A/D
converter channel and uses a constant
current source to calculate capacitance
changes and the time difference be-
tween events.
The CTMU works by using a fixed
• 802.11a, b, g, i, n • Security: WEP, WPA, WPA2 current source to charge a circuit. The
• USB WiFi Dongles • Ralink RT2501, RT2573, type of circuit depends on the type of
• PCI WiFi Cards RT2860, RT2870, RT3070, measurement being made. In the case
• Device <–> Access Point RT3572, RT5370 Drivers of charge measurement, the current is
• Device <–> Device • Small RAM/ROM Footprint fixed and the amount of time the cur-
• Optimized for SMX® • Full source code rent is applied to the circuit is fixed.
• Portable to other RTOSs • Royalty free The amount of voltage read by the
A/D converter is then a measurement
www.smxrtos.com/wifi of the capacitance of the circuit. The
voltage read by the A/D is representa-
tive of the amount of time elapsed

20 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


cover feature

! The CTMU is based on Based upon the preceding equation,


the different steps that are involved in
I x T = C x V. By rearranging detecting the touch are as follows:
the CTMU peripheral and A/D
converter.
• The touch sensor is initially

!
charged from a constant current
the equation, a relative
• The capacitive touch sensor, which source for a fixed time period (T),
shift in capacitance can be acts a capacitor, is connected to a and the voltage (V) across the sen-
channel that is multiplexed with sor is measured using the A/D

! sensed by observing a
change in voltage. A block diagram of a CTMU-based cap-touch system.
CTMU
from the time the current source starts
ADC
and stops charging the circuit. Sensor 0 MUX
It can be used to provide up to 27
channels for time or charge measurement,
depending on the specific device and the
number of A/D channels available.
The CTMU can be “programmed”
for a variety signal-source variations, via

Channels
on-chip registers containing control bits

for configuring edge source selection, CA/D
edge source polarity selection, edge se-
quencing, A/D trigger, analog circuit ca-
pacitor discharge, as well as for selecting
the current source range and current
A/D converter
source trim.
Sensor 15
THEORY OF OPERATION
Operationally, the CTMU peripheral is Figure 3

based upon the following relationship


among current, time period, capaci-
tance, and voltage: Charging and discharging waveform of CTMU.

IxT=CxV

where:

• I is the constant current source of


the CTMU.
• T is the fixed period that the CTMU
charges the capacitive touch sensor.
• C is the capacitance of the capaci-
tive touch sensor.
• V is the capacitive touch-sensor
voltage, as read by the A/D
converter.

By rearranging this equation as


follows, a relative shift in capacitance
can be sensed by observing a change in
voltage: Legend: 1. CTMU current source OFF
2. A/D conversion takes place
3. Discharge the capacitive-sense circuit
C = (I x T)/V 4. CTMU current source ON
Figure 4

www.embedded.com | embedded systems design | JULY/AUGUST 2011 21


cover feature

!
converter, as illustrated in tance is caused by a touch on the
Figure 4. sensor pad.
The CTMU peripheral is
• This voltage remains relatively
constant in the successive itera- The availability of a constant cur-
connected directly to the
tions of charge measurement, as
long as no change in the capaci-
rent source in the CTMU peripheral, in
conjunction with a multichannel A/D
! A/D converter’s input,
allowing it to connect to
THE BASICS OF CAPACITIVE TOUCH-SENSING
TECHNOLOGY
The recent success of the capacitive-sensor scroll wheel, now being
! any pin through the ana-
log multiplexer.
used in quite a few devices, has given this technology an edge over
other touch-sense technologies. converter, provides an effective plat-
When any object with capacitive characteristics—such as a fin- form for interfacing to the capacitive
ger—comes close to a capacitive touch sensor, it acts as another ca- touch sensor.
pacitor due to its dielectric nature. This varies the effective capacitance The CTMU peripheral is connected
of the system, which is used to detect the touch. directly to the A/D converter’s input, al-
The finger acts as one of the parallel plates, while another parallel lowing it to connect to any pin through
plate is connected to the sensor input of the chip, as shown in the illus- the analog multiplexer. With this con-
tration below. The iron content in human blood creates strings of ca- figuration, a CTMU peripheral can
pacitors that are aligned to the surface of the body. When such strings measure the capacitance of all the sen-
of capacitors come in proximity with a conductor, a capacitance that sors that are connected to the A/D con-
is essentially coupled to ground is created, which causes a change in verter channels.
the measured voltage, determining the touch. The trim bits associated with the
A typical capacitive touch-sense system is composed of three main current source facilitate the calibra-
functional blocks: tion, to counter the external interfer-
ence and transmission losses.
• An analog block for capacitive sensing.
FIRMWARE ELIMINATES EMI/EMC
• A controller for processing the data. Factors such as humidity, heat, extent of
• An interface block for communicating with a host processor. touch, contaminants on sensors, and
EMI/EMC interference can cause dy-
namic fluctuations in capacitance,
thereby impacting the system’s capaci-
The principles of capacitive touch sensing.
tive touch-sensing capabilities.
To counter these influences,
firmware can be employed with both
CF
the CVD and CTMU methods. Trip-
level dynamic variation can also be
used. These techniques will make the
system more robust.
Area
Additionally, this approach allows
Protective overlay
the use of software filtering, which re-
Copper pad
sists any residual noise on the sensor
d Printed circuit pad by programming the firmware reg-
board isters to distinguish between a touched
CS and an untouched condition.
Design teams can develop algo-
rithms for both the CMTU and CVD
CF Finger capacitance methods that detect multiple-touch
CS Sensor capacitance
d Distance between the plates
conditions, to help the system differ-
entiate between the intended and the
unintended touch. The software can

22 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


Learn today. Design tomorrow.

BOSTON
September 26-29, 2011.
Attend the East Coast’s Leading Embedded Systems Event.

ESC Boston drives product discussions and faster applications, delivers training and education on
the latest technologies, and helps you discover new solutions to your real-world design challenges.
Explore ESC Boston’s Agenda! Customize your schedule and attend sessions covering today’s most
relevant engineering issues.
Applications Hardware for Embedded Keynote Speakers
• HMI and Multimedia Systems
• Systems Architecture • Challenges and Solutions in
• Reliability, Security, and Embedded Designs
Performance • Connectivity and Security
• Remote Monitoring and Wireless • Programmable Logic and Memory
Networking • Low Power Design and
Microcontrollers
Embedded Software Joerg Borchert Charles G. Sodini
• Linux/Android/Open Source Topics in Embedded-System Vice President, Chip LeBel Professor EECS
• Programming for Storage, I/O, and Design Card & Security ICs MIT
Infineon Technolo-
Networking • Architecture Design gies North America
• Programming Languages and • DSP, Communication,
Techniques and Control Design
• RTOS and Real Time Software • HW and Platform Design Register Now for 10% off ANY package!
• Software Processes and Tools • Quality Design and Intellectual
Property Expo Pass registration is FREE.
Tools and Best Practices esc.eetimes.com/boston
• Debugging and Optimizing
• Design and Test
Promo Code: AD1
• Process and Management

Four Events. One Unique Experience.


This year, ESC Boston is part of DesignDays 2011: a distinctive
electronics industry event comprised of 4 design conferences—
ESC Boston, DesignCon East, DesignMED and Designing with LEDs.
Attend all 4 conferences with the All Access Pass!
cover feature
then be calibrated to sense a touch CAPACITIVE TOUCH SENSING tion. The microcontroller that is used
even when there is a thick overlay on WITH A CMTU in the reference design has 13 A/D con-
the capacitive-touch pad. Figure 5 illustrates a reference design verter channels that can connect to a
for a capacitive touch-sense applica- maximum of 42 touch sensors.
The design includes four capacitive
touch sensors connected to Ports A0
FACTORS FOR EFFECTIVE CAPACITIVE through A3. The CTMU module has a
TOUCH-SENSING DESIGNS programmable current source that is
Capacitive touch sensing poses various challenges for real-time appli- used to charge the capacitive touch sen-
cations. The following design considerations help to reduce parasitic sors. The USB receptacle is used for ap-
capacitance and increase finger capacitance, ultimately ensuring bet- plication power as a bus-powered de-
ter sensor design: vice, which uses the microcontroller’s
on-chip USB engine.

Size of the sensor pad. When designing a capacitive sensor,


the shape of the sensor pad is not important. The main concern is the
area of the pad, which determines its sensitivity. The larger the pad,
the better the sensitivity. As a rule of thumb, the area should be about
! Develop algorithms for
CMTU or CVD to detect
the size of an average user’s finger press (15 x 15 mm). If the size of
the sensor pad is larger than optimal, the parasitic capacitance can in-
crease because of the proximity to the ground. ! multiple-touch conditions
to differentiate between

!
Separation between the sensors. The proximity of the sen-
sor to the adjacent sensors should be considered. When a sensor is
the intended and the
touched, the finger introduces additional capacitance not only to the unintended touch.
current sensor, but also to the nearby sensors. Therefore, to insulate the
finger’s capacitance, a space between adjacent sensors must be main- When the sensor is pressed, the
tained. Ideally, the sensors’ separation should be 2 to 3 times the thick- firmware can provide feedback by dis-
ness of the covering material of the capacitive touch-sense system. For playing the appropriate status of the
example, if the thickness of the covering material is 3 mm, the distance touch sensor in the LCD module, driven
between the sensors should be 6 mm to 9 mm, for a typical capacitive- by the pins in Port D. A six-pin header is
touch design. provided, for connecting the reference
Length of the trace. The trace length between the sensor and board to a hardware programmer.
the microcontroller must not be too long, which otherwise might have a
higher susceptibility to parasitic capacitance. This could change the THE CVD OR CTMU
trace resistance and will affect the sensitivity. Ideally, the length of the In this article, we’ve described two ap-
trace should not exceed 12 inches (300 mm). proaches to awakening electronic de-
Material and thickness of the covering material. The vices that have capacitive touch key-
covering material used and its thickness determines the capacitance of pads. We briefly touched on the CVD
a finger that is transmitted to the capacitive-touch sensor. The covering method, which uses a microcontroller’s
material used must have a large dielectric constant, to increase the A/D converter, and went into some de-
sensitivity. Keep the covering material as thin as possible. If the thick- tail about the CTMU method, which in-
ness of the covering material increases, then the crosstalk effect be- volves a separate MCU peripheral. The
tween the sensors increases. CTMU approach enables the design of
Grounding techniques. The sensing method is affected by the scan modules that detect the actuation
parasitic capacitance of a sensor to ground. This can be countered by of any capacitive touch sensor; these
placing ground very close to the sensor, which increases the parasitic modules remain in operation even
capacitance and, hence, reduces its effect on the sensor. when major power-consuming circuits
Selecting an adhesive. The adhesive is used to secure the of the electronic device are in a sleep
covering material to the PCB. The adhesive that is used should be kept mode and will not wake up the major
thin, in order to keep the sensitivity high. Care should be taken to power-consuming circuits until an ac-
make sure that there are no air bubbles when applying the adhesive. tion requiring the circuits is needed.
The bonding instructions of the adhesive should be read before apply- This approach reduces the overall
ing it. power consumption of the electronic

24 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


cover feature
Reference design for a capacitive-touch-sensing application.
C3

0.1

D+

RD3
RD2
RD1
RDO
D-

VDD
44
43
42
41
40
39
38
37
36
35
34
VUSB
RC6
RC5/D+
RC4/D-
RD3
RD2
RD1
RDO

RC2
RC1
N/C
RC7 1 RC7 N/C 33
2 RD4 RC0 32
RD4
RD5 3 RD5 OSC2 31
4 30 Y1
RD6 RD6 OSC1
VDD 5 29 VDD
RD7 RD7 U1 VSS 8 MHz
6 18F46J50 28 D0
VSS VDD C10 C11
7 VDD RE2 27 D1
8 RB0 RE1 26 C8 22pf 22pf D2
C1 9 25
RB1 RE0 D3
10 24 0.1
0.1 RB2 RA5 RD D4
11 VDDCORE/VCAP 23 LCD
RB RD D5
RA0/AN0
RA1/AN1
RA2/AN2
RA3/AN3
RB6/PGC
RB7/PGD

C9 RD D6
MCLR
RB5
N/C
N/C

RD D7
RB

6.8µF
12
13
14
15
16
17
18
19
20
21
22

RD EN
J1 RD RS VDD VDD
PGC
PGD

Sensor1
1 R17 100 RD RW
MCLR VSS VSS
2 VDD Sensor2
3
4 Sensor3
5
6 VDD Sensor4

R18
Program 10K
MCLR
C7
0.1

Figure 5

device while still maintaining the scan- division. He is a group leader for the ca- its MCUs and the CTMU and CVD methods,
ning of the capacitive sensors on such pacitive touch-sense applications team see application notes and product data sheets,
as well as for the PIC18, 8-bit microcon- available from their website online:
things as keypads. When the CTMU de- troller products at Microchip’s India De-
tects a valid key press of a capacitive sign Center.
touch sensor, the CTMU sends an in- • PIC24F Family Reference Manual, Sect. 11
Charge Time Measurement Unit (CTMU),
terrupt to the electronic device that Harsha Jagadish is an applications engi- DS39724B.
brings it out of a sleep mode and into neer in Microchip Technology’s Advanced
an operating mode, for further process- Microcontroller Architecture Division. Har- • Perme, Tom. “AN1101: Introduction to Ca-
pacitive Sensing.”
sha has worked on various PIC microcon-
ing and appropriate action commensu-
rate with the actuation of the specific
trollers for applications ranging from user- • Davison, Burke. “AN1334: Techniques for
Robust Touch Sensing Design.”
interface development, energy-meter
capacitive touch sensor. ■ designs, and personal-electronic-device
accessories for smartphones and tablets.
• Bohn, Bruce. “AN1250: Microchip CTMU
for Capacitive-Touch Applications.”
Nithin Kumar Mada is a senior applica-
tions engineer in Microchip Technology’s FURTHER READING: • Perme, Tom. “AN1298: Capacitive Touch
Using Only an ADC (CVD).”
Advanced Microcontroller Architecture For more information from Microchip about

www.embedded.com | embedded systems design | JULY/AUGUST 2011 25


Call For Entries: July 11th - August 26th
The Electronics Choice Industry Awards is a celebration of excellence in marketing for
the electronics industry. Open exclusively to ECIA members, the competition will honor
those companies that have displayed exceptional branding and marketing programs in
the past year.

Round up samples of your best marketing efforts and enter the contest today. Take
advantage of an opportunity to make history - be the first to win an ECIA marketing
award!
CATEGORIES: P R E S E N T E D AT T H E
E C I A 2 0 11 E x e c u t i v e C o n f e r e n c e
Best PRINT
Brand Awareness Campaign M O N D A Y, O C T O B E R 2 4 T H
Co-OpAdvertising Campaign
I N T E R C O N T I N E N TA L C H I C A G O O ’ H A R E
Corporate Capability Brochure
Corporate Newsletter
ECIA, in partnership with UBM Electronics, is
Best DIGITAL pleased to present this NEW opportunity to
Search Engine Optimization showcase ECIA members’ marketing efforts!
Social Outreach
Web Promotion
Corporate e-Newsletter Your team does a great job of branding your
Best Online Campaign company - this is a chance to grab some well
Best INTEGRATED deserved, industry-wide recognition.
Integrated Marketing
Industry Advocacy
There is a nominal $45 fee per entry -
Best of SHOW enter as many categories as you like.
Single Entry with Highest Score

Enter today at www.eciawards.com

Enter at
www.eciawards.com

ECIA - connecting all segments of the industry: manufacturers, authorized distributors and manufacturers representatives. www.eciaonline.org
feature

One engineer’s adventures designing with microprocessor-based FPGAs.

Designing with
core-based
high-density FPGAs

M
BY ROBERT S. GRIMES

odern field programmable gate arrays (FPGAs) are great


for a wide range of high-speed, complex signal processing
but can be difficult to interface to external systems. Mi-
croprocessors are great for interfacing to other systems,
especially when equipped with Ethernet for communica-
tions, but don’t offer the same levels of performance.

Until recently, designers either had to This article presents my experience


work around the weak spots of the cho- with designing a nontrivial multiproces-
sen device or combine the two devices; sor system, using three networked Xilinx
the latter approach presents new difficul- Virtex-4FX-based controllers.
ties when the data rate between the signal
processing and general processor is sig- PROBLEM AND SOLUTION
nificant. Enter FPGA devices with built- The system being developed by my client
in microprocessors, combining modern was a high-powered, pulsed laser for a
32-bit microcontrollers and Ethernet military application. Unlike laser point-
media access controllers (MACs) with ers, which are continuous wave (CW)
FPGA resources. lasers, this system consists of four pulsed

www.embedded.com | embedded systems design | JULY/AUGUST 2011 27


feature
lasers, using a technique called Q- mand and telemetry interface with an board of old) augmented by a wide
switching to emit a series of regularly- external host system for overall control range of peripheral IP (such as interrupt
spaced laser pulses; the output of these and monitoring, argued strongly for a controllers, serial ports, serial peripheral
four lasers are ultimately combined opti- microprocessor-based solution. interfaces, memory controllers) provide
cally for the final output.1 The initial thought was to combine the basis for a complete microprocessor
So, in addition to general house- an FPGA with a microprocessor, but be- system on a chip, with the benefit of
keeping, the client identified a need early cause it appeared the interface between supporting high-speed interfaces to cus-
on for a number of high-speed photodi- the two would, in itself, provide a chal- tom logic entities.
odes to monitor various aspects of the lenge, I decided to investigate the then-
generated laser pulses. Ultimately, this new Virtex-4FX devices (this was in the HARDWARE DESIGN
evolved into an eight-channel pulse de- fall of 2005). In addition to the high-per- The approach we took during the design
tection and analysis system operating at formance logic and memory resources of this system was to first partition the re-
200 million samples per second (Msps) expected in a modern FPGA, these de- quired functionality into two separate
for each channel. Clearly, no embedded vices incorporate several “hard IP” re- processing elements because the overall
processor system was going to be able to sources, specifically PowerPC 32-bit mi- system design divided the system into a
handle that throughput, so an FPGA- croprocessors and Ethernet MACs. laser assembly and a supporting electron-
based solution was envisioned. These hard IP (IP stands originally ics rack (shown in Figure 1). The laser as-
At the same time, other require- for intellectual property but is also used sembly contains the four laser resonators,
ments, such as a relatively large number to identify a module that may be incor- optics, Q-switches, and the high-speed
of sensors (more than 200), a good porated into an FPGA design, similar to photodiode diagnostic sensors, and had
number of actuators, and unique com- a peripheral chip in a microprocessor to conform to strict physical interfaces.
Because of several high-level deci-
sions, the design of the laser assembly
System block diagram. was further partitioned into two identi-
The master processor and two laser processors are connected via a local Ethernet, which also supports an
external support laptop during development and testing activities. cal halves, each implementing two of the
four lasers; therefore, the laser electron-
ics also consists of two identical assem-
blies. The supporting rack fills a stan-
Laser processor dard 19-inch electronics rack, and
electronics
contains power converters, Q-switch
Laser processor drivers, eight high-power laser pump
electronics
diodes and their drivers, host interfaces,
and the master processor.
So, due to our high-level require-
ments (the laser assembly and support
rack approach) and the resulting system
design, the electronics design evolved
into a multiprocessor solution, with
three processors networked together to
satisfy the functionality demanded.
To keep the development effort
manageable, the three processor assem-
blies utilize a common “digital board,”
each augmented with different analog
boards; of course, the two laser proces-
sors used the same analog board design.
Here is the first instance where the
flexibility of the Virtex-4FX devices paid
Support laptop real benefits; because the two analog
board designs required different mixes
of analog-to-digital (A/D) and digital-
Support electronics rack to-analog (D/A) converters, as well as
with master processor
various other digital I/O interfaces, it
Figure 1

28 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


feature
would have been difficult to meet both
sets of I/O without significant waste.
thresholds were sufficient to pick out the
pulses and inadvertent emissions (laser
• After the pulse is complete, or after
the window is filled, the inadvertent
However, by putting the actual inter- energy outside of the expected window emission threshold is used to look
face circuits (such as photodiode circuit- after Q-switch firing). Finally, I had the for signal excursions above the
ry, A/D converters, serial line drivers) FPGA logic and block RAM resources at nominal level between pulses.
onto the custom analog board, the inter- my disposal, without which there really
connection between the two boards con- was no hope! The time of each pulse threshold
sists largely of direct FPGA I/O connec- The first step in processing the laser crossing is noted in a register, and inad-
tions; hence, a different configuration, data, after acquisition, is to compare vertent events are counted.
with the appropriate IP peripherals, al- against a threshold to detect whether a As I mentioned earlier, the laser
lowed the same processor board to im- pulse or inadvertent emission is present; pulses always happen shortly after the
plement different functionality. Q-switches are triggered. The Virtex-
Now that the high-level system ar-
chitectural decisions had been made, it
was time to detail the designs of each of
the processor subsystems. The first step
! I had the FPGA logic and
block RAM resources at
4FX has a number of 18 kilobit block
RAM resources, which can conveniently
hold 1,024 samples of A/D values, which
at 200 MHz represents a 5-µs window;
was to separate the data acquisition and,
where applicable, real-time analysis
functions into high-rate and low-rate
categories. The high-rate analyses were
! my disposal, without
which there was no hope!
fortunately, the pulses arrive well within
that window. So, a simple state machine
was used to look for the Q-switch trig-
ger, then direct the next 1,024 samples
limited to relatively simple, high-speed actually, three thresholds were used: into the block RAM.
algorithms that are performed on input pulse start, pulse end, and inadvertent After the block RAM has been filled,
data stream by dedicated FPGA logic. emission. The logic for selecting which an interrupt is sent to the PowerPC, in-
Lower-rate, more complex analyses per- to use is simple: forming it of data to be processed. Be-
formed on buffered data, assisted by the cause the lasers are pulsed at 5 kHz, the
stream processing. • From the Q-switch trigger until a
pulse is found, the pulse start
PowerPC must process the four channels
of data within 200 µs. This processing is
HIGH-SPEED PROCESSING threshold is used. greatly simplified by the onset and offset
The high-speed processing entailed sev-
eral measurements:
• From the starting of the pulse, the
pulse end threshold is used until the
delay measurements, as only we only
need to sum (for pulse energy calcula-
signal returns below that. tions) those few points.
• Pulse detection.
Pulse measurements.
• Timing of pulse (delay, width, onset,
offset). The high-speed sampling of the photodiodes allow real-time measurement of a number of pulse characteristics,
• Peak amplitude. such as timing (start and width), amplitude (peak and quiescent laser output), and total pulse energy.

• Total energy. Pulse

• Inadvertent emissions. TStart TPW Enerby

These measurements had to be deter-


mined on a data stream at 200 Msps—a Threshold
new sample every 5 ns! Fortunately, I VPEAK Baseline
had three things in my favor. First, the
optics design ensured that the laser puls-
es—if they occurred at all—would al-
ways appear within a few hundred TEnd
nanoseconds from when the Q-switches
are pulsed; this allowed me to capture a
block of A/D readings triggered by the
Q-switch pulse, and process the data be-
tween pulses (as shown in Figure 2). TWindow
Second, the analog design of the
photodiode amplifier, filtering, and A/D TPRF
conversion was very good, and simple Note: Not drawn to scale.

Figure 2

www.embedded.com | embedded systems design | JULY/AUGUST 2011 29


feature
(An interesting aside here is that, thence, an output pulse; unfortunately, vided by Xilinx, because it requires the
during development, a bug caused the because of mechanical and material dif- chip select signal to be asserted for the
pulse start and end offset measurements ferences, the delay between the electrical 16-bit transfer for each channel read.
to be mishandled, and very weird behav- sync pulse and the output laser pulse The stock Xilinx SPI controller provided
ior ensued. The number of pulses seen varies between the four channels. by the EDK v9.1i tools supported two
was exactly a tenth of what was expect- To allow us to calibrate the four modes of chip select operation, namely
ed, for three of the four channels, but the channels, I designed a custom IP, using automatic (per-byte), or manual.
fourth channel was much worse, and it the Xilinx EDK new peripheral wizard to Unfortunately, the SPI controller
varied considerably. It turned out that connect it to the internal processor bus. only supported 8-bit word sizes, which
because the offsets were wrong, most of This peripheral accepts an externally forces the manual mode; this in turn
the buffers were being processed, and the provided sync pulse, stretches it as re- would have required each channel to ei-
PowerPC was not able to keep up; inter- quired by the Q-switches, and delays ther be polled or an interrupt for each of
rupts were being missed. A not-so-subtle 96 sensors (six 16-channel A/Ds were
reminder of how little time 5 ns is to a
PowerPC!)
Statistics were gathered over a 1/10 ! I created a new SPI16
controller, based on the
used). This was even more aggravating
because the controller had a 16-word
FIFO, which was so tempting; if it were

!
second window of the minimum, maxi- 16-bits wide, a single interrupt could be
mum, and average values for the pulse
supplied version, and used to read all 16 channels from a sin-
characteristics (for example, delays, use it for the A/D. gle A/D converter.
width, peak amplitude, and total ener- So, I decided to create a new SPI16
gy), and these were sent, along with a each output pulse as necessary to time- controller, based on the supplied ver-
representative pulse, to the main proces- align the output laser pulses. In this case, sion, and use it for the A/D. This was an
sor for storage. the peripheral was fully custom, though example of starting with a supplied IP
the wizard automated the connection to and customizing it for your purposes.
OTHER CUSTOM PERIPHERALS the processor. It should be noted that the SPI16 de-
Other custom peripherals were needed to We also had to create custom periph- velopment was quite trivial, as the sup-
support system devices, both unique and erals for some common devices. For an plied SPI IP already had parameters for
common. As an example of the former, as example, we used a number of Analog the width of an SPI word, but they were
I mentioned earlier, the system actually Devices’ multichannel A/D converters not exposed to the design environment,
consists of four lasers that are combined (the 16-channel AD7490) for acquiring so they could not be changed. All I had
to create the final output. In order to gen- sensor data; these were interfaced to the to do was recode them to 16 bits, make a
erate a coherent pulse, the four must emit FPGA via a serial peripheral interface few other minor adjustments, rename
their pulses (nearly) simultaneously. (SPI) with multiple chip selects. The A/D the IP to a unique name, and I was done.
Each laser is sent a “sync pulse” converter represented a challenge not Finally, I believe the newer versions of
which is used to trigger its Q-switch, and well met by the stock SPI controller pro- the Xilinx EDK tools provide more flexi-
ble SPI controllers, so I would not have
had to develop my own.
Software block diagram.
Four distinct software components cooperate to implement the necessary functionality on top of the Virtex-4FX- SOFTWARE DESIGN
based hardware platform. The software to support the hardware
design in meeting the system require-
Master or laser ments consisted of a number of ele-
application
ments, as illustrated in Figure 3. There
are two distinct boot-time programs
MicroMonitor
(which I’ll describe next), along with a
real-time operating system (RTOS)—
RTEMS and
board-support package the Real-Time Executive for Multi-
Bootstrap
processor Systems (RTEMS) and its
board-support package (BSP). The ap-
plication programs (“master” and
“laser” for the respective processors) use
Virtex-4FX
the environment set up for them by Mi-
croMonitor and RTEMS as a framework
Figure 3

30 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


feature
for implementing the required system began this project in the fall of 2005, I Because our board had larger and
functionality. had wanted to use RTEMS as the RTOS different flash parts, I needed to develop
for this project, and seeing that there was suitable drivers for them in order to use
BOOTSTRAPPING no BSP for the Virtex-4FX in their distri- MicroMonitor’s Tiny File System (TFS).
Startup of the PowerPC in the Virtex- bution, I started with a posting to the Because MicroMonitor was designed to
4FX is a bit unusual, as illustrated in Fig- RTEMS mailing list to see if anyone had be readily ported to any embedded
ure 4. When you design an “embedded been working on or considering such a processor board, a framework is provid-
processing” system using this part, you BSP. 2 ed for incorporating drivers tailored for
must include at least one area of block In addition to a couple of responses the devices in use.
RAM to serve as the processor’s initial that proved fruitful there, I got one from As is often the case for similar open-
code and data storage; this is because the Ed Sutter about an initial port of his Mi- source software, both a general skeleton
chip is designed to support small sys- croMonitor boot monitor that he had as well as a variety of examples are pro-
tems with no external memory. Because recently got working on the Virtex-4FX.3 vided within the source tree. If your
of this, the first code the PowerPC exe- While I wasn’t yet concerned with a boot board happens to use an already sup-
cutes is packaged with the rest of the monitor, it seemed a good idea to check ported device, you use the existing driver;
FPGA configuration data, typically out a “working program,” since other if not, you either start with a similar driv-
stored in a Xilinx Platform Flash or oth- than the usual “Hello world” app in the er and modify it as required, or if none
er external nonvolatile memory. Xilinx EDK environment, I had nothing are reasonably similar, you start with the
Given that changing the Platform to work with. So, I downloaded the skeleton. In my case, after researching the
Flash in our system was going to be diffi- codebase and started there. parts we were using and comparing it to
cult once the boards were installed, I de- As Ed had informed me, he had the
cided to keep this initial bootstrap code as basic monitor running, with networking Boot sequence.
simple as possible and use it to start up a and flash drivers for the Xilinx ML403 The boot sequence involves both hardware-only (FPGA
more capable, network-aware boot moni- development board; unfortunately, we configuration by Platform Flash) and several layers of
tor. On startup, the bootstrap simply ex- were using different, bigger flash, and I software “bootstrap” routines, the latter due to the
startup nature of the Virtex-4FX devices (for example,
amines several predefined blocks in the wanted to use the hardware (Xilinx’s) initial processor memory constrained to relatively limited
board’s flash storage (“regular” flash de- TEMAC (hard IP MAC), so new drivers block RAMs).
vices on the processor’s memory bus, not were needed for those features. Of
to be confused with the Platform Flash) course, networking was critical for my
Virtex-4FX
for an executable image; for redundancy, application, and without the ability to configuration
up to four images are supported. write flash, it would be nearly useless, so
Any images found are validated I had the road laid before me on the old
against a CRC-32 checksum, and if that learning curve. Still, having an existing PowerPC release
from reset
checks out, becomes a candidate for implementation for a similar hardware
loading and executing. Once the list of setup greatly eased the “getting started”
bootstrap candidates has been deter- stage.
mined, a simple menu is printed out the Getting the networking up and run- Bootstrap
console serial port, allowing an external ning was my first priority, both in terms
system a chance to select an image to of risk-reduction (because the serial port
load; for our system, this is merely a de- was not available once the processors Bootstrap starts
velopment feature, as we have no access were installed) and because of Ethernet’s MicroMonitor
to the console. superior performance for downloading
If no choice is made within a config- code. Fortunately, Xilinx provides suit-
urable time limit, the first valid image is able low-level drivers that are operating- MicroMonitor
loaded (merely by copying to a known system agnostic, which greatly eased the
location in SDRAM and jumping to the burden of getting a suitable port to Mi-
entry point—at this point, the bootstrap crocross’s MicroMonitor; the task was MicroMonitor sets up
is complete. even easier due to the monitor’s design environment,
starts the application
emphasizing simplicity—specifically, no
BOOT MONITOR interrupts—and a provided hardware-
The boot monitor is responsible for tak- specific template that contains skeletons Master or slave
ing over from the bootstrap and brings of the low-level functions required by application
the system up to full operation. When I MicroMonitor.
Figure 4

www.embedded.com | embedded systems design | JULY/AUGUST 2011 31


feature
existing drivers, I was able to identify a The SD card required additional and how it impacts new develop-
similar driver to serve as my starting work to handle the unique command ment. While the Xilinx EDK is sup-
point. A little careful reading of the data structure for SD Cards, such that the plied with extensive drivers for the
sheet, and I had a working driver. block-level drivers of the RTEMS file sys- IP supplied with the tools, the
tem can read and write data as necessary. RTEMS licensing was incompatible
RTEMS BOARD-SUPPORT PACKAGE This could be an article all in itself, so I with the Xilinx license terms, and
The biggest hurdle at the start of the won’t detail it further here, other than to therefore drivers needed to be writ-
project was clearly getting a development illustrate a different choice that was ten from scratch for the BSP. This
environment and the BSP for RTEMS up made. could require extra work on your
and running. As mentioned in the previ- For the previous drivers, I imple- part, though again, you may be able
ous section, I started this rather daunting mented them within the BSP proper, es- to get some help!
task by a simple post to the RTEMS mail- sentially making them freely available to 3. Expect to put in some good old “el-
ing list.4 my application code. However, for the bow grease,” especially if you are
In addition to the MicroMonitor tip, SD card “middleware” driver, it wasn’t working with new target platforms.
I received two offers of help and several clear where to put it in the general sense; The more different the board and
other notes of interest; the two offers furthermore, the RTEMS BSP build sys- CPU are, the more work you will
turned out to be invaluable. One was tem, based on automake and the like, is need to put in; on the other hand,
from Thomas Doefler, a member of the quite complex and sometimes quite dif- you will get a much deeper under-
RTEMS Steering Committee, who of- ficult. So I made the alternate choice of standing of, and appreciation for,
fered to do all the work with the RTEMS the inner workings—both of the
BSP build system to integrate what I
come up with into the standard tree; as
the project evolved, he also served as a ! Seek collaborators early
and often. Start early by
software and your hardware! ■

Robert S. Grimes is the president of RSG

!
sort of guru and booster.
The other responder had already de- subscribing to a pro- Associates, an embedded systems devel-
opment firm based in Boston, MA. Bob is
veloped drivers for several of the periph- ject’s mailing list or a 1983 graduate of MIT, where he first
learned of the joys of combining hard-
erals, which he was so kind to supply to
the effort. Together with Thomas, we
were able to incorporate the drivers into
a new BSP for the Virtex, which I was
able to build and test with early proto-
! forum and post a simple
statement of your plans.
ware, firmware, and software to control
some small aspect of the world at large.
In recent years, he has been busy sorting
garbage (he developed the control elec-
tronics for a recycling system), discover-
ing water (he designed the FPGA “brain”
types of my applications. building the driver as part of my appli-
in a near-infrared spectrometer that dis-
cation, which was relevant for only the covered water on the Moon during the
OTHER DRIVERS main processor anyway, so exposing a bit NASA LCROSS mission), and developing
Other drivers were needed for the IP of extra complexity there seemed worth vestibular research systems for diagnosing
chosen to communicate with my sys- it, at least to me! The important thing is balance disorders at the Massachusetts
Eye and Ear Infirmary (Boston, MA) and
tems’ devices. For example, we used a to remember there are usually several the University of Berne (Switzerland).
number of SPIs to connect multichannel ways to do most things in software! Robert Grimes may be reached at
A/D and D/A converters, Ramtron rsg@alum.mit.edu.
FRAM nonvolatile memories, an SD LESSONS LEARNED
(Secure Digital) card for removable me- I learned these three lessons:
dia, and a temperature monitor chip. ENDNOTES
This required development of a low- 1. Seek collaborators early and often. 1. Wikipedia definition of “Q- Switching” at
level driver that plugged into RTEMS’ Start early by subscribing to a pro- en.wikipedia.org/wiki/Q-switching.
driver manager framework, and specifi- ject’s mailing list or forum and post 2. Real-Time Executive for Multiprocessor
cally, its I2C/SPI subsystem. Fortunately, a simple statement of your plans. If Systems or RTEMS at www.rtems.com.
because my custom SPI16 peripheral you’re not sure how to start, ask for 3. Ed Sutter’s MicroMonitor is “a free em-
was based on the stock peripheral, I was pointers in getting started. Offer to bedded system boot platform centered
able to use the same driver for both; still, work with others who are working around an extensible embedded flash file
system called TFS.” http://umonfw.com/.
this did take a bit of time to get it exactly on similar applications, or who may
4. Grimes, Robert S. Comment posted on
correct, but once done, I was able to be interested.
RTEMS.com. “RTEMS port to Virtex-
communicate with all the above devices, 2. Understand an open-source soft-
4/PowerPC” at www.rtems.com/ml/rtems-
except the SD card. ware project’s licensing philosophy, users/2005/december/msg00067.html.

32 JULY/AUGUST 2011 | embedded systems design | www.embedded.com


By Jack G. Ganssle
break points
Assume nothing
“ You will say that I am always
conjuring up awful difficulties &
consequences—my answer to
this is it is an important part of the
duty of an engineer.”—Robert
An engineer’s
work built to
last: a recent
photo of the
Britannia Bridge.

Stephenson, the brains behind the

Photo: Andrew Dixon (public domain


Britannia Bridge, which opened in

photo from posted on Wikipedia).


1850 between Wales and the island of
Anglesey. Quite a novel design, it
stood for 120 years before being
structurally compromised by a fire.

TAKE MY KIDS, PLEASE


Raising children is a humbling experi-
ence. The young parent, full of zeal, is
excited by all that he can teach that
formative mind. But the experience
also shapes the much less malleable ! An engineer’s duty is to assume nothing, think of
everything, and be humble. After all, building an

!
adult’s brain. For one finds that
deeply held beliefs and assumptions embedded system is a humbling experience. And
crumble when the tough choices of humility helps with the first two duties.
reality intervene. Very good reasons
arise why that core belief is simply, in
a particular case, wrong.
Here’s just one of many examples: ionably for most of a year, rebuilding BRILLIANT BUT BRITTLE
I was convinced that the high school an engine, swapping transmissions, Building embedded systems is, too, a
kids shouldn’t own cars. Like the fixing the brakes and all of the other humbling experience. Young engi-
Amish, I felt this would disrupt family issues. He learned auto mechanics neers charge into the development
life and create even more of a barrier and a pride in ownership of the battle armed with intelligence and
to communication. Then my son pre- phoenix that was the product of his hubris, often cranking out systems
sented a plan to buy—with his mon- vision and our shared experience. We that may work but are brittle. Unfet-
ey—two 30-year-old VW microbuses established a new, special bond de- tered by bitter experience, they make
with seized engines and a plethora of spite the afflictions of teenagerhood assumptions about the system and the
other problems, and build one work- that lasts to this day, many years later. environment it works within that,
ing vehicle from the pair of wrecks. Parents tack and jibe, slowly while perfectly natural in an academic
The result was exactly the oppo- learning the meta-lesson: all of our cloister, don’t hold up in the gritty
site of what I expected. We spent our assumptions are wrong. real world. Inputs are noisy. Crud gets
free time working together compan- into contacts. Mains power is hardly
pristine. Users do crazy and illogical
things.
The root cause of brittle systems
Jack G. Ganssle is a lecturer and consultant on embedded
development issues. He conducts seminars on embedded systems is making incorrect assumptions—as-
and helps companies with their embedded challenges. sumptions that may be so banal and
Contact him at jack@ganssle.com. so obvious no one questions them.
But question them we must.
For instance, what is the likeli-

www.embedded.com | embedded systems design | JULY/AUGUST 2011 33


“ The secret of business is knowing something
nobody else knows.

- Aristotle Onassis

Know more. Business moves on information. Having the inside track on a


technology trend, a merger, or that next start-up can make all the difference to your business. Our
award-winning editorial team provides timely global coverage of the companies, events and people
that will drive the electronics industry, and delivers it directly to you.
EE Times Confidential is the unique source of vital business intelligence that will keep you a step ahead.

Every issue of EE Times Confidential includes:

The Big Idea: Business models, ecosystems EET on the QT: The inside scoop on deals,
and technology trends partnerships and who’s who

Lay of the Land: News on emerging VC Watch: Track investments


market segments in new companies

IP Landscape: IP trends and litigation news Market Data: Pricing, inventory and more

subscribe today
and receive 10% OFF your annual subscription. Promo Code: LR

Details on annual subscription rates, two-year


subscriptions and corporate subscriptions at
www.eetimesconfidential.com
or call (516) 562-5843.
Hardware interlocks can fail or suf- likely claims me, but I’m equally sure
fer from hard-to-diagnose design flaws. that in 1970, the two-digit-year crowd
adopted the same “heck, it’s a long
1+1≠2 way off” viewpoint. It’s interesting we
Some scientists believe the Ishango rail against CEOs’ short-term gain
bone demonstrates an understanding philosophy, yet practice it ourselves. In
of arithmetic back in the Upper Pale- both cases, the rewards are structured
olithic era. That suggests that for 20 toward today rather than tomorrow.)
millennia Homo sapiens has known Y2K did not teach us what is one
that 1+1=2. of the first lessons in computer sci-
But only a very green developer ence: check your goesintas and goe-
succumbs to the utter fiction that, in soutas. If the date rolls back to a crazy
A scorching snowy day.
the computer world, one and another number, well, there’s something
hood the sun will rise tomorrow? one, too, sum to two. Sure, that’s what wrong. Toss an exception, recompute,
Dumb question; for four billion years we were taught in grade school, be- alert the user, do something! Even
the probability has been 1.0. Surely it’s cause young children aren’t equipped without complex problems like reen-
safe for an engineer to think that the to deal with the exigencies of adult life. trancy and the like, lots of conditions
sun will indeed appear tomorrow as it In a perfect world, a utopia that can create crazy results. Divide by zero
always has. Five or six eons from now doesn’t exist, that summation is in- and C will return a result. The number
it will be a burned-out cinder, but our deed correct. In an embedded system, will be complete garbage, but, if not
systems will be long landfilled by then. caught, that value will then invariably
Recently a developer told me about be manipulated again and again by
a product he worked on that changed
the display’s color scheme depending
on whether it’s night or day. It does a ! I’m pretty sure that the
VP looking down into the
higher-level functions. It’s like replac-
ing a variable with a random number.
Perhaps deep down inside an A/D
very accurate calculation of sunrise or
sunset using location data. Turns out,
a customer took one of the units above ! unit was getting a dose to
his forehead. I saw him a
driver a bit of normalization math ex-
periences an overflow or a divide by
zero. It propagates up the call chain, at

!
the Arctic Circle where it crashed, the each stage being further injected, in-
algorithm unable to deal with a sun
couple of years later, his spected, detected, infected, neglected,
that wouldn’t rise for months. hair now snowy white. and selected (as Arlo Guthrie would
The sun may not rise tomorrow. say). The completely bogus result
Don’t count on anything. might indicate how much morphine
if variables a and b are each one, to push into the patient or how fast to
HARDWARE FAILS, TOO a+b==2 only on a good day. It could set the cruise control.
An instrument I worked on used a large also be 0x1ab32, or any other value, if Sure, these are safety-critical appli-
hunk of radioactive cesium-137 to any of a number of problems arise, cations that might (emphasis on
measure the thickness of steel. Elabo- such as one variable being clobbered “might”) have mitigation strategies to
rate safety precautions included a hard- by a reentrancy problem, or a stack prevent such an occurrence, though
ware interlock to close a shutter, block- getting blown. Google returns 168,000 results to the
ing off the beam, if the software went Complexity buried in our systems, keywords “FDA recall infusion
nuts. But at one point a defect in the even so deeply as to be invisible in the pumps.” But none of us can afford to
hardware design caused the shutter to code we’re examining (such as some tick off the customer in this hyper-
cycle open and closed, over and over, other task running concurrently), can competitive world.
even though the software was correctly corrupt even seemingly obvious My files are rife with photos of sys-
issuing commands to close the radia- truths. tems gone bad because developers
tion source. It’s hard to know where the The Y2K problem taught us only didn’t look for silly results. There are
invisible beam impinged, but I’m pretty one of two very important lessons in dozens of pictures of big digital clocks
sure that the VP looking down into the writing code: memory is cheap, and adorning banks and other buildings
unit was getting a dose to his forehead. one should never clip the leading dig- showing results like “505 degrees,” or
I saw him a couple of years later, his its of the year. (Perhaps we haven’t “-196 degrees.” One would think any-
hair now snowy white. Was the gray learned even that bit of pedagogy. The thing over 150 or so is probably not
from the radiation or his kids with their Unix Y2.038K bug still looms. I’m re- right. And the coldest temperature ever
shiny new drivers’ licenses? assured that will be long after senility recorded in nature on Earth is –129 de-

www.embedded.com | embedded systems design | JULY/AUGUST 2011 35


break points
An expensive parking meter The quote at the beginning of this
bill. Or is that the cost of
World War II-era parking? article is the engineer’s credo: we as-
sume things will go wrong, in varied
and complex ways. We identify and
justify all rosy assumptions. We do
worst case analysis to find those prob-
lem areas, and improve the design so
the system is robust despite inevitable
problems. All engineered systems have
flaws; great engineering mitigates
those flaws.
Software is topsy-turvy. A single

!
darn close but completely absurd. error can wreak havoc. A mechanical
Software is topsy-turvy. A This is a very small sample of engineer can beef up a beam to add
single error can wreak inane results from my files of dumb margin; EEs use fuses and heavier wire
computer errors. All could have been to deal with unexpected stresses. The

! havoc. Get one bit wrong


in a program that encom-
prevented if developers adopted a
mind-set that their assumptions are
likely wrong, chief among those the
beam may bend without breaking; the
wire might get hot but continue to
function. Get one bit wrong in a pro-

! passes 100 million and


the system may crash.
notion that everything will be perfect-
ly fine.
gram that encompasses 100 million
and the system may crash. That’s
99.999999% correctness, or a thou-
sand times better than the Five Nines
requirement, and about two orders of
grees Fahrenheit at the Soviet’s Antarc- magnitude better than Motorola’s
tic research station (Vostok), which is vaunted Six Sigma initiative.
not a bad lower limit for a sanity check. I’ll conclude with a quote from the
Then there’s the system that final report of the board that investi-
claimed power had been out gated the failure of Ariane 5 Flight
for –470,423 hours, –21 minutes, 501. The inertial navigation system ex-
and –16 seconds. A year ago Yahoo perienced an overflow (due to poor as-
More systems
showed the Nasdaq crash- gone wild. sumptions) and the exception handler
ing –16,000,000%, though—take (poorly engineered and tested) didn’t
heart!—the S&P 500 was up 19%. The take corrective action. “The exception
Xdrive app showed –3GB of total disk was detected, but inappropriately han-
space, but happily it let the user know dled because the view had been taken
52GB was free. Ad-Aware complained that software should be considered
the definitions were 730,488 days out correct until it is shown to be at fault.”
of date (Jesus was a just a lad then). Ah, if only the assumption that
While trying to find out if the snow None of these examples endan- software is correct were true! ■
would keep me grounded, Southwest’s gered anyone; it’s easy to dismiss them
site indicated my flight out of Balti- as non-problems. But one can be sure RELATED READING:
more was cancelled but, mirabile dic- the customers were puzzled at best. From the archives, here are some related
tu, it would land on-time in Chicago. Surely the subliminal takeaway is “this columns from Jack Ganssle:
Parking in the city is getting expensive; company is clueless.” I do think we
I have a picture of a meter with an $8 have polarized the industry into safety “Disaster redux!”
million tab. There’s The NY Times’ critical and non-safety critical camps, 12/9/2004, www.eetimes.com/4025051
website, always scooping other news- when another option is hugely impor-
papers, showing a breaking story re- tant: mission critical. Correct receipts
“When disaster strikes”
leased –1,283 minutes ago. A reader are mission-critical at Fuddruckers,
11/11/2004, www.eetimes.com/4025041
sent me a scan of his Fuddrucker’s re- and in the other examples I’ve cited
ceipt: the bill was $5.49, he tendered “mission critical” includes not making
$6.00, and the change is the organization look like an utter “Optimistic Programming”
$5.99999999999996E-02. That’s pretty fool. 4/22/2008, www.eetimes.com/4007556

36 JULY/AUGUST 2011 | embedded systems design | www.embedded.com

You might also like