0% found this document useful (0 votes)
117 views42 pages

Embedded Systems Design, May 2010 (h33t) (Mkrandow)

embedded system design

Uploaded by

Bhavin Panchal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views42 pages

Embedded Systems Design, May 2010 (h33t) (Mkrandow)

embedded system design

Uploaded by

Bhavin Panchal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

VOLUME 23,

NUMBER 4
MAY 2010

EMBEDDED SYSTEMS DESIGN


The Official Publication of The Embedded Systems Conferences and Embedded.com

Using an FPGA
to test a PLL
band calibration
algorithm, 23

Object-code
generation fix, 29

Ganssle: More
on test driven
development, 33

Protect against
malicious software
16

Embedded Systems Conference Chicago


Donald E. Stevens Convention Center,
Rosemont, IL
Conference: June 7–9, 2010 • Expo: June 8–9, 2010
One Size
Doesn’t Fit All

With HCC, you can choose a file system that’s


• File Systems right for your application. HCC products run
• USB Stacks with the broadest range of CPUs and memory
• Bootloaders devices, with or without an operating system.
• Windows Drivers
• Embedded Development THE MOST COMPREHENSIVE PORTFOLIO OF FILE

Services SYSTEMS FOR EMBEDDED APPLICATIONS

HCC-Embedded
FILE SYSTEMS WITH A DIFFERENCE ZbWZYYZY

www.hcc-embedded.com • [email protected]
INTEGRITY RTOS has it.
No one else does.

The NSA has certified the INTEGRITY RTOS technology


to EAL6+. INTEGRITY is the most secure real-time operating
system available and the first and only technology to have
achieved this level.

The NSA also certified INTEGRITY to High Robustness, an even higher


level of security than EAL6+, with 133 additional security mandates
over and above the 161 required for EAL6+.

When security is required, Green Hills Software’s INTEGRITY


RTOS technology is the only option.

Copyright © 2010 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.
www.ghs.com
The Newest Products
For Your Newest Designs
Embed Your Innovation into the Market Place.

XBee® and XBee-PRO® ZB Adapters


pters
mouser.com/digixbeeadapter

SocketModem® iCell / Cell Embedded ZICM2410P2 MeshConnect™ Module A1084-B GPS receiver module
Wireless Modems mouser.com/celzicm2410p2 mouser.com/vincotecha1084b
mouser.com/multitechicell/

WARNING: Designing with Hot, New Products


May Cause a Time-to-Market Advantage.

The newest embedded and wireless products and technologies make designing
even more fun. Experience Mouser’s time-to-market advantage with no
minimums and same-day shipping of the newest products from more than 400
leading suppliers.

mouser.com (800) 346-6873

Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.
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
programming
pointers 9
Alternative models for
memory-mapped devices
BY DAN SAKS
Traditional techniques for communi-
cating with hardware devices can be
inconvenient and error-prone. Here are
EMBEDDED SYSTEMS DESIGN ways to make them simpler and robust.
VOLUME 23, NUMBER 4
MAY 2010 break points 33
An interview with James
Grenning, Part 2

16 BY JACK G. GANSSLE
Is test driven development viable for
embedded systems? Ganssle continues
to grill Grenning on TDD.

DEPARTMENTS
#include 5
Virtualization extends down to
mobile devices
BY RICHARD NASS
The BOM on a virtualized handset can
be reduced significantly over a more
traditional design.

Cover Feature: parity bit 7


Bullet-proofing your software design marketplace 32
BY NAT HILLARY
Applying secure programming standards and methodology can
reduce vulnerabilities in software. IN PERSON
ESC Chicago

23
June 7–9, 2010
How to use an FPGA to test a PLL band esc-chicago.techinsightsevents.com/
calibration algorithm ESC India
BY RUSSELL MOHN July 21–23, 2010
Prototyping an ASIC design first on an FPGA is not only useful www.esc-india.com/
for verification but allows more room for algorithm experimen- ESC Boston
tation. September 20–23, 2010
www.embedded.com/esc/boston

29 Dealing with misbehaving tools Embedded Live


October 20–21, 2010
BY ANDERS HOLMBERG
www.embedded.co.uk
When errors in object code are generated by your tools, such as
the compiler, assembler, and linker, try this novel approach to ESC Silicon Valley
the “update tool or update source” dilemma. May 2–5, 2011
www.embedded.com/esc/sv
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, P.O. Box 3404, Northbrook, IL 60065-9468. For customer service, telephone toll-free
(877) 676-9745. 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
ONLINE
by EE Times Group. All rights reserved. Reproduction of material appearing in EMBEDDED SYSTEMS DESIGN is forbidden without permission. www.embedded.com
B
E
N
C
H
BUILD it [Reliably]
With Express Logic’s award-winning BenchX® IDE or use tools from
over 20 commercial offerings including those from ARM, Freescale,
Green Hills, IAR, Microchip, MIPS, Renesas, and Wind River.

RUN it [Fast]
With Express Logic’s small, fast, royalty-free and industry leading
ThreadX® RTOS, NetX™ TCP/IP stack, FileX® FAT file system, and USBX™
T H R E A D

USB stack.

ANALYZE it [Easily]
T
With Express Logic’s graphical TraceX® event analysis tool, and new
R

StackX™ stack usage analysis tool. See exactly what is happening in your
A
C
E

system, which is essential for both debugging and optimization.

SHIP it [Confidently]
No matter what “it” is you’re developing, Express Logic’s solutions will
help you build it, analyze it, run it, and ship it better and in less time. Join
the success of over 600,000,000 deployed products using
Express Logic’s ThreadX!

B E N C H T H R E A D T R A C E S T A C K

Newnes

ion
Second Edit
E
REAL-TIM
ED
EMBEDD ADING
RE
MULTITH dX
With Threa
re,
ARM, Coldfi

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


ndices for
with appe res
Now architectu
PowerPC
MIPS and

CD-R OM
INCL UDED
ThreadX
Containing

ThreadX, BenchX, TraceX and FileX are a registered trademarks of Express Logic, Inc. All other trade-
n system
demonstratio
examples
and C code

marks are the property of their respective owners.


AD
THRE

L. Lamie
Edward
EMBEDDED SYSTEMS DESIGN

Editorial Director
BY Richard Nass #include
Richard Nass
(201) 288-1904
[email protected]
Managing Editor
Susan Rambo
[email protected]
Virtualization extends down
Contributing Editors
Michael Barr, John Canosa,
Jack W. Crenshaw, Jack G. Ganssle,
Dan Saks, Larry Mittag
to mobile devices
Art Director
Debee Rommel
[email protected]
European Correspondent
Colin Holland
[email protected]
I t wasn’t too long ago that you had
to explain to designers what the
term “virtualization” was all about.
That’s generally not the case anymore.
In fact, the number of systems that are
Kernel Labs (OK Labs, for short)
shows a significant cost savings, up to
46% over a similar, nonvirtualized de-
sign. The biggest savings comes from
being able to eliminate the applica-
Embedded.com Site Editor
Bernard Cole
“virtualized” as part of the design tions processor, which could cost as
[email protected] process has increased considerably. much as $30, depending on the re-
Production Director In most cases, the systems that quired performance, functionality,
Donna Ambrosino were candidates for virtualization and feature set of the handset.
[email protected]
were those of the high-performance Eliminating that apps processor
Subscription Customer Service
P.O. Box 2165, Skokie, IL 60076 variety. Today, you can make an argu- reduces the memory footprint, there-
(800) 577-5356 (toll free) ment to go the virtual route for almost by savings a few dollars. The only ad-
Fax: (847) 763-9606
[email protected] any type of embedded system, includ- ditional cost to the BOM comes in the
www.customerserviceesp.com ing mobile devices. The technology way of the hypervisor needed to do
Article Reprints, E-prints, and that’s been deployed for years in enter- the virtualization, which is where OK
Permissions
Mike O’Brien prise data centers can be driven down Labs comes in. They provide that hy-
Wright’s Reprints into consumer devices. pervisor software.
(877) 652-5295 (toll free)
(281) 419-5725 ext.117 While traditional virtualization of- One example of a handset that
Fax: (281) 419-5712 ten concentrates on a high-end (even was virtualized using the OK Labs
www.wrightsreprints.com/reprints/index.cfm
?magid=2210 multicore) processor and chipset, mo- technology is the Motorola Evoke. It
Publisher
bile virtualization tends to look at the employs an embedded hypervisor
David Blaza paradigm a little differently. For exam- from OK Labs, called the OKL4 (note
(415) 947-6929
[email protected]
ple, it’s no surprise to see multiple that the Motorola Evoke will be the
chips consolidated into a unified object of an upcoming Tear Down ar-
Editorial Review Board
Michael Barr, Jack W. Crenshaw, processor, with dedicated DRAM, glue ticle, where we really get into the nuts
Jack G. Ganssle, Bill Gatliff, logic, and so on. At the same time, and bolts of how the handset was de-
Nigel Jones, Niall Murphy, Dan Saks,
Miro Samek multiple functions can be ported to signed, with a particular focus on the
that single virtualized processor. While virtualization aspect).
potentially increasing performance, The bottom line is that you
there’s a big upside in the reduced shouldn’t dismiss virtualization tech-
number of interconnects required. nology as just being for high-end de-
Corporate—EE Times Group
Paul Miller Chief Executive Officer The single virtualized processor also vices. You could be missing an oppor-
Felicia Hamerman Group Marketing Director
Brent Pearson Chief Information Officer reduces the overall memory footprint tunity to reduce your BOM and
Jean-Marie Enjuto Financial Director
Amandeep Sandhu Manager Audience Engagement required by the system. ultimately simplify your design, espe-
Barbara Couchois Vice President Sales Ops
A side-by-side comparison of a cially if your product lends itself to
handset that was virtualized by Open multiple versions/family members.

Richard Nass
Corporate—UBM LLC ([email protected])
Marie Myers Senior Vice President,
Manufacturing
is the editorial direc-
Pat Nohilly Senior Vice President, Strategic tor of Embedded
Development and Business
Administration
Systems Design maga- Richard Nass
zine, Embedded.com, [email protected]
and the Embedded
Systems Conference.

www.embedded.com | embedded systems design | MAY 2010 5


336 Volts of Green Engineering
MEASURE IT – FIX IT

Developing a commercially viable fuel cell vehicle has been a significant challenge because
of the considerable expense of designing and testing each new concept. With NI LabVIEW
graphical programming and NI CompactRIO hardware, Ford quickly prototyped fuel cell control
unit iterations, resulting in the world’s first fuel cell plug-in hybrid.

MEASURE IT FIX IT

Acquire Analyze Present Design Prototype Deploy


Acquire and Analyze and Present data Design optimized Prototype designs Deploy to the
measure data extract information with HMIs, Web control algorithms on ready-to-run hardware platform
from any sensor with signal interfaces, and systems hardware you choose
or signal processing and reports

Ford is just one of many customers using the NI graphical system design platform to improve the world around
them. Engineers and scientists in virtually every industry are creating new ways to measure and fix industrial
machines and processes so they can do their jobs better and more efficiently. And, along the way, they are
creating innovative solutions to address some of today’s most pressing environmental issues.

>> Download the Ford technical case study at ni.com/336 800 258 7018

©2009 National Instruments. All rights reserved. CompactRIO, LabVIEW, National Instruments, NI, and ni.com are trademarks of National Instruments.
Other product and company names listed are trademarks or trade names of their respective companies. 1121
parity bit
Debating test driven development
W ith respect to the guest (Jack
Ganssle, “An interview with
James Grenning,”April 2010,
p.35, www.embedded.com/224200702),
he is an example of the kind of software
against it. But so far, it is the best tool
going for managing complexity and risk
in real-world projects. You can use TDD
or OOD or whatever you need to use
inside your waterfall block, but your
code correct rather than to prove it in-
correct. Under time pressure, this be-
comes a subconscious driver. It would
be really easy to write “soft” tests in
TDD as well. Addressing this would
person who focuses too much on the block has to be correct in relation to the probably result in developers complain-
software itself and not enough on the other blocks of the project. ing about BTUF (Big Testing Up Front).
whole system. Consider: “The code — Larry Martin —lwriemen
specifies the behavior of the executable Owner, www.GlueLogix.com Chief Frog
program in all its necessary detail.”
That’s a true statement but a mis- I think we all agree that the product
leading one. Only the target processor must be tested as whole in its intend-
can read the code to the level of preci- ed environment. Or...? The require-
sion needed to answer key questions, ments may be flawed or incomplete,
like, “What is the maximum travel of numerous research have labelled poor
this actuator?” or, “What is the maxi- requirements as the most common
mum RPM of this motor?” Therefore, cause for disaster.
human reading of source code is no Also, no matter how loose cou-
substitute for a concise, accurate, top- pling your code has, there might be
level specification, which feeds both im- unforseen dependencies arising when
plementation and system test activities. the code is put together. All modules
Here’s an example. Some years ago,
I heard about a software-related inci-
dent at an automated sawmill. The tar-
! One difference between
embedded and other
in your project will also share the
same system resources. And there will
always be the top-down dependancy
get processor was 16 bits, and the soft-
ware was calibrated in .001-inch units.
The first log that came through the sys- ! software is that physical
systems often have
from main thread -> code modules -
> objects/functions. So the code, too,
needs to be tested in its intended soft-

! complex requirements
tem with diameter greater than 32.767 ware environment, just like the final
inches caused a reversal of some actua- product needs to be tested in the in-
tor that broke stuff and injured the op- of their own. tended “real world” environment.
erator. So code may equal design, but in None of the this excludes TDD.
this case something more explicit was But of course TDD can’t be used as a
needed. I daresay that TDD-style unit TDD is a way to ensure that some replacement for final verification/vali-
testing would not have caught that analysis and design is being addressed dation, that would just be plain stu-
problem either. “up-front”, but this article didn’t cover pid, for the above mentioned reasons.
One difference between embedded all my concerns. I really don’t hope that’s the case...
and other software is that physical sys- I’ve seen a lot of projects run into I’m going to be mean and shoot
tems often have complex requirements trouble, when integration occurs, due to down [Larry Martin’s] example [about
of their own. Those requirements need a lack of planning for integration of the the automated sawmill]. Any decent
to be captured independently of the units. TDD doesn’t seem to address static analyzer (and good compilers as
code, and need system-level testing in- this. well) would have attacked that particu-
dependent of any in-code specification. I also believe it’s very beneficial to lar bug saying something like “implicit
I think a certain personality type have independence in testing, even at conversion between signed and un-
likes to pick apart the waterfall method, the unit test level. It is too common for signed int.” If you scratch your head for
and there are obvious arguments developers to write tests to prove their CONTINUED ON PAGE 32

www.embedded.com | embedded systems design | MAY 2010 7


programming
By Dan Saks
pointers
Alternative models for memory-mapped
devices
D evice drivers typically communi-
cate with hardware devices
through device registers. A driver
sends commands or data to a device by
storing into device registers, or retrieves
Several years ago, I wrote a
series of articles on accessing
memory-mapped device regis-
ters using C and C++.1, 2, 3 At the
time, I focused on how to set
status information or data from a device up pointers (in C or C++) or
by reading from device registers. references (in C++) to enable
Many processors use memory-mapped access to memory-mapped reg-
I/O, which maps device registers to fixed isters. I followed those articles
addresses in the conventional memory with another discussing some
space. To a C or C++ programmer, a alternatives for choosing the
memory-mapped device register looks types that represent the regis-
very much like an ordinary data object. ters themselves.4
Programs can use built-in operators such In the years since then, I’ve
as assignment to move values to or from had many discussions with
memory-mapped device registers. readers and conference atten-
Some processors use port-mapped dees who use other techniques
I/O, which maps device registers to ad- for representing device registers.
dresses in a separate address space, I find that many programmers
apart from the conventional memory are still using approaches that
space. Port-mapped I/O usually re-
quires special machine instructions,
such as the in and out instructions of ! Traditional techniques for
communicating with hard-
are inconvenient and error-
prone. This month, I’ll compare
some popular alternatives, fo-

!
the Intel x86 processors, to move data cusing more on the interface de-
to or from device registers. To a C or ware devices can be incon- sign issues than on the imple-
C++ programmer, port-mapped de- venient and error-prone. mentation details.
vice registers don’t look like ordinary
memory.
The C and C++ standards say
nothing about port-mapped I/O. Pro-
grams that perform port-mapped I/O
! Here are ways to make
them simpler and robust.
MAPPING MEMORY THE
OLD-FASHIONED WAY
Let’s consider a machine with a
variety of devices, including a
must use nonstandard, platform-specific language or li- programmable timer and a couple of UARTs (serial
brary extensions, or worse, assembly code. On the other ports), each of which employs a small collection of device
hand, programs can perform memory-mapped I/O using registers. The timer registers start at location
only standard language features. Fortunately, port- 0xFFFF6000. The registers for UART0 and UART1 start at
mapped I/O appears to be gradually fading away, and few- 0xFFFFD000 and 0xFFFFE000, respectively.
er programmers need to fuss with it. For simplicity, let’s assume that every device register
is a four-byte word aligned to an address that’s a multiple
of four, so that you can manipulate each device register as
an unsigned int. Many programmers prefer to use an
Dan Saks is president of Saks & Associates, a C/C++
training and consulting company. For more informa- exact-width type such as uint32_t. (Types such as
tion about Dan Saks, visit his website at uint32_t are defined in the C99 header <stdint.h>.)5
www.dansaks.com. Dan also welcomes your feed- I prefer to use a symbolic type whose name conveys
back: e-mail him at [email protected].
the meaning of the type rather than its physical extent,
such as:

www.embedded.com | embedded systems design | MAY 2010 9


Innovative Intelligent Integration
© 2010 Actel Corporation. All rights reserved.

FPGA + ARM®Cortex™-M3 + Programmable Analog

Get Smart, visit: www.actel.com/smartfusion


typedef uint32_t device_register; is asking for trouble. You could easily write |= instead of &=,
leave off the ~, or select the wrong mask. Even after you get
Device registers are actually volatile entities—they may everything right, the code is far from self-explanatory.
change state in ways that compilers can’t detect.6, 7 I often in- Rather, you should package this operation as a function
clude the volatile qualifier in the typedef definition, as in: named timer_disable, or something like that, so that you
and your cohorts can disable the timer with a simple func-
typedef uint32_t volatile device_register; tion call. The function body is very short—it’s only a single
assignment—so you should probably declare it as an inline
I’ve often seen C headers that define symbols for device function. If you’re stuck using an older C dialect, you can
register addresses as clusters of related macros. For example: make it a function-like macro.
But what should you pass to that call? Most devices have
// timer registers several registers. Is it really a good idea to make the caller re-
#define TMOD ((unsigned volatile *)0xFFFF6000) sponsible for selecting which of the timer registers to pass to
#define TDATA ((unsigned volatile *)0xFFFF6004) the function, as in:
#define TCNT ((unsigned volatile *)0xFFFF6008)
timer_disable(TMOD);
defines TMOD, TDATA, and TCNT as the addresses of the timer
mode register, the timer data register, and the timer count when only one register will do? Maybe it’s better to just build
register, respectively. The header might also include useful all the knowledge into the function, as in:
constants for manipulating the registers, such as:
inline
#define TE 0x01 void timer_disable(void)
#define TICKS_PER_SEC 50000000
{
*TMOD &= ~TE;
which defines TE as a mask for setting and clearing the timer }
enable bit in the TMOD register, and TICKS_PER_SEC as the
number of times the TCNT register decrements in one second. so that all you have to do is call:
Using these definitions, you can disable the timer using
an expression such as: timer_disable();

*TMOD &= ~TE; This works for the timer because there’s only one timer.
However, my sample machine has two UARTs, each with six
or prepare the timer to count for two seconds using: registers, and many UART operations employ more than one
register.
*TDATA = 2 * TICKS_PER_SEC; For example, to send data out a port, you must use both
*TCNT = 0; the UART status register and the transmit buffer register. The
function call might look like:
Other devices require similar clusters of macros, such as
Listing 1. In this case, UART0 and UART1 have identical sets
of registers, but at different memory-mapped addresses. They Listing 1
can share a common set of bit masks:
// UART 0 registers
#define ULCON0 ((unsigned volatile *)0xFFFFD000)
#define RDR 0x20 ~~~
#define TBE 0x40 #define USTAT0 ((unsigned volatile *)0xFFFFD008)
#define UTXBUF0 ((unsigned volatile *)0xFFFFD00C)
SO WHAT’S NOT TO LIKE? ~~~
This approach leaves a lot to be desired. As Scott Meyers likes
to say, interfaces should be “easy to use correctly and hard to // UART 1 registers
use incorrectly.”8 Well, this scheme leads to just the opposite. #define ULCON1 ((unsigned volatile *)0xFFFFE000)
By itself, disabling a timer isn’t a hard thing to do. When ~~~
#define USTAT1 ((unsigned volatile *)0xFFFFE008)
you’re putting together a system with thousands of lines of
#define UTXBUF1 ((unsigned volatile *)0xFFFFE00C)
code controlling dozens of devices, writing:
~~~

*TMOD &= ~TE;

www.embedded.com | embedded systems design | MAY 2010 11


programmer’s pointers
UART_put(USTAT0, UTXBUF0, c); This gets tedious quickly, and becomes prohibitive when the
number of UARTs is much bigger than two.
Maybe passing two registers isn’t that bad, but what about As an alternative, you could pass an integer designating a
operations that require three or even four registers? UART, as in:
Beyond the inconvenience, calling functions that require
multiple registers invites you to make mistakes such as: typedef unsigned UART_number;

UART_put(USTAT0, UTXBUF1, c); void UART_put(UART_number n, int c);

which passes registers from two different UARTs. In fact, the To make this work, you need a scheme that converts integers
function even lets you accidentally pass a timer register to a into register addresses at run time. Plus, you have to worry
UART operation, as in: about what happens when you pass an integer that’s out of
range.
UART_put(USTAT, TDATA, c);
USING STRUCTURES
Ideally, compilers should catch these errors, but they Structures provide a better way to model memory-mapped
can’t. The problem is that, although each macro has a differ- devices. You can use a structure to represent each collection
ent value, they all yield expressions of the same type, namely, of device registers as a distinct type. For example:
“pointer to volatile unsigned.” Consequently, compilers can’t
use type checking to tell them apart. typedef uint32_t volatile device_register;
Using different typedefs doesn’t help. A typedef doesn’t
define a new type; it’s just an alias for some other type. Thus, typedef struct timer_registers timer_registers;
even if you define the registers as: struct timer_registers
{
// timer registers device_register TMOD;
typedef uint32_t volatile timer_register; device_register TDATA;
device_register TCNT;
#define TMOD ((timer_register *)0xFFFF6000) };
#define TDATA ((timer_register *)0xFFFF6004)
~~~ The typedef before the struct definition elevates the
tag name timer_registers from a mere tag to a full-
// UART 0 registers fledged type name.9 It lets you refer to the struct type as
typedef uint32_t volatile UART_register; just timer_registers rather than as struct timer_
registers.
#define ULCON0 ((UART_register *)0xFFFFD000) You can provide corresponding structures for each device
#define UCON0 ((UART_register *)0xFFFFD004) type:
~~~
typedef struct UART_registers UART_registers;
then timer_register and UART_register are just two dif- struct UART_registers
ferent names for the same type, and you can use them inter- {
changeably throughout your code. Even if you take pains to device_register ULCON;
declare the UART_put function as: device_register UCON;
device_register USTAT;
void UART_put(UART_register *s, device_register UTXBUF;
UART_register *b, int c); ~~~
};
you can still pass it a timer register as a UART register. By any
name, an volatile unsigned is still an volatile unsigned. Using these structures, you can define pointers that let
Again, you could write the UART functions so that they you access device registers. You can define the pointers as
know which registers to use. But there are two UARTs, so macros:
you’d have to write pairs of nearly identical functions, such as:
#define the_timer
void UART0_put(int c); ((timer_registers *)0xFFFF6000)
void UART1_put(int c); #define UART0 ((UART_registers *)0xFFFFD000)

12 MAY 2010 | embedded systems design | www.embedded.com


built with
WindoWs 7
technologies

A mAlfunction in the system


Vol.
5
could cost the plAnt millions...

thE dEvicE has to...


Work pErfEctly, to thE microsEcond,
and havE thE conEctivity to track
pErformancE in rEal timE.

thEy'rE counting
on mE to dElivEr.

WindoWs ® EmbEdEd offErs a highly rEliablE platform, With thE lEvEl of


pErformancE you ned to hElp dElivEr conEctEd dEvicEs that stand out.

Which WindoWs ® embedded-plAtform cAn help you deliver stAndout devices?


find out At WindoWsembedded.com/devicestories
programmer’s pointers
or as constant pointers: which is just a tad simpler than it was before. Plus, you can’t
accidentally mix registers from two UARTs at once.
timer_registers *const the_timer Using structures avoid other mistakes as well. Each struct
= (timer_registers *)0xFFFF6000; is a truly distinct type. You can’t accidentally convert a
UART_registers *const UART0 “pointer to timer_registers” into a “pointer to
= (UART_registers *)0xFFFFD000; UART_registers.” You can only do it intentionally using a
cast. Thus, compilers can easily catch accidents such as:
In C++, using a reinterpret_cast is even better:
timer_disable(UART0); // compile error
timer_registers *const the_timer UART_put(the_timer, c); // compile error
= reinterpret_cast<timer_registers *>
(0xFFFF6000); One of the problems with using structures to model
UART_registers *const UART0 collections of memory-mapped registers is that compilers
= reinterpret_cast<UART_registers *> have some freedom to insert unused bytes, called padding,
(0xFFFFD000); after structure members.10 You may

!
have to use compile switches or
Whichever way you define the pointers,
For device operations that pragma directives to get your struc-
you can use them to access the actual de- use more than one regis- tures just so.4 You can also use com-
vice registers. pile-time assertions to verify that
For example, you can disable the
timer using the expression:
! ter, you can pass just the
address of the entire
the structure members are laid as
they should be.11

the_timer->TMOD &= ~TE;

Even better, you can wrap it in an inline


function:
! register collection rather
than individual registers.
CLASSES ARE EVEN BETTER
In C++, using a class to model hard-
ware registers is even better than us-
ing a struct. I’ll show you why over
the coming months. ■
inline
void timer_disable(timer_registers *t) ENDNOTES:
{ 1. Saks, Dan. “Mapping Memory,” Embedded Systems Programming,
t->TMOD &= ~TE; September 2004, p. 49. www.embedded.com/26807176
} 2. Saks, Dan. “Mapping Memory Efficiently,” Embedded Systems Pro-
gramming, November 2004, p. 47. www.embedded.com/50900224
or a function-like macro: 3. Saks, Dan. “More ways to map memory,” Embedded Systems Pro-
gramming, January 2005, p. 7. www.embedded.com/55301821
#define timer_disable(t) ((t)->TMOD &= ~TE) 4. Saks, Dan. “Sizing and Aligning Device Registers,” Embedded Sys-
tems Programming, May 2005, p. 9. www.embedded.com/55301821
Whether you use an inline function or a macro, you can sim- 5. Barr, Michael. “Introduction to fixed-width integers,”
Embedded.com, January 2004. www.embedded.com/17300092
ply call:
6. Saks, Dan.“Use Volatile Judiciously,” Embedded Systems Program-
ming, September 2005, p. 8. www.embedded.com/170701302
timer_disable(the_timer);
7. Saks, Dan.“Place Volatile Accurately,” Embedded Systems Program-
ming, November 2005, p. 11. www.embedded.com/174300478
For device operations that use more than one register,
8. Meyers, Scott. “The Most Important Design Guideline?” IEEE Soft-
you can pass just the address of the entire register collection ware, July/August 2004, p.14. www.aristeia.com/Papers/IEEE_Soft-
rather than individual registers. Again, sending data to a ware_JulAug_2004_revised.htm
UART uses both the UART status register and the transmit 9. Saks, Dan. “Tag Names vs. Type Names,” Embedded Systems
buffer register. You can declare the UART_put function as: Programming, September 2002, p. 7. www.embedded.com/9900748
10. Saks, Dan. “Padding and rearranging structure members,”
void UART_put(UART_registers *u, int c); Embedded Systems Design, May 2009, p. 11.
www.embedded.com/217200828
and write it so that it picks out the specific registers that it 11. Saks, Dan, “Catching Errors Early with Compile-Time Assertions,”
needs. A call to the function looks like: Embedded Systems Programming, July 2005, p. 7.
www.embedded.com/columns/164900888
UART_put(UART0, c);

14 MAY 2010 | embedded systems design | www.embedded.com


power2solve SEMINAR TOUR
Helping engineers solve complex debug challenges quickly

You’re invited.
Power2Solve is a series of FREE technical seminars for Design Hands-on Training
Engineers and Educators, offering practical, how-to training on the
latest troubleshooting techniques for embedded system design.
You’ll spend a day working side-by-side with your peers and industry
experts from Tektronix finding solutions to your debugging challenges.

Courses Include:
• Power Analysis
Use Tektronix cutting-edge
• Debugging Digital Designs oscilloscopes to perform
• Serial and Parallel Data Debug hands-on digital debug and
• Characterization & Jitter Analysis serial data measurements.

The Power2Solve Seminar is coming to a city near you:


May 18, 2010 The Hyatt Regency Richardson,TX
May 20, 2010 The Radisson Hotel Denver/Longmont, CO
May 24, 2010 The Hyatt Regency San Diego, CA
May 26, 2010 The Hyatt Regency Santa Clara, CA

Attend the event and get


the opportunity to win the
new Apple iPad!

Limited Seating — Register Now.


www.tektronix.com/power2solve
cover feature

Applying secure programming standards and methodology can


reduce vulnerabilities in software.

Bullet-proofing your
software design
BY NAT HILLARY

I
n August 2003, a rolling blackout affected 10 million people in Ontario
and 45 million people in the eastern part of the United States, raising
concern that a cyber-attack by a hostile force was underway. Ultimately
the causes of the blackout were traced to a slew of system, procedur-
al, and human errors and not an act of aggression. Nevertheless, the
event brought home the vulnerability of critical infrastructures connect-
ed to the Internet, raising awareness of the need for secure system
components that are immune to cyber attack.
This increasing dependence on In- definition of secure software will follow
ternet connectivity demonstrates the that provided by the U.S. Department
growing need to build security into of Homeland Security (DHS) Software
software to protect against currently Assurance initiative in “Enhancing the
known and future vulnerabilities. This Development Life Cycle to Produce Se-
article will look specifically at the best cure Software: A Reference Guidebook
practices, knowledge, and tools avail- on Software Assurance.” DHS main-
able for building secure software that’s tains that software, to be considered se-
free from vulnerabilities. cure, must exhibit three properties:

SECURE SOFTWARE 1. Dependability—Software that exe-


In his book The CERT C Secure Coding cutes predictably and operates cor-
Standard, Robert Seacord points out rectly under all conditions.
that there is currently no consensus on 2. Trustworthiness—Software that
a definition for the term software secu- contains few, if any, exploitable vul-
rity. For the purposes of this article, the nerabilities or weaknesses that can

16 MAY 2010 | embedded systems design | www.embedded.com


cover feature
be used to subvert or sabotage the
software’s dependability.
3. Survivability (also referred to as ! Adding a security
perspective to software
standing of the security risks associated
with the domain of the software under
development. This is determined by a

!
“Resilience”)—Software that is re- security risk assessment, a process that
silient enough to withstand attack
requirements ensures ensures the nature and impact of a se-
and to recover as quickly as possi- that security is included curity breach are assessed prior to de-
ble, and with as little damage as ployment in order to identify the secu-
possible from those attacks that it
can neither resist nor tolerate.

The sources of software vulnerabil-


! in the definition of system
correctness.
rity controls necessary to mitigate any
identified impact. The identified securi-
ty controls then become a system re-
quirement.
ities are many, including coding errors, these applications are discovered and re- Adding a security perspective to
configuration errors, and architectural ported on an almost weekly basis. The software requirements ensures that se-
and design flaws. However, most vul- reason is that these applications were curity is included in the definition of
nerabilities result from coding errors. written to satisfy functional, not securi- system correctness that then permeates
In a 2004 review of the National Vul- ty requirements. Testing is used to verify the development process. A specific se-
nerabilities Database for their paper that the software meets each require- curity requirement might validate all
“Can Source Code Auditing Software ment, but security problems can persist user string inputs to ensure that they do
Identify Common Vulnerabilities and even when the functional requirements not exceed a maximum string length. A
Be Used to Evaluate Software Security?” are satisfied. Indeed, software weakness- more general one might be to with-
to the 37th International Conference on es often occur by the unintended func- stand a denial of service attack.
System Sciences, Jon Heffley and Pascal tionality of the system. Whichever end of the spectrum is used,
Meunier found that 64% of the vulner- Building secure software requires it is crucial that the evaluation criteria
abilities resulted from programming er- adding security concepts to the quality- are identified for an implementation.
rors. Given this, it makes sense that the focused software-development lifecycle When translating requirements into
primary objective when writing secure so that security is considered a quality design, it is prudent to consider security
software must be to build security in. attribute of the software under develop- risk mitigation via architectural design.
ment. Building secure code is all about This can be in the choice of implement-
BUILDING SECURITY IN eliminating known weaknesses (Fig- ing technologies or by inclusion of secu-
Most software development focuses on ure 1), including defects, so by necessity rity-oriented features, such as handling
building high-quality software, but secure software is high-quality software. untrusted user interactions by validating
high-quality software is not necessarily Security must be addressed at all inputs and/or the system responses by
secure software. Consider the office, me- phases of the software development an independent process before they are
dia-playing, or web-browsing software lifecycle, and team members need a passed on to the core processes.
that we all use daily; a quick review of common understanding of the security The most significant impact on
the Mitre Corporation’s Common Vul- goals for the project and the approach building secure code is the adoption of
nerabilities and Exposures (CVE) dic- that will be taken to do the work. secure coding practices, including both
tionary will reveal that vulnerabilities in The starting point is an under- static and dynamic assurance measures.
The biggest bang for the buck stems
from the enforcement of secure coding
Building secure code by eliminating known weaknesses.
rules via static analysis tools. With the
introduction of security concepts into
the requirements process, dynamic as-
surance via security-focused testing is
then used to verify that security features
have been implemented correctly.

CREATING SECURE CODE WITH


STATIC ANALYSIS
A review of the contents of the CVE
dictionary reveals that common soft-
Figure 1 ware defects are the leading cause of se-
curity vulnerabilities. Fortunately, these

18 MAY 2010 | embedded systems design | www.embedded.com


Extend battery life with the
MAXQ610 16-bit microcontroller

Up to 12 MIPS in under 4mA—industry’s highest MIPS/mA!


The MAXQ610 microcontroller is designed for low-cost, high-performance, battery-powered applications. This
16-bit, RISC-based microcontroller has a wide operating range (down to 1.7V) for long battery life and ultra-low
power consumption. Its anticloning features and secure MMU enable you to protect your IP.

Application partitioning
VCC: 1.7V to 3.6V
and IP protection

Microcontroller Peripherals
• 16-bit MAXQ RISC core • Two USARTs and one SPI master/slave
• 64KB flash memory, 2KB SRAM communication port
• Ultra-low supply current • Two 16-bit timers/counters
– Active mode: 3.75mA at 12MHz • 8kHz nanoring functions as programmable
– Stop mode: 200nA (typ), 2.0μA (max) wakeup timer
• Wide, 1.7V to 3.6V operating voltage range • IR timer simplifies support for low-
• IP protection speed infrared communication
– Secure MMU supports multiple privilege • IR driver capable of 25mA
levels, helps protect code from copying and sink current
reverse engineering
Temp Range Program Data Operating Price†
Part Package
(°C) Memory Memory Voltage (V) ($)
MAXQ610B 0 to 70 64KB flash 2KB SRAM 1.7 to 3.6 40-TQFN 1.45

MAXQ is a registered trademark of Maxim Integrated Products, Inc.


SPI is a trademark of Motorola, Inc.
†1000-up recommended resale. Prices provided are for design guidance and are FOB USA. International prices will differ due to local duties, taxes, and exchange rates. Not all packages are offered
in 1k increments, and some may require minimum order quantities.

www.maxim-ic.com/MAXQ610-info

DIRECT ™

www.maxim-ic.com/shop www.em.avnet.com/maxim TM

For free samples or technical support, visit our website.


Innovation Delivered is a trademark and Maxim is a registered trademark of Maxim Integrated Products, Inc. © 2010 Maxim Integrated Products, Inc. All rights reserved.
cover feature
vulnerabilities can be attributed to guage in critical systems. The same that can lead to these vulnerabilities.
common weaknesses in code, and a practice can be used to similar effect in The standards in each of these diction-
number of dictionaries have been creat- the creation of secure software. aries can be enforced by the use of stat-
ed to capture this information, such as Of the common exploitable soft- ic analysis tools that help to eliminate
the Common Weakness Enumeration ware vulnerabilities that appear in the both known and unknown vulnerabili-
(CWE) dictionary from the Mitre ties while also eliminating latent errors
Corporation and the CERT-C Secure
Coding Standard from the Software
Engineering Institute at Carnegie ! Static software analysis
tools assess the code
in code. For example, the screenshot in
Figure 2 shows the detection of a buffer
overflow vulnerability due to improper

!
Mellon. These secure coding stan- data types.
dards can be enforced by the use of
under analysis without Static software analysis tools assess
static analysis tools, so that even executing it and are the code under analysis without actual-
novice secure software developers can ly executing it. They are particularly
benefit from the experience and
knowledge encapsulated within the
standards.
The use of coding standards to
! adept at identifying cod-
ing standard violations.
adept at identifying coding standard vi-
olations. In addition, they can provide a
range of metrics that can be used to as-
sess and improve the quality of the code
eliminate ambiguities and weaknesses under development, such as the cyclo-
in the code under development has CVE dictionary, some occur more than matic complexity metric that identifies
been proven extremely successful in the others—user input validation, buffer unnecessarily complex software that’s
creation of high-reliability software, overflows, improper data types, and difficult to test.
such as the use of the Motor Industry improper use of error and exception When using static analysis tools for
Software Reliability Association (MIS- handling. The CWE and CERT-C dic- building secure software, the primary
RA) Guidelines for the use of the C lan- tionaries identify coding weaknesses objective is to identify potential vulner-
abilities in code. Example errors that
static analysis tools identify include:

• Insecure functions
• Array overflows

Embedded •

Array underflows
Incorrectly used signed and

smxWiFi ™ unsigned data types

Since secure code must, by nature,

untethers be high-quality code, static analysis


tools can be used to bolster the quality

your designs. of the code under development. The


objective here is to ensure that the soft-
ware under development is easy to veri-
fy. The typical validation and verifica-
tion phase of a project can take up to
s 802.11a, b, g, i, n sDevice <–> Device 60% of the total effort, while coding
sUSB WiFi Dongles sSecurity: WEP, WPA1, WPA2 typically only takes 10%. Eliminating
sPCI WiFi Cards sRalink RT25xx, RT2860, defects via a small increase in the cod-
sDevice <–> Access Point RT2870, RT3070 Support ing effort can significantly reduce the
burden of verification, and this is where
static analysis can really help.
Ensuring that code never exceeds a
maximum complexity value helps to
800.366.2491 [email protected] enforce the testability of the code. In
www.smxrtos.com addition, static analysis tools identify
other issues that affect testability, such
Full source code s Optimized for SMX® s Portable to other RTOSs
as having unreachable or infeasible
Small RAM/ROM Footprint s Royalty free

20 MAY 2010 | embedded systems design | www.embedded.com


cover feature

!
code paths or an excessive number of test-case generation, execution and
loops.
The most effective and maintenance streamline the unit
By eliminating security vulnerabili- cheapest way of ensuring testing process, easing the unit test-
ties, identifying latent errors, and en- ing burden and reinforcing unit
suring the testability of the code under
development, static analysis tools help
ensure that the code is of the highest
! that the code under
development meets its •
test accuracy and completeness.
Dynamic analysis—analyses per-
formed while the code is executing
quality and secure against not only cur-
rent threats but unknown threats as
well. ! security requirements is
via unit testing.
provide valuable insight into the
code under analysis that goes be-
yond test-case execution. Structur-
al coverage analysis, one of the
FITTING TOOLS INTO THE more popular dynamic analysis
PROCESS ments from their source through all methods, has been proven to be in-
Tools that automate the process of stat- of the development phases and valuable for ensuring that the veri-
ic analysis and enforcement of coding down to the verification activities fication test cases execute all of the
standards such as CWE or CERT C Se- and artifacts ensures the highest code under development. This
cure Coding guidelines ensure that a quality, secure software. helps ensure that there are no hid-
higher percentage of errors are identi-
fied in less time. This rigor is compli-
• Unit testing—the most effective
and cheapest way of ensuring that
den vulnerabilities or defects in the
code under development.
mented by additional tools for: the code under development meets
its security requirements is via unit While these various capabilities can
• Requirements traceability—a good
requirements traceability tool is in-
testing. Creating and maintaining
the test cases required for this,
be pieced together from a number of
suppliers, some companies offer an in-
valuable to the build security in however, can be an onerous task. tegrated tool suite that facilitates the
process. Being able to trace require- Unit testing tools that assist in the building security in process, providing

LDRA TBvision screenshot showing improper data type sign usage resulting in buffer overflow vulnerability.

Figure 2

www.embedded.com | embedded systems design | MAY 2010 21


Secure coding in the iterative lifecycle.
Requirements
traceability

Requirements Analysis and design


Initial Secure codes standards
Planning enforcement, quality, and testability

Planning Implementation

Automated
testing unit
Configuration
and change
management

Test and metrics


reporting

Evaluation Testing

Deployment

Test completeness
verification
Figure 3

all of the solutions


described above.

BUILDING
! It’s not surprising that the processes for
building security into software echoes the
SECURITY
It’s not surprising
that the processes
for building secu-
! high-level processes required for building
quality into software.
rity into software
echoes the high-level processes required CERT-C Secure Coding Guidelines and
for building quality into software. CWE dictionary, static analysis tools
Adding security considerations into the help make this objective both practical
process from the requirements phase and cost effective. Combine this with
onwards is the best way of ensuring the the improved productivity and accura-
development of secure code, as de- cy of requirements traceability, unit
scribed in Figure 3. High-quality code testing and dynamic analysis and the
is not necessarily secure code, but se- elimination of exploitable software
cure code is always high-quality code. weaknesses become inevitable. ■
An increased dependence on inter-
net connectivity is driving the demand
for more secure software. With the Nat Hillary is a field applications engi-
neer with LDRA Technologies, Inc., a po-
bulk of vulnerabilities being attributa- sition that he comes to via an extensive
ble to coding errors, reducing or elimi- background in software engineering,
nating exploitable software security sales and marketing. He is an experi-
weaknesses in new products through enced presenter in the use of software
analysis solutions for real-time safety crit-
the adoption of secure development ical software who has been invited to
practices should be achievable within participate in a number of international
our lifetime. forums and seminars on the topic.
By leveraging the knowledge and
experience encapsulated within the

22 MAY 2010 | embedded systems design | www.embedded.com


feature

Prototyping an ASIC design first on an FPGA is not only useful for verification but allows
more room for algorithm experimentation.

How to use an FPGA


to test a PLL band
calibration algorithm BY RUSSELL MOHN

I
t’s a common technique to split the required frequency tuning
range of a controlled oscillator into discrete bands. The advantage
of having many bands is that a wide tuning range can be covered
while keeping a relatively low voltage-controlled oscillator (VCO)
gain within each band. Low VCO gain is good for achieving low
VCO phase noise. It’s required that the frequency bands overlap.
The tuning bands are changed with a digital band control signal.

When an oscillator with discrete ing the PLL to lock.


tuning bands is used in a phase-locked A straightforward way to calibrate
loop (PLL), the desired band must be the band is by racing two counters, one
selected before the PLL can proceed to clocked with the reference clock and
phase lock. This necessary step has the other clocked with the feedback
many names (band calibration, auto- clock that is the frequency divided ver-
band selection, band selection, and so sion of the VCO output. The frequency
on), but the idea is the same: to pick division occurs in a block called a mul-
the right frequency band before allow- ti-modulus divider (MMD).

www.embedded.com | embedded systems design | MAY 2010 23


feature
The counters are forced to start at local oscillator input to a mixer that function and gives a fractional resolu-
the same time and permitted to count downconverts the received radio fre- tion of REF/2^(# sigma-delta accumu-
up to a predetermined value. Whichev- quency (RF) signal to an intermediate lator bits).
er counter gets to the value first is not- frequency. Channel selection is Frequency synthesizers multiply a
ed as the winner; it follows that that achieved by setting the synthesizer’s fixed frequency crystal oscillator up to
clock was greater in frequency. constant of proportionality. In general, the required frequency. The PLL acts as
Using the information about which RF = Ndiv * REF, where RF is the out- a closed-loop negative feedback system
counter was the winner, the band con- put frequency, Ndiv is the constant of to implement this exact multiplication.
trol of the VCO can be either incre- proportionality, and REF is the refer- The job of the MMD is to divide the
mented or decremented to bring the ence frequency. frequency of the VCO output by the in-
frequencies closer. This algorithm is Ndiv can be a ratio of integers, N/R, teger value N.
implemented in a band calibration where N is an integer divide value for The phase of this signal is com-
block (BCAL). Instead of waiting for an pared with the phase of the reference,
expensive ASIC fabrication run that in- and the difference in phases is filtered
cludes the entire PLL and other circuits,
you can implement a band calibration
algorithm and test it on an FPGA. This
! A large VCO gain would
make the PLL susceptible
to remove high-frequency components.
The filtered signal is used as the voltage
control of the VCO. If there is any
article shows you how.

VCO BAND CALIBRATION (BCAL) ! to high phase noise. For


these reasons, the tuning
phase difference between the output of
the MMD and the reference, the con-
trol voltage at the VCO will adjust to

!
In communications chips, frequency range is split up into dis- correct that phase difference.
synthesizers are ubiquitous functional For the application at hand, the
blocks. A frequency synthesizer is loosely crete bands. synthesizer needed to create frequencies
defined as a PLL that generates an out- from 3,000 to 4,000 MHz. Continuous
put frequency that’s directly proportion- tuning of the VCO is accomplished by
al to a reference frequency. The constant the output of the VCO, and R is anoth- changing the bias voltage across a var-
of proportionality is a specific subset of er integer divide ratio for dividing the actor which is part of the parallel in-
integer or real numbers, depending on reference oscillator. If even finer fre- ductor-capacitor (LC) resonant circuit.
the synthesizer implementation. quency resolution is needed, the N val- The fabrication technology limits the
One use for a synthesizer in a re- ue can be added to a sigma-delta mod- control voltage to a maximum change
ceiver front-end is the creation of the ulated code that dithers the divider of about 1.5 V. It’s difficult to build a
varactor that will change its reactance
The band calibration testbench implemented on the FPGA is analogous enough to cause a frequency change of
to band calibration used in a frequency synthesizer on an ASIC. 1,000 MHz with only a control voltage
change of 1.5 V.
Furthermore, a large VCO gain of
BCAL Ndiv 1,000 MHz/1.5 V would make the PLL
8b
susceptible to high phase noise. For
VCO
these reasons, the tuning range is split
PFD Filter MMD
REF
VC
RF up into discrete bands. The discrete
xtal
Disabled bands are implemented by adding bina-
ry-weighted capacitors to the parallel
LC tank circuit. They are switched on
or off depending on the digital band
setting. The band must be set before the
FPGA band-calibration testbench
PLL can be allowed to lock and track in
7-segment a continuous manner.
display
The BCAL circuit operates as a sec-
ond feedback loop controlling the VCO
REF BCAL NCO
signal source
8b Proto pin for through its band input. During band
viewing on scope
calibration, the VCO control voltage is
Push-button reset fixed at a convenient voltage, usually
the mid-point of its allowable control
Figure 1

24 MAY 2010 | embedded systems design | www.embedded.com


feature
voltage range. The phase-detector is making the model accurately reflect the was deemed acceptable to use in the
also disabled during band calibration. implementation in RTL. The RTL code closed-loop test setup for the BCAL.
My goal was to design and test the was written in verilog and run on Al- After establishing that the NCO has
band calibration algorithm before inte- tera’s Stratix II DSP Development Kit. a monotonic tuning curve and can pro-
grating it with the PLL on an RF receiv- From within Altera’s Quartus II duce frequencies in the range 10 to
er ASIC. To that end, a system analo- software all-things-FPGA could be ac- 14 MHz, which is approximately the
gous to the PLL when it’s being complished: design entry, simulation for PLL’s reference frequency, I built the
band-calibrated was constructed entire- functionality, simulation for timing, syn- BCAL model. The BCAL algorithm
ly with circuits that could be imple- thesis, fitting, configuring the FPGA works by racing two identical 10-bit
mented on an FPGA. Since the VCO with the design, and debugging. When I counters. One counter is clocked by the
and MMD lumped together act as a tested the band-calibration in real time, I reference; the NCO clocks the other.
programmable oscillator with output used the signal source and oscilloscope. Since they both start from 0, the
frequencies around the reference fre- first counter to get to a constant
quency, their functionality can be mod- HIT_VALUE, is clocked by the greater
eled by a numerically-controlled oscil-
lator (NCO), shown in Figure 1.
For the synthesizer to have low ! The binary search block
holds the current band
frequency. To determine which count-
er gets to HIT_VALUE first, each
count value is continuously compared

!
phase noise, a crystal generates the fre- with the HIT_VALUE, and the XOR of
quency reference. The reference fre- output value and deter- the two comparison results is used to
quency is typically in the tens of MHz, mines what the next band clock a “1” into a D flip-flop.
which is well below the maximum When both count values are less
speed of the logic that can be imple-
mented on today’s FPGAs. The BCAL
algorithm itself can be described and
designed with digital techniques.
! value will be based on
which clock won the race.
than HIT_VALUE, the comparators
both output 0, and the XOR result is 0.
At the instant one of the values ex-
ceeds the HIT_VALUE, the XOR out-
At its simplest, its inputs are two put transitions to 1 and captures a 1
clocks, the reference and the output of DESIGN AND PROTOTYPING on the DFF output. Sometime there-
the NCO; its output is the band signal PROCEDURE after, the other count value will get to
for the NCO. The combination of the The design and prototyping procedure HIT_VALUE, and the XOR result re-
band calibration, NCO, and an external- is the iteration of the following familiar turns to 0.
ly applied reference signal forms a steps: 1. Design Entry; 2. Test; 3. Debug; Another comparator is used to
closed loop system with negative feed- 4. Go To 2. This cycle is repeated as compare the reference counter to a
back that is analogous to the PLL oper- many times as necessary until the de- constant RESET_VALUE, and when
ating during its band calibration mode, sired functionality is reached. the count exceeds this value, both
all of which can be coded in RTL and First, I built the NCO as a Simulink counters are reset to 0 and the race be-
tested on an FPGA before spending subsystem. The NCO Simulink model gins over again. If the HIT_VALUE is
money on an ASIC fabrication. was reverse-engineered from the verilog 230, a plausible RESET_VALUE is 240.
for an NCO I found on the web at Meanwhile, the bit of information
WHAT YOU NEED www.mindspring.com/~tcoonan/nco.v. about which clock was faster is used as
1. An FPGA and its programming The NCO was based on a programma- input to a binary search block.
software ble modulo counter. Its output frequen- The binary search block holds the
2. Matlab/Simulink for algorithm de- cy equals Fs*(BAND+STEP)/MOD current band output value and deter-
velopment and verification where STEP and MOD are fixed values mines what the next band value will be
3. A signal source for generating the and BAND is the 8-bit band signal. based on which clock won the race.
reference clock, such as 10 to 15 The NCO’s functionality was veri- The binary search block either adds or
MHz fied by running transient simulations subtracts the appropriate binary
4. An oscilloscope for debugging using Fs=11MHz and sweeping weighted value from its current out-
through the BAND values, 0 to 255, put. For an 8-bit band, the initial band
I used Matlab/Simulink to enter the and calculating the resulting output value is mid-range at 128, and seven
initial design and testbench. The sup- frequency. The resulting output fre- consecutive races are conducted to fill
port for fixed-point numbers that quency versus BAND, or band tuning in the 8-bits from MSB to LSB. An ex-
comes with the Fixed-Point Toolbox curve, was monotonic but not perfect- ample run of the BCAL algorithm is
and Simulink Fixed Point is useful for ly linear. Since it was monotonic, it shown in Figure 2.

www.embedded.com | embedded systems design | MAY 2010 25


feature
In a manner similar to the erence clock, the design functionality

! The BCAL algorithm finishes


in 146 µs so only the final
testing done in Simulink, all the
submodules were simulated and
verified in Quartus II. After
was okay in simulation. The next step
was to load the design onto the FPGA
and verify through measurement.

! value appears to a human


observer. The BCAL algorithm
functionality was confirmed for
the submodules, a test schematic
for the entire BCAL was made.
The testing proceeded by changing
the reference frequency generated by
the signal source from 10 to 14 MHz in

!
The test schematic includes the increments of approximately 100 kHz.
was pass/fail tested for 50 NCO which is controlled by the The test setup is shown in Figure 3. At
possible frequencies. BCAL band output. each reference frequency, the band cali-
To complete the loop, the bration was initiated by a reset tied to a
NCO output is used as one of push-button. Switch debouncing would
After building the band calibration the clock inputs to the BCAL. The BCAL have made a cleaner testbench but was
algorithm in Simulink from logic gates, reference input was wired through one not necessary.
comparators, registers, delays, and of the FPGA pins to an SMA connector Multiple resets caused by the switch
look-up tables, the design was entered on the board so it could be clocked with bounce cause the algorithm to start
in the Quartus II software. To make de- an external signal source. over repeatedly; when the switch stops
bugging easier, every wire in the The BCAL testbench was synthe- bouncing, the BCAL operates normally.
Simulink model was named. sized and fitted, and the timing netlist The 8-bit band value was mapped to
During the translation process, I was simulated. Immediately, it was ap- two 7-segment displays on the FPGA
used the same names for signals in the parent there was a bug in the design be- board to display the final band value in
Verilog code. If a signal originated cause some of the band bits were going hexadecimal.
from a register (or a delay in a trig- into undefined states, shown as “U” in The BCAL algorithm finishes in
gered subsystem) in the Simulink Quartus II. 146 µs (= 7*230/11 MHz), so only the
model, I made it a register in Verilog; The bug came from the asynchro- final value appears to a human observ-
otherwise the signal was a wire. As a nous comparisons of the counter values er. The readout made it easy to compare
result, the design entry from Simulink to the HIT_VALUE. After registering against the theoretical value from the
primitive subsystems to Verilog was these comparison results and retiming Simulink model. In this way, the BCAL
straightforward. the asynchronous data paths to the ref- algorithm was pass/fail tested for 50
possible frequencies from its minimum
to maximum band values.
An example band calibration run with REF = 14.3MHz; the band
settles to 227. POTENTIAL PITFALLS AND TIPS
260
One of the challenges of this particular
design was its asynchronous nature.
BCAL The frequency of the NCO clock
240
changes during the band calibration,
Target and some logic elements in the BCAL
220 depend on the timing of the edges of
that clock. Likewise, other logic ele-
ments change synchronously to the ref-
200
erence clock edges.
Band [LSB]

The FPGA design software is not


180 conducive to asynchronous design. It’s
not impossible to make an asynchro-
nous design, but don’t be surprised if
160
you have to look through documenta-
tion on a collection of warnings to de-
140 termine if your code does what you in-
tend. Since the reference frequency
never changes, the design was modified
120
0 50 100 150 to make all the data paths synchronous
Time [µS] to the reference clock.
Figure 2

26 MAY 2010 | embedded systems design | www.embedded.com


feature
When the data path needed to jump clock domains, it The functionality checked out okay in those simulations.
was retimed with cascaded registers to minimize metastabili- Since then, the RF receiver ASIC that includes the frequency
ty. Similarly, another pitfall was not registering combinatorial synthesizer was fabricated and measurements of the chip
comparator outputs. These are both examples of problems show the frequency synthesizer phase locks over its range of
that arise in actual hardware but may not show up in the ide- possible output frequencies. This implies that the band cali-
alized models in Simulink, unless you explicitly add them in bration functions correctly. As a result, the design team can
your model. focus on squeezing better performance out of the analog por-
To ease the migration of the Simulink model to RTL, try tions of the ASIC.
to use Simulink function blocks that are primitives in the The process of prototyping a design on an FPGA before
RTL language of your choice. For example, logic functions committing it to an ASIC is useful not only verification pur-
such as XOR, AND, and greater-than map directly from poses but also for the possibilities it provides for algorithm
Simulink to Verilog. A delay or explicit DFF in Simulink is experimentation. If the context of the algorithm can be repli-
modeled as a register in Verilog. cated on the FPGA as it will appear on the ASIC, any number
I also recommend naming all the signals in the Simulink of algorithm implementations may be tried and compared in
model and using the same names in the Verilog code. It’s terms of area efficiency, current consumption, or speed. Hap-
okay to first build the model using floating-point data types py prototyping! ■
in Simulink, but if you migrate the floating-point design to
fixed-point, it will ease the coding process and lead to a de- Russell Mohn is a senior design engineer at Epoch Microelec-
sign that is easier to debug. tronics, an IC design services company specializing in mixed-
signal, analog, and RF design. At Epoch, his focus has been
THE END RESULT on the design of fractional-N frequency synthesizers for com-
munications applications. In 2001, he received his B.E. in EE
After running the RTL code on the FPGA and judging that from Cooper Union. His interests include FPGA prototyping,
the design is functional and meets specifications based on system modeling, and signal processing.
measured data, it was time to implement the code on an
ASIC. The logic synthesis and layout was done with Ca-
dence’s Encounter software. As a final check, I simulated the
resulting logic netlist and also the extracted layout netlist
with parasitic resistors and capacitors to make sure the func-
tionality was still okay after Encounter’s synthesis and place-
and-route.

Lab setup for band calibration running on the


FPGA showing that measured band value
matches the simulation. Now, the RTL code can
be implemented on the ASIC with confidence
it will function correctly.

REF
frequency [MHz]

NCO output
~14.3 MHz
REF input
to FPGA

band value (hex)


hE3 = d227
Stratix II
FPGA

Figure 3

www.embedded.com | embedded systems design | MAY 2010 27


Join EE Times Group to learn how distributors
stack up in today’s market

Live Webinar
Registration information
2010 Distributor Brand Preference Study ■ Register by 4/30/10: $250.00
(USD)
OEMs rank distributors based on how well they help them achieve their
■ Register between 5/1/10 and
operating goals and today, more than ever, it’s crucial for distributor partners 5/14/10: $299.00 (USD)
to understand how they stack up in the face of their vendor partners and end
The registration fee is payable by
customers, how they are measured and where they rate compared to their
American Express, Mastercard,
competitors in order to strengthen revenues and plan for a strong year ahead. or Visa. All paid registrants will
Tune in on May 14 as EE Times Group unveils the 2010 Distributor Brand be given a confirmation number
Preference Study, our annual benchmark research on the $40 billion+ and a url which will enable them
distribution market where design engineers, technical managers, supply to view the study, at their leisure,
chain management, purchasing and corporate managers across the OEM from May 14 to December 31, 2010.
market have weighed in on:
Please contact EE Times’
■ Which distributors are preferred and what criteria matters the most Webinar Support with
such as ease of doing business, customer service, pricing and website any questions at
capabilities. [email protected]
■ How distributor brand preference varies across product categories such
as semiconductors, connectors & interconnects, passive components
and electromechanical devices
Presenter:
■ What factors influence purchasing decisions from the same distributor
Presented by EE Times, this landmark research is a key measurement Jim McLeod-Warrick
tool for OEM’s, CEM’s, distributors and suppliers. If you are a distributor, an Founding Partner of Beacon
OEM or a decision maker in the purchase process of electronic components Technology Partners LLC
you need to attend this webinar.

Register today: http://tinyurl.com/514-eet-study


feature

Here’s a novel approach to the “update tool or update source” dilemma.

Dealing with
misbehaving tools
BY ANDERS HOLMBERG

M aking software changes very late in a project is almost never a


good thing. Although correction of the error might be crucial for
the correct and safe usage of the end product, it has a number
of unwanted side effects:

• The process view: Making changes to


the code and rebuilding the applica-
tion image will force a restart of one
or more test and quality assurance
(QA) activities in the project. Mini-
in the process you have to go to re-
visit certain activities. In the worst
case, a full external revalidation or
recertification assessment may be
required.
mizing test and QA without com- • The code view: Changing code to
promising safety and integrity in the correct erratic behavior always car-
face of code changes can thus be- ries the risk of introducing new un-
come critical for time to market. wanted behavior. This sometimes
The later in the process a prob- leads to the decision to leave a prob-
lem is encountered the further back lem as is in the product and docu-

www.embedded.com | embedded systems design | MAY 2010 29


feature
ment clearly the impact of the code
behavior. High-integrity regulatory
frameworks often make things even ! It’s not always possible
to avoid code changes,
base with all the implications for the
project outlined above.
For high integrity projects the build

!
tougher by requiring extensive im- chain and the vendor should be subject
pact analysis of the changes prior to
but methods and tools to a lot of scrutiny before selection. And
performing them. to avoid or minimize the the typical scenario is that once a partic-
• The goodwill view: Frequent or ular compiler and version is selected,
large code changes in the final
stages of a project can make stake-
holders nervous about the end
product. If the product has already
! impact of changes can
be extremely helpful.
you stay with it throughout the project.
Some high-integrity process frameworks
even require the tools selection to be
subject to a formalized process where
reached the market, the situation in the future. However, as this kind the tools are prequalified or validated ac-
can be a real nightmare. of latent bug is mainly a process cording to certain criteria.
and knowledge issue, it will not be We will now take a look at a special
So, it’s not always possible to avoid discussed further here. technique that can be used if you have a
code changes, but methods and tools to
avoid or minimize the impact of
• This leaves us with the main focus
for this article, the object-code-gen-
close relationship with your compiler
vendor. Consider a compiler for a 32-bit
changes can be extremely helpful. eration-tool bug. We will restrict architecture. Many 32-bit CPU kernels
Three broad categories cause most the discussion to bugs in the build incorporate some kind of instruction
of the late code changes: chain, in other words, the compiler, pipeline to increase performance by di-
assembler, and linker. viding complex instructions into 1-cycle
• The source-code bug: This kind of
error is either due to mistakes or Consider the following situation. A
pieces that are executed in their own
pipeline stage.
misunderstandings by the pro- bug you have found is the result of the In this way a throughput of one in-
grammer in the implementation or compiler making wrong assumptions struction per clock cycle can be
an ambiguous or incomplete func- about register allocation and stack allo- achieved under ideal circumstances. It is
tional specification that leaves too cation of variables that are local to a however very easy to break this if subse-
much open to interpretation. Al- function. The bug is exposed when quent instructions are competing for
though this is a common occur- many variables compete for the avail- the same resource. An example is if the
rence, I won’t be discussing it in able CPU registers and some variables first instruction writes to a particular
this article. have to be temporarily moved to the register and the directly following in-
• The latent non-ANSI C/C++ source
bug: The ANSI C standard has
stack. You have found the bug in a large
function with a lot of arithmetic com-
struction reads from the same register.
On many pipelined architectures, this
some dark corners where behavior putations, but that is no guarantee that will cause a so called pipeline stall that
is either implementation defined or the bug will only manifest itself in large means that one-cycle processing is in-
undefined. If you’ve implemented functions with a lot of computations. terrupted while the second instruction
parts of the source code to depend So we end up with the question of waits for the first instruction to finish
on how a particular compiler be- whether to persuade the compiler ven- writing to the register.
haves for these corner cases of the dor to supply a fix or applying the A good compiler for such a CPU ar-
standard, you can expect a problem workaround(s) throughout the code chitecture will try to rearrange or sched-

Listing 1 Listing 2
Bool AreIndependent(Instr inst1, Instr inst2) void ChangeMOVOrder(Instr inst1, Instr inst2)
{ {
if (IndependentSourceAndDest(Inst1, Inst2)) // Do other processing first
{ …
return true; if (AreIndependent(inst1, inst2))
} {
else ChangeOrderHelper(inst1, inst2);
{ }
return false; }
}
}

30 MAY 2010 | embedded systems design | www.embedded.com


feature
ule instructions so as to maximize the
distance between instructions that use Listing 3
the same CPU resource in a pipeline
blocking way. void ChangeMOVOrder(Instr inst1, Instr inst2)
{
To do such rearranging, the compiler // Do other processing first
must build up one or more dependency …
graphs for the block of instructions it’s // Bug detection code
if (IsVolatile(inst1) || IsVolatile(inst2)
about to schedule to determine if it is safe {
to move an instruction backward or for- ReportSourceStatement(inst1);
ward in the instruction stream. The com- ReportSourceStatement(inst2);
return;
piler uses a set of functions to determine }
if two instructions are independent which if (AreIndependent(inst1, inst2))
means that they do not use resources in {
ChangeOrderHelper(inst1, inst2);
a conflicting way and thus implicates }
that their order can be exchanged. }
Let’s take a look at a function that
the compiler might use to determine if
two MOV instructions are independent, As noted, the scheduler can of This function can be changed to de-
shown in Listing 1. course choose to leave two independent tect the bug case, in other words, when
This function looks innocent instructions in place. For this customer, the ChangeMOVOrder() function uses
enough. It basically shifts the question it’s easy to see that he has at least one lo- the wrong information to make a deci-
of independence to a helper function cation that is affected by this bug, but sion. The added code in red in Listing 3
that determines if the source and desti- looks for the offending situation and
nation of the MOV instructions are when such a situation arise it reports
used independently.
It’s perfectly OK for the compiler to
leave the instructions together in the
! One remedy: a special
version of the original
the affected source locations. Note how
the code in red would also cure the bug
because it classifies all MOV instruc-
same order. To get the puzzle together
with maximum performance as a result,
it might for example sometimes just cre- ! compiler can try to
identify all code in the
tions with the volatile attribute as de-
pendent. But it is crucial to understand
that we could not have placed the detec-

!
ate a new pipeline stall by moving two tor code in the buggy function! If we
instructions to avoid another stall.
user’s code base that is would have done so, it would report
Let’s return to the function in Listing affected by the bug. every occurrence of possibly erroneous
1 and the compiler that uses this func- MOV instructions.
tion. When a customer compiles a cer- Even this simplified example showed
tain program with this compiler, it works does he have more affected locations? us one of the pitfalls in creating a pro-
flawlessly, except that he notes that two Finding that out effectively amounts to duction quality bug detector. It can be
memory writes are done in the wrong or- going through the complete code base simple to isolate the root cause of the
der as opposed to how they are specified looking for accesses to volatile variables bug but complicated to determine when
in the program. Usually this is the princi- and examining the generated code; so this bug will actually result in the gener-
ple that the scheduler is dependent on to we’re back to the central theme of this ation of wrong code. We could for exam-
perform its magic, but in this case it’s not article—how can the customer’s change ple have a number of different functions
OK because the user has specified that management be simplified? of varying complexity that depend on
both variables that are affected by the Here is one possible remedy to the the AreIndependent() function.
MOV instructions are declared as situation: a special version of the origi- But if it’s practically possible to create
volatile, which has implies that the or- nal compiler can try to identify all code the bug detector, it can now be used to
der of the writes should not change. If, in the user’s code base that is actually af- pinpoint the exact locations of any other
for example, the memory writes are in- fected by the bug. code that is affected by the original bug.
tended to initialize some external hard- Here is how the compiler can be In this way, we can avoid going through
ware, this can be extremely important. turned into a bug detector. The function all object code by hand to look for possi-
The AreIndependent() function in Listing 1 is used in another function ble occurrences of the problem. ■
ignores the volatile attribute of both in- (Listing 2) that changes the order of two
structions and thus reports that it’s OK instructions when that function has de- Anders Holmberg is software tools prod-
to rearrange these instructions. cided that it is beneficial to do so. uct manager at IAR Systems.

www.embedded.com | embedded systems design | MAY 2010 31


EMBEDDED SYSTEMS MARKETPLACE

Thermocouples, Make Your Own


The Hot Spot Welder is a
portable capacitive discharge
wire welding unit that allows
thermocouple wire to be formed
into free-standing bead or butt
welded junctions, or to be
directly welded to metal
surfaces. The HOT SPOT provides a quick, simple,
accurate, low cost means of fabricating thermocouples
on a “when needed, where needed” basis. Brochure and
specification sheet provide photos and descriptions of
thermocouple construction and use.

DCC Corp.
7300 N. Crescent Blvd., Pennsauken NJ 08110
PH: 856-662-7272 • Fax: 856-662-7862
Web: www.dccCorporation.com

My experience in embedded software


ADVERTISING SALES
parity bit supports every word Mr. Grenning said.
MEDIA KIT:
www.embedded.com/mediakit
from page 7
First, in my 30 years in the field I
a moment, you will realize that the tool remember only one brand-new first- EMBEDDED SYSTEMS DESIGN

is telling you: “why are you using a release program that was a total mess, Sales Contacts
600 Harrison St., 5th Flr,
signed int to store a diameter for? It and I’m sure that was deliberate ob-
San Francisco, CA 94107
doesn’t make sense.” You will then no fuscation. Most developers seem to be
doubt start digging in that code piece, able to divide a program into reason- David Blaza
Publisher
finding numerous other bugs. able modules and implement these (415) 947-6929
So I daresay that any form of test modules intelligently, no matter the [email protected]
would have found that bug in a few process they follow. Bob Dumas
minutes, if it involved a good compiler It is enhancements that destroy Associate Publisher
or static analyzer. As I see it, the bug the programs. This was true when (516) 562-5742
[email protected]
was likely caused by any combination of new breath types were added to a
the following: medical ventilator, new measure- Advertising Coordination and
ments to optical inspection systems, Production
• A poor requirements specification.
Did the specification state how
or new protocols to telemetry sys-
tems. These changes are almost always
600 Community Drive,
Manhasset, NY 11030
Donna Ambrosino
thick logs that were allowed? If it made under time pressure and use as Production Director
did, was the product tested against much existing code as possible. The (516) 562-5115
that requirment? result is usually that pretty decent [email protected]

• Poor test tools or no test tools at all. modules grow to be untestable and
• Insufficient knowledge in embed-
ded programming. A qualified
unmaintainable. I have had to take
over far too much such legacy sys-
developed whatever the official process
may be.
guess is that the program was writ- tems, and it’s very hard to convince —The Heretic
ten by an unskilled programmer managers that it’s costing them more Software Department
who was using the default “int” than it’s worth. If TDD can stop this
type—a deadly sin in any embed- code rot and force needed refactoring, Editor’s note: James Grenning responds
ded programming. But in that case I hope every organization whose code at www.embedded.com/224200702.
the real culprit was poor coding I ever have to maintain will adopt it.
standards at the company, or no P.S. Kent Beck may have taken the, We welcome your feedback. Letters to the
coding standards at all. write a little code, test it, and extend it, editor may be edited. Send your comments to
method past any reasonable point, but Richard Nass at [email protected] or fill
—Lundin
out one of our feedback forms online, under
R&D Manager that is how real working programs are the article you wish to discuss.

32 MAY 2010 | embedded systems design | www.embedded.com


By Jack G. Ganssle
break points
An interview with James Grenning, Part 2
J ames Grenning (www.renaissance-
software.net), whose book Test Driv-
en Development in C will be out in
the fall, graciously agreed to be inter-
viewed about TDD (test driven devel-
should have very high code coverage,
along with meaningful checks that con-
firm the code is behaving correctly.
Some practitioners do a periodic review
of code coverage, looking for code that
opment). The first part of our talk ran slipped through the TDD process. I’ve
last month at www.embedded.com/ found this to be useful, especially when
224200702, where you can also see a team is learning TDD.
reader comments. There has been some research on
Jack: How do you know if your TDD’s impact on cyclomatic complexi-
testing is adequate? TDD people— ty. TDD’s emphasis on testability, mod-
heck, practically everyone in this indus- ularity, and readability leads to shorter
try—don’t seem to use MC/DC, npath, functions. Generally, code produced
or cyclomatic complexity to prove they with TDD shows reduced cyclomatic
have run at least the minimum number complexity. If you Google for “TDD cy-

!
of tests required to ensure the system clomatic complexity,” you can find arti-
has been adequately verified.
Is test driven development cles supporting this conclusion.
James: You are right; TDD practi- viable for embedded sys- Jack: Who tests the tests?
tioners do not generally measure these James: In part, the production code
things. There is nothing said in TDD
about these metrics. It certainly does
not prohibit them. You know, we have ! tems? It may be part of
the answer. Ganssle con-
tests the test code. Bob Martin wrote a
blog a few years ago describing how
TDD is like double entry accounting.
not really defined TDD yet, so here
goes. This is the TDD micro cycle:

• Write a small test for code behavior


that does not exist
! tinues to grill James
Grenning on TDD.
One reason these metrics are not
Every entry is a debit and a credit. Ac-
counts have to end up balanced or
something is wrong. If there is a test
failure, it could be due to a mistake in
the test or the production code. Copy
• Watch the test fail, maybe not even
compile
the focus is that there are some prob-
lems with them. It is possible to get a
and paste of test cases is the biggest
source of wrong test cases that I have
• Write the code to make the test
pass
lot of code coverage and not know if
your code operates properly. Imagine a
seen. But it’s not a big deal because the
feedback is just seconds after the mis-
• Refactor any messes made in the
process of getting the code to pass
test case that executes fully some hunk
of code but never checks the direct or
take, making it easy to find.
Also the second step in the TDD
• Continue until you run out of test
cases
indirect outputs of the highly covered
code. Sure it was all executed, but did it
micro cycle helps get a test case right in
the first place. In that step, we watch the
behave correctly? The metrics won’t tell new test case fail prior to implementing
Maybe you can see that TDD you. the new behavior. Only after seeing that
would do very well with these metrics. Even though code coverage is not the test case can detect the wrong re-
Coverage will be very high, measured the goal of TDD it can be complemen- sult, do we make the code behave as
by line or path coverage. tary. New code developed with TDD specified by the test case. So, at first a
wrong implementation tests the test
case. After that, the production code
Jack G. Ganssle is a lecturer and consultant on embedded
development issues. He conducts seminars on embedded systems tests the test case.
and helps companies with their embedded challenges. Another safeguard is to have others
Contact him at [email protected]. look at the tests. That could be through
pair programming or test reviews. Ac-
tually, on some teams we’ve decided

www.embedded.com | embedded systems design | MAY 2010 33


that doing test reviews is more impor- the faulty function did not correctly tem test. If you have automated some of
tant than reviewing production code. identify the whole problem. I was in the these tests, and you rely on using the real
The tests are a great place to review in- group that got it almost right; a.k.a. clock, tests could take a long time to run.
terface and behavior, two critical aspects wrong. Then I wrote a test. The test can- But that may not be a problem, because
of design. not be fooled as easy a human. So, I the cadence of acceptance and systems
Jack: As has been observed, all test- think we need both, inspections and tests does not need to be as fast as unit
ing can do is prove the presence of bugs, tests. tests. We’d like to run these longer tests
not the absence. A lot of smart people Jack: Some systems are complex or automatically as part of a continuous in-
believe we must think in terms of quality control processes that respond slowly. tegration system.
gates: multiple independent activities What happens when it takes hours to Jack: Let’s move on to my business
that each filter defects. So that includes run the tests? concerns. Through incremental delivery,
requirements analysis, design reviews, James: For TDD to be a productive TDD promises to produce a product
inspections, tests, and even formal verifi- way to work, the micro cycle has to be that closely aligns with the customer’s
cation. Is this orthogonal to TDD ap- very short in duration. This pretty much needs. That is, at each small release the
proaches, and how do TDD practition- rules out going to the target during the customer can verify that he’s happy with
ers use various quality gates? micro cycle, and also that unit test exe- the feature, and presumably can ask for a
James: TDD does not try to prove change if he’s not. “Customer” might re-
the presence of bugs; it is a defect pre- fer to an end-user, your boss, the sales
vention technique (www.renaissancesoft-
ware.net/blog/archives/16). People make
mistakes regularly during development,
! If there is a lengthy con-
trol process being test
department, or any other stakeholder. If
there’s no barrier to changes, how does
one manage or even estimate the cost of
but in the TDD micro cycle, the mis-
takes are immediately brought to the de-
veloper’s attention. The mistake is not ! driven, we need to take
control of the clock. If we
a project?
James: This is more of an Agile re-
quirements management issue than

!
around long enough to ever make it into TDD, but that’s OK. Let me start by say-
a bug-tracking system.
are managing dependen- ing that it is a misconception that there
I think TDD is only part of the an- cies, this is not hard. is no barrier to requirements changes,
swer. Reviews, inspections, and pair pro- and feature creep. For successful out-
gramming are orthogonal and comple- come, requirements have to be carefully
mentary to TDD. cution must also be kept short. managed.
There is another form of TDD, a To avoid the target bottleneck, I rec- In Agile projects there is usually a
more requirements-centric activity called ommend that TDD practitioners first single person that is responsible for driv-
Acceptance Test Driven Development run their unit tests in their development ing the development to a successful de-
(ATDD). In ATDD, the customer repre- system. If you are practicing the SOLID livery. Some refer to this as the customer
sentative defines tests that describe the design principles it is natural to manage or the product owner (PO). The product
features of the system. Each iteration, the the dependencies on the hardware and owner might be from marketing, prod-
team works to complete specific stories operating system. uct management, or systems engineer-
defined by the customer. A story is like a If there is a lengthy control process ing. She usually heads a team of skilled
use case, or a specific usage scenario. The being test driven, we need to take control people who know the product domain,
acceptance tests describe the definition of the clock. If we are managing depend- the market, the technology, and testing.
of done for the story. These acceptance encies, this is not hard. A time-driven She is responsible for making trade-offs.
tests are also automated. If the new and event eventually resolves to a function Team members advise her, of course.
all prior tests pass, the story is done. call. The test fixture can call the event To manage development, we create
That is an important a quality gate. processing code as well as some operat- and maintain something called the
Don’t get me wrong, I am a proponent ing system, or interrupt-based event product backlog. The backlog is the list
of reviews, but I think that TDD is supe- handler. If your code needs to ask some of all the features (we can think of) that
rior to inspections at preventing defects. time service what the current millisec- should go into the product. There is a
I did a case study on the Zune bug ond is, we can intercept those calls and strong preference to make the work visi-
that illustrates my point. This bug mimic any time-based scenario we like ble to the PO, over work that only engi-
caused the 30G Zune model to freeze on without any of the real delays slowing neers understand. It is mostly feature
New Year’s Eve 2008. My informal re- the test execution time. oriented, not engineering-task oriented,
search on the bug (www.renaissancesoft- With that said about unit tests, you focusing on value delivery. We prevent
ware.net/blog/archives/38) showed that might have the same issue when it comes surprises by taking three month engi-
most online code pundits who inspected to a more thorough integration, or sys- neering deliverables and splitting them

www.embedded.com | embedded systems design | MAY 2010 35


break points

! TDD is just part of the picture.


The team activities should

! encompass cross-functional
needs. While the product is

! evolving, the team’s progress


is an open book.

orous and fact-based schedule that most


developers are used to working with.
The Agile approach can be used to man-
into a series of demonstratable bits of points per iteration. The initial estimate age to a specific date, or to specific fea-
work that our customer cares about. for the project would be the total of all ture content.
The product owner’s team can add story points divided by the estimated ve- TDD is just part of the picture. The
things to the backlog, but in the end, the locity. This will probably tell us that team activities should encompass cross-
authority of what goes into a specific it- there is no way to make the delivery functional needs. While the product is
eration is the PO’s responsibility. For date. But it’s just an estimate, next we’ll evolving, the team’s progress is an open
highly technical stories, a hardware engi- measure. book. The user documentation, market-
neer might play the role of the customer. As we complete an iteration, we cal- ing materials, etc., can and should be
For manufacturability stories, built in culate the actual velocity simply by kept up to date. I don’t try to get bosses
test for example, a manufacturing engi- adding the point values of the completed to buy into vague outcomes. I get bosses
neer or QA person might play the role of stories. The measured velocity provides that are not satisfied with vaguely
the customer. You can see there may be feedback that is used to calibrate the “working harder/smarter next time.” I
many “customers,” but the final call on plan. We get early warning of schedule get bosses interested that want pre-
what is worked on at what time is up to problems, rather than 11th-hour sur- dictability and visibility into the work. I
the product owner. prises. If the projected date is too late for get bosses that want to see early and
You also ask about estimating time the business needs, managers can use the steady progress through the develop-
and cost. There is no silver bullet here, data to manage the project. The PO can ment cycle, ones that are not so interest-
but there is a realistic process Agile carefully choose stories to do and not do ed in doing more of the same thing and
teams use. When an initial backlog is to maximize delivered value. The busi- expecting different results.
created, all the backlog items or stories ness could looks at adding people before Jack: Now for a hardball question: Is
are written on note cards and spread out it is too late, or change the date. it spelled agile or Agile?
on a table. (A story is not a specification, Jack: Engineering is not a stand- James: Saving the toughest for last,
but rather a name of a feature or part of alone activity. While we are designing a setting me up. Someone with greater
a feature.) Engineers get together and do product, the marketing people make ad- command of the language better take
an estimation session. Each story is given vertising commitments, tech writers cre- that one. Like any label, agile is aging
a relative difficulty on a linear scale. The ate the user’s manual, trade shows are and getting diluted. My real interest, and
easiest stories are given the value of one arranged, accounting makes income and I think yours too, is advancing how we
story point. All stories labeled with a one expense projections, and a whole host of develop embedded software and meet
are of about the same difficulty. A story other activities must come together for business needs. To me many the ideas in
with a value of two is about twice as dif- the product’s launch. TDD says the boss Agile Development can really help
ficult to implement than a one. A five is must accept the fact that there’s no real teams. But its important to consider it a
about five times as difficult. I am sure schedule, or at least it’s unclear which start, not the destination.
you get the idea. features will be done at any particular Jack, thanks again for the chat. It’s
Once all the stories have a relative time. How do you get bosses to buy into always good talking to you.
estimate, we attempt to calibrate the such vague outcomes? Jack: Thanks, James, for your in-
plan, by choosing the first few iterations James: Jack, there goes that miscon- sightful answers. I hope the readers will
and adding up their story points. We’re ception again on “no real schedule.” respond with their thoughts and experi-
estimating the team’s velocity in story There is a schedule, probably a more rig- ences using TDD in their workplace. ■

36 MAY 2010 | embedded systems design | www.embedded.com


R&D Prototype

PCB Assembly
$50 in 3-Days
Advanced Assembly specializes in fast assembly for R&D prototypes, NPI, and low-
volume orders. We machine-place all SMT parts and carefully follow each board through
the entire process to deliver accurately assembled boards in three days or less.

R&D Assembly Pricing Matrix/Free tooling and programming


Up to # SMT Parts 25 50 100 150 200 250 300 Over 300
1st board $50 $85 $105 $155 $205 $255 $305
2nd board $30 $55 $65 $95 $125 $165 $185 Call for
Each additional board $25 $35 $45 $65 $95 $125 $155 Pricing
Stencil $50 $50 $50 $50 $50 $50 $50

aapcb.com/esd4
1.800.838.5650

The new standard for pcb assembly

You might also like