1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;[]-=-=[];,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;[]-=-=[];,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;[]-=-=[];,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;[]-=-=[];,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;[]-=-=[];,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;’[]-=-=[];’,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;’[]-=-=[];’,./
1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM,./;[]-=-=[];,./
7
9
25274 75349
0 1>
CIRCUIT
CELLAR
®
ww
ww
ww
..cc
iirr
cc
uu
iitt
cc
ee
llll
aa
rr
..cc
oo
mm
T H E M A G A Z I N E F O R C O M P U T E R A P P L I C AT I O N S
$4.95 U.S. ($5.95 Canada)
# 1 3 8 J A N U A R Y 2 0 0 2
MEASUREMENT & SENSORS
Build An Engine
Control Unit
Powering USB Devices
A Closer Look At QNX Neutrino
Inside IrDA Standards
• 2 Channel Digital Oscilloscope
•
• Advanced Math options
• FFT Spectrum Analyzer options
Probes, Interface Cable, Power
Adapter, and software for
Win95/98, WinNT, Win2000
and DOS.
Optional 100 MSa/s Pattern Generator
LA2124-128K (100MSa/s, 24CH)
Clips, Wires, Interface Cable, AC
Adapter and Software
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
5
An Integrated PWM Light Controller
Part 2: The Battery Charger
No Power Supply Required
Powering USB Devices
An RF-Controlled Irrigation System
Extensibility for Small Embedded Systems
APPLIED PCs
“The” Embedded Project
Part 1: Specifications and Components
What Good is IrD, Eh?
Part 1: Cordless Protocol
COLUMNS
ISSUE
New Product News
edited by Rick Prescott
Advertiser’s Index
February Preview
Priority Interrupt
Steve Ciarcia
I’ll Stay on the Ground, Thank You!
6
8
11
94
96
138
54
68
76
FEA
TURES
12
20
26
32
38
50
60
44
ave you considered the fact that this January
will be the first time in three years that New Years
has been celebrated without someone arguing over
whether or not the new millennium was beginning? It’s a
small thing, but it just serves as a reminder that everyone is entitled to an
opinion, regardless of whether it is mathematically or logically sound.
Early last year we started formulating a plan to completely overhaul the
Circuit Cellar web site and one of the first things we did was put together a
few short surveys that were posted on the existing site. Aside from the
yes/no answers, we always encouraged feedback or suggestions. And a
wide range of feedback we got. Everything from, “I hate all those blinking
ads!” to “I love all those blinking ads!” Of course, not all of it was mathemati-
cally sound (e.g., “Please make the whole magazine available for free on
the web site.”), but there were some practical suggestions and ideas that
provided real insight into what Web users are looking for.
While those surveys were being conducted, we also took an in-depth
look at the web traffic statistics for the existing site. We compared the
monthly traffic for certain pages, noted which pages saw the most traffic,
which pages saw the least traffic, what users had eaten within the last six
hours before they visited the site (of course I’m kidding, Bill’s team won’t
have that tracking system ready for beta testing for at least another six
months). Then, with numbers and opinions in hand, we sat down and con-
sidered each page of the site and decided whether it needed to be
improved, removed, or just left alone. Looking at numbers was helpful, but
having access to your opinions took a lot of the guesswork out of this stage.
So, after almost five months of getting the new material ready and work-
ing everything out, the new web site appeared on November 1 amidst no
fanfare and no promotional strong-arm tactics to pull people in. There had
been the occasional editorial mention that a new site was coming, but we
were determined not to promote until we were sure we had a fully functional
product. It may have been an antiquated strategy when compared with
today’s typical Web promotion schemes (send out a press release announc-
ing that a groundbreaking press release will be sent out next week…), but if
the “build it and they will come” strategy worked for Kevin Costner in
Field
of Dreams, why couldn’t it work for us?
As I write this editorial about one month after the new site went live, I
have the distinct pleasure of looking at the web-traffic statistics for the
month of November. The numbers that we hoped would be up are up, the
numbers that we hoped would be down are down, and thus far it seems like
the overhaul is just what was needed.
The new site probably won’t win a Webby Award nor will we get to see
our five-word acceptance speech posted on www.webbyawards.com, but in
my opinion (no matter how mathematically or logically incorrect it may be), it
looks like the
Circuit Cellar readers got what they asked for, and that’s good
for everyone.
CIRCUIT CELLAR
®
www.circuitcellar.com
EDITORIAL DIRECTOR/PUBLISHER
Steve Ciarcia
WEB GROUP PUBLISHER
Jack Shandle
MANAGING EDITOR
Rob Walker
EDITORIAL PRODUCTION COORDINATOR
Jennifer Huber
TECHNICAL EDITOR
Jennifer Belmonte
WEST COAST EDITOR
Tom Cantrell
CONTRIBUTING EDITORS
Ingo Cyliax
Fred Eady
George Martin
George Novacek
NEW PRODUCTS EDITOR
Rick Prescott
PROJECT EDITORS
Steve Bedford
David Tweed
ADVERTISING
ADVERTISING SALES MANAGER
Kevin Dows
Fax: (860) 871-0411
(860) 872-3064
E-mail: kevin.dows@circuitcellar.com
ADVERTISING COORDINATOR
Valerie Luster
Fax: (860) 871-0411
(860) 875-2199
E-mail: val.luster@circuitcellar.com
ADVERTISING CLERK
Sally Collins
Fax: (860) 871-0411
(860) 875-2199
E-mail: sally@circuitcellar.com
CONTACTING CIRCUIT CELLAR
SUBSCRIPTIONS:
INFORMATION: www.circuitcellar.com or subscribe@circuitcellar.com
To Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, or
subscribe@circuitcellar.com
PROBLEMS: subscribe@circuitcellar.com
GENERAL INFORMATION:
TELEPHONE: (860) 875-2199 Fax: (860) 871-0411
INTERNET: info@circuitcellar.com, editor@circuitcellar.com, or www.circuitcellar.com
EDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066
NEW PRODUCTS: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066
newproducts@circuitcellar.com
AUTHOR CONTACT:
E-MAIL: Author addresses (when available) included at the end of each article.
CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub-
lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at
Vernon, CT and additional offices.
One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico
$31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico
$55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money
order, or check drawn on U.S. bank.
Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH
03755-5650 or call (800) 269-6301.
Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.
For information on authorized reprints of articles,
contact Jeannette Ciarcia (860) 875-2199 or e-mail jciarcia@circuitcellar.com.
Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the
consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-
er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or
from plans, descriptions, or information published by Circuit Cellar®.
The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to
build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to
construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.
The reader assumes any risk of infringement liability for constructing or operating such devices.
Entire contents copyright © 2001 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks
of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.
CHIEF FINANCIAL OFFICER
Jeannette Ciarcia
ACCOUNTANT
Howard Geffner
CUSTOMER SERVICE
Elaine Johnston
ART DIRECTOR
KC Prescott
GRAPHIC DESIGNERS
Cindy King
Mary Turek
STAFF ENGINEERS
Jeff Bachiochi
John Gorsky
QUIZ COORDINATOR
David Tweed
EDITORIAL ADVISORY BOARD
Ingo Cyliax
Norman Jackson
David Prutchi
TASK
MANAGER
Cover photograph Ron Meadows—Meadows Marketing
PRINTED IN THE UNITED STATES
h
Survey Says…
6
Issue 138 January 2002
rob.walker@circuitcellar.com
NEWS
8
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
NEW PRODUCT
Edited by Rick Prescott
12-BIT SAR ADC
The AD7490 is a 12-bit, 1 MSps, successive-
approximation (SAR) ADC designed with an
increased channel count to meet the demands of
today’s wired and wireless communications
applications, as well as industrial and medical
instrumentation data acquisition applications.
This 16-channel converter is appropriate for
multi-channel applications. A sequencer con-
trolled by a shadow register allows continuous or
single conversions on selected channels. The
channel selection func-
tion can be altered while
the sequence is in
progress.
The AD7490 achieves
low power dissipation
at high throughput
rates. Full-power dissi-
pation is just 3.6 mW,
and in Shutdown mode,
power consumption is only 1 µA.
This ADC operates from a single 2.7- to 5.25-
V supply and contains a Vdrive (interface drive
voltage) function to allow the serial interface to
connect directly to either 3- or 5-V processor
systems independent of the power supply volt-
age. The converter contains a low-noise, wide
bandwidth track/hold amplifier that can handle
input frequencies in excess of 1 MHz.
The AD7490 is offered in a 32-pin lead
frame chip scale package for $6.35 in 1000-
piece quantities.
THREE-AXIS MAGNETIC SENSOR
To complement the ultra-small HMC1052 two-axis sen-
sor, Honeywell designed the HMC1051Z, a single-axis mag-
netic sensor that when used together, offer a miniature,
low-power, low-field three-axis magnetic sensing solution.
Both the HMC1051Z and the HMC1052 have a sensi-
tivity of l mV/V/Gauss, a wide field range up to ±6 gauss,
resolution of 120 microgauss, and can operate on a sup-
ply voltage as low as 1.8 V. Patented on-chip set/reset
straps eliminate the effects of temperature drift and stray
magnetic fields to ensure accuracy and reliability. They
come in small 8-pin SIP and 10-pin MSOP packages.
For compassing and position sensing applications
requiring small size, low power, and high performance,
the HMC1052 is a more cost-effective solution. The
HMC1052 is a two-axis sensor ideal for handheld wire-
less appliance applications such as location-based servic-
es in mobile phones, compassing and Global Positioning
System (GPS) applications in personal digital assistants,
walkie talkies, watches, and GPS receivers. Advantages
of the new design include nearly perfect orthogonal two-
axis sensing in a 3 mm × 3 mm × 1 mm 10-pin miniature
surface mount package (MSGP).
Honeywell International
www.magneticsensors.com
Distributed by:
Digi-Key
(800) 344-4539
www.digikey.com
Analog Devices, Inc.
(800)-262-5643
(781) 937-2824
www.analog.com
I/O MODULE
The ADIO-104 blends popular analog and digital I/O func-
tions in a single PC/104-compliant module. The 16 single-
ended 12-bit analog inputs are independently programmable to
operate in one of four ranges: ±10 V, ±5 V, 5 V, or 10 V. This
increases the dynamic range to 14-bits when using range-
switching software techniques. The ADC operates up to 50
kSps and allows the separate acquisition and conversion inter-
vals to be controlled by the host software or automatically
timed by the hardware. A feature allows simultaneous (phase-
coherent) acquisition on identically configured analog input
pairs. Eight 12-bit analog outputs share a common jumper-selec-
table output range: 5 V, –5 V, ±5 V, 10 V, –10 V, or ±10 V.
An onboard DC/DC converter permits the bipolar and 10-V
ranges to be achieved while operating the module from a single
5-V host supply. In addition, the analog outputs can be updated
simultaneously using a single software command, a necessity in
phase-critical applications such as x-y positioning. Depending on
the model purchased, all analog outputs are automatically set
to zero-scale (RZ) or mid-scale (RM) during a hardware reset.
Port A is bidirectional and can be software programmed for
input or output operation on a 4-bit nibble basis. Port B has six
bidirectional channels and two dedicated input channels. Pull-
up resistors on the four lower channels
simplify connections to external switch-
es, contact closures, and open-collector
devices. Port C is an output-only port.
The four upper channels feature 50 V/165
mA open-drain MOSFETs.
Also included is an 8-bit binary pulse
accumulator (counter) and an edge-sensi-
tive external interrupt input. A standard J1/P1 stack-through
connector allows the module to reside anywhere within an 8-
bit PC/104 stack.
Cost is $352 in 100-piece quantities.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
9
NEWS
NEW PRODUCT
least 13% and maximum power dissipation by at least
26%, while the device profile is decreased by 39%.
Because PowerPAK devices run cooler while producing
more power, they can replace a DPAK or two standard
SO-8 devices running in parallel, thereby saving space
and reducing component costs. The thermal performance
is made possible through a direct thermal path from the
die to the printed circuit
board. PowerPAK’s design
provides a consistent foot-
print regardless of the par-
ticular silicon used in a
given device.
Pricing for 100,000-piece
quantities ranges from
$0.72 to $1.16 per unit.
POWER MOSFETS
A new series of higher-voltage n-channel power
MOSFETs is the first in the PowerPAK SO-8 to be opti-
mized for the primary side of DC/DC converters. These
PowerPAK devices feature a thinner profile than the
standard SO-8 MOSFETs, as well as superior current and
power dissipation capabilities. They can be used in iso-
lated power supply DC/DC converters in 24- to 48-V
applications including telecommunications, computer,
server, automotive, and military aviation products hav-
ing higher supply voltages. In many applications, they
will allow designers to replace DPAK power MOSFETs
with a device that is less than half the size.
The new devices can handle currents from 5.3 to
12.5 A, enabling higher power density designs. Typical
gate charge ratings range from 18 nC in the 60-V
Si7850DP to 34 nC in the 200-V Si7450DP. On-resist-
ance values are 22 m
Ω
and 80 m
Ω
at a 10-V gate drive
for the ’7850 and ’7450, respectively.
The series features the industry’s lowest on-resistance
times gate charge product for 60- to 200-V primary side
MOSFETs. Continuous drain current is improved by at
Vishay Intertechnology, Inc.
(610) 644-1300
Fax: (610) 296-0657
www.vishay.com
&DOORUYLVLWRXUZHEVLWHWRUHFHLYHPRUHLQIRUPDWLRQ
&LVDWUDGHPDUNRI3KLOLSV&RUSRUDWLRQ0LFURFKLS7HFKQRORJ\,QF$OOULJKWVUHVHUYHG
DQDORJSHUIRUPDQFH
HPEHGGHGRQWKHQHZIDPLO\
RIFRQÀJXUDEOHDQDORJ3,&
VPDOOSDFNDJHRSWLRQV
PRUHWKDQLQWHJUDWHGVWDQGDORQHFRPSRQHQWV
IDPLOLDUEXLOGLQJEORFNVUHGXFHOHDUQLQJFXUYH
FRPSUHKHQVLYHVHWRIGHYHORSPHQWWRROV
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
11
AD422 (Requires 9VDC) $79.00
AD422-1 for 110VAC
ADA485 (requires 9VDC) $79.00
ADA485-1 for 110VAC
CMC’s low cost converters adapt any
use with RS422 or RS485
devices
• Adds multidrop capability to
ADA425 (requires 9VDC) $89.00
ADA425-1 for 110VAC 99.00
Mention this ad when you order and deduct 5%
Use Visa, Mastercard or company purchase order
WWW.2CMC.COM Fax:(203)775-4595
PO BOX 186, Brookfield,CT 06804
Connecticut microComputer, Inc.
• Use as a short haul modem
• Plug in and go. No software
—Regular expression quantifiers can be classified as
“greedy” or “non-greedy,” depending on whether they attempt to find
the longest possible match or shortest possible match, respectively.
For example, in Perl, you would use the greedy /.+/ or the non-
greedy /.+?/ to match a string of one or more arbitrary characters.
Suppose you were searching a string for of filenames ending in .txt,
using either /\w+\.txt/ or /\w+?\.txt/. Would you expect one or the
other to perform significantly better than the other? Why?
—You need to read a series of records from one file and
discard any that match any of a set of patterns given in a second file,
and then print the remainder. How would you code this in Perl?
—Anyone who has worked with spectral analysis knows
that a squarewave contains all of the odd harmonics, where the
amplitude is one over the frequency ratio. In other words, if the fun-
damental frequency has an amplitude of one, the third harmonic has
an amplitude of one third, and so on.
What is special about the following waveform, which can be con-
structed by taking two squarewaves and adding them together after
shifting one by one-sixth of a period relative to the other?
Draw a phasor diagram that explains the special characteristics of
—If you have four flip-flops and three resistors, how
would you calculate the resistor values to get the best approxima-
uring the early to
mid 1980s, vehicle
manufacturers, under
pressure to increase fuel
economy and simultaneously reduce
emissions, switched to electronic fuel
injection and have never looked back.
When the automotive aftermarket saw
the trend, it entered the field, first with
PROM chips that allowed you to modi-
fy the constants programmed into the
electronic controller unit at the factory
by simply switching chips. The tech-
nology of PROM chips enabled you to
increase performance, generally at the
expense of gas mileage, and to make
engine modifications for which changes
in program parameters were needed.
Gradually, conversion kits were
developed to allow do-it-yourself guys
and racers to upgrade carburetor
engines to electronic fuel injection (EFI)
or to switch ECUs to obtain more con-
trol over the system than the repro-
grammed PROM chips allowed. These
kits generally contain an ECU and a
wiring harness, and many include
mechanical options such as intake
manifolds, throttle bodies, fuel pumps,
and injectors appropriate for EFI.
Although now plentiful, these kits
are costly, even without the mechani-
cal options (most of which can be
obtained from the local scrap yard).
The price for just an ECU and soft-
ware generally ranges from $1000 to
well over $3000 for high-end units
used in formula one racing.
This article is about building your
own fuel injection ECU for a small
fraction of this cost. Of course, you’ll
have to supply the labor to solder the
board and make the wiring harness
and mechanical modifications needed.
Before starting on the electronics, you
should know something about how
modern EFI works and what algo-
rithms are needed.
EFI BASICS
The electronic fuel injection system,
like most embedded systems, consists
of a set of sensor inputs, a processing
unit, and a set of output controls. The
basic inputs required are: engine speed,
intake manifold air pressure (MAP) or
mass air flow (MAF), barometric pres-
sure, throttle position (TPS), battery
voltage, coolant temperature, intake
manifold air temperature (MAT), and
exhaust gas oxygen content (EGO).
Numerous other inputs can be added
to this list, limited only by your imagi-
nation. Examples of these inputs found
on various makes and years of cars are:
knock detection, oil and fuel pressure,
power steering pressure, transmission
gear selection, air conditioning status,
braking status, and wheel speed (for
traction control). All are intended to
provide the processor with the informa-
tion it needs to make the car run
smoother, safer, cleaner, and more effi-
cient and reliable under all conditions.
The primary outputs of the processor
are the signals to turn the fuel injectors
on and off. The on time pulse width
determines the amount of gas that is
injected into the engine, and is contin-
uously calculated to within at least 0.1
ms, a fraction of the measured air
quantity being drawn into the engine.
When power is needed, the fuel/air
mixture can be enriched by lengthen-
ing the injector on time. When idling
at a stoplight, the mixture can be
leaned out to save gas and reduce
emissions. This system is far more
accurate than a carburetor, and pro-
vides infinitely more flexibility in tai-
loring the fuel curve to actual road
12
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Bruce Bowling & Al Grippo
Building a
Fuel-Injection ECU
Trying to replace or
upgrade an ECU with
commercial offerings
can get expensive.
Instead, Bruce and Al
take you through the
process of building
your own fuel-injection
ECU. They start with
plenty of information
on electronic fuel injec-
tion systems and how
everything works.
d
conditions. Other common outputs
include spark control, idle speed con-
trol, fuel pump relay, exhaust gas
recirculation, fan and A/C control,
and transmission lockup.
FUEL CALCULATIONS
The primary control algorithm used
in EFI is the calculation of injector on
time or pulse width. To first order,
this is simply:
[1]
The injector flow rate is a constant
measured at the factory by flowing the
injector at the line pressure specified
for the car. A typical value is 20 lbs/h
for a port injector that supplies one
cylinder. This value is normally loaded
in the flash memory of the ECU. It is
one of the parameters that the after-
market PROMs would change if you
wished to install higher flow injectors.
The fuel required in Equation 1 is
the hard part. It depends on the
amount (mass) of air entering the
engine and the desired fuel- to-air
ratio. This ratio affects several things,
including the amount of
power the engine makes,
fuel economy, and emis-
sions produced.
The chemically opti-
mum (stoichiometric)
ratio is 14.7 parts air to
one part fuel, in units of
mass. This results in the
most complete combus-
tion of the fuel in the
laboratory. In the
engine, however, it is
found that a little bit
richer produces more
power, a little leaner
gives better gas mileage,
and emissions are best
overall at stoich.
As you will see, there
are several other factors
to be considered. For
now, assume you know
the AFR you want, so
now, you just need to
determine how much
air is entering the
engine. This is most
commonly determined from the MAP
sensor, which gives a signal propor-
tional to the absolute pressure in the
intake manifold. After you determine
how much air density is entering the
engine, use the following equations:
[2]
[3]
[4]
Air density is in pounds per cubic foot,
MAP in kilopascals, MAT is the
intake manifold air temperature in
degrees Fahrenheit, and the 459.7 con-
verts to degrees Rankine. The volume
of the cylinder is in cubic feet and,
under ideal conditions, will be entirely
filled with air before it is compressed
by the piston and ignited.
Of course ideal conditions never pre-
vail, so you need to correct for the
actual cylinder filling (i.e., engine
pumping efficiency). This turns out to
be a function of engine revolutions per
minute and throttle position. The
more you press on the throttle, the
easier air can enter, and the manifold
configuration and cylinder valve tim-
ing are such that air enters most effi-
ciently at some mid-range revolutions
per minute (maximum torque point).
So, you need a correction factor in
the fuel equation that is a function of
revolutions per minute and throttle
position. Because the MAP is deter-
ministic for a given revolutions per
minute and throttle, it is common to
just make the correction factor,
called the volumetric efficiency, a
function of revolutions per minute
and MAP. The correction table is
determined at the factory using an
engine dynamometer and then down-
loaded to ECU flash memory.
At the same time, provision is made
for any deviation desired from the
ideal 14.7 AFR. This all can be done in
one table or a separate AFR table can
be downloaded. Typically, the AFR is
made closer to 12 at high revolutions
per minute and high MAP values
(wide open throttle conditions) and
under idling conditions where the
engine is less efficient.
In order to do the VE/AFR table
look-up, you need to know the engine
revolutions per minute. This can be
determined from several
devices. Typically, a reluc-
tor or Hall sensor senses a
toothed wheel attached to
the engine crankshaft or
distributor, and the pulses
are timed in the ECU.
From this stage, it is simple
to determine revolutions
per minute, do the table
look-up, calculate the cor-
rected mass fuel quantity,
and determine the required
injector pulse width. This
timing signal is then used
to control the injector driv-
er section of the ECU,
which will be discussed in
the electronics description.
Typical values for pulse
width are 2 to 10 ms.
For those of you who
want to make your own
engine controller, the
VE/AFR table must be
determined by trial and
error. But that’s why you
want your own ECU, so
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
13
Figure 1—Here is the schematic of the circuit for the MC68HC908GP32 microprocessor,
crystal oscillator circuit, power supply regulation, as well as filtering for the EFI controller.
Note the extra filtering circuits for the ADC reference supply and the onboard phase-locked
loop oscillator.
that you may change the
values to suit your needs.
Various sources may pro-
vide a starting point for
the table. Aftermarket
ECUs typically have
default tables that at least
get the car running. Then,
you can start adjusting
values at idle to make the
engine run smoothly.
The next step in tuning
is to drive at fixed revolu-
tions per minute in a
fixed gear and again adjust
until the engine sounds
good. For optimum tun-
ing, you need to visit a
service shop with a chas-
sis dynamometer. Today,
there are many such
shops with the experience
to tune an ECU properly.
A session typically costs
several hundred dollars.
FUEL STRATEGIES
The preceding description covered
the basics, but there are several other
corrections that need to be made if
you want a vehicle that can be driven
during any condition. The first of
these is an enrichment for a cold start.
The modern engine is designed to
operate with a coolant temperature
of about 190°F or higher, so even start-
ing in 90°F weather in Florida can be
considered a cold start. During the
cranking period and for at least several
minutes thereafter, an extremely rich
fuel mixture is required for the engine
to fire and run properly. How rich
depends on the coolant temperature as
measured by the coolant sensor. Thus,
a table is provided in flash memory for
fuel enrichment versus temperature,
and this is factored into the injector
pulse width equation. As the engine
warms up, the enrichment tapers off.
During the cranking phase, more
sophisticated strategies employ asyn-
chronous injection, in which the injec-
tor is made to pulse several
short bursts of fuel rather
than a single long shot.
This produces better mix-
ing of the fuel and air,
which is needed during
cranking, because there is
little engine vacuum gener-
ated at the slow cranking
speeds. Hence, the air
moves slowly through the
intake tract and does not
mix well with the fuel,
thereby producing a weaker
and rougher combustion
event. This can make the
difference between having
to continuously crank
before enough gas accumu-
lates in the mix to fire
or having the engine fire
almost the instant you
turn the ignition key.
A second area requir-
ing special improvement
is acceleration. When
you press down on the
throttle to pass another
car, a large amount of air
is suddenly let into the
engine; it’s obvious that
power is wanted, not fuel
economy. Under these
conditions, a rich mix-
ture is required for a
short period to keep the
engine, which is trying
to move a 3000- to 4000-
lbs mass, from stum-
bling. To do this, the
ECU must first sense
that acceleration is
occurring.
The ECU does this by
polling for a TPS or
MAP sensor rate of change that is
above a fixed threshold. When this
occurs, the mixture is enriched by an
amount and for a time period, which is
a function of the rate of change. This is
a trial and error enrichment. Note that
a variety of more sophisticated
schemes can be used to ensure the
smoothest possible speed transition.
Another fuel correction commonly
used is for barometric pressure.
Barometric pressure affects airflow
and air density, therefore, the fuel
must be corrected to maintain a
desired AFR. AFR may be sensed with
a MAP sensor that is simply exposed
to air, as opposed to the primary MAP
that is installed in the intake tract. If,
however, you are an OEM bean count-
er, you may save money by using the
intake MAP reading just before you
start the engine as the barometric
pressure. That way, you don’t need a
second sensor and have saved the
company say $20 times x million cars.
The fuel injector is a solenoid tied
to battery voltage on one end, and is
grounded by the ECU at the other end
when it is desired to turn on the injec-
tor. Now, the specification injector
flow rate is for steady state conditions.
But, the injector in the car is not run
14
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Figure 2—Inputs for the EFI controller are shown here. The manifold absolute pressure,
coolant, air temperature, and oxygen sensors are filtered with low-pass filters to reduce signal
noise. In addition, the ignition coil primary circuit is optoisolated from the controller IRQ circuit-
ry to help prevent circuit damage resulting from stray high-voltage ignition spikes.
Figure 3—The fuel injectors are driven by two independent MOSFET
driver circuits that can be operated together or in an alternate fashion,
depending on the software configuration. Make sure you take a close
look at the driver circuitry for the fuel pump relay and fast idle solenoid.
16
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
at steady state, rather it is constant-
ly pulsed on and off and requires
about 2 ms to fully open and 1 ms
to fully close. (It fights spring pres-
sure while opening, and the spring
assists in closing.)
This fact requires two more cor-
rections to the fuel equation. One
modification is because the flow
rate is not constant, and the other
is a compensation for battery volt-
age, which has an effect on the
open time.
If the battery is weak, the injector
will take longer to open. Therefore,
battery voltage must be sensed, gen-
erally by running a portion of the
ECU power into an A/D channel.
The nominal injector open time is
then modified either linearly or
from a table according to the devia-
tion of battery voltage from 12 V.
The injector flow rate then can be
modified in a number of ways to take
into account the initial flow ramp.
As mentioned previously, the stoi-
chiometric mixture is the best for all-
around driving, economy, and emis-
sions. Hence, you strive for this in
Closed Loop mode using oxygen sen-
sor feedback. This sensor, as the name
implies, sends back to the ECU a volt-
age proportional to the amount of free
oxygen in the exhaust. Too much
means a lean mixture requiring
more fuel be added; too little
means just the opposite.
So, in Closed Loop mode, a PID
loop or its equivalent is used to
modify the basic fuel equation to
maintain the correct fuel mix regard-
less of the brand or type of gas you
use or the amount of wear on your
engine. This mode is used instead of
idling during cruise conditions when
a stoich mixture is desired.
Well, we’ve talked quite a bit
about EFI theory. Although it may
sound complicated, it should be
obvious that an ECU does what any
embedded control system does—
senses various parameters and acts
accordingly to implement various
controls.
SHOW ME THE CIRCUIT
You start the circuit description
with the power supply. It is hard to
find a more hostile environment than
the electrical system of a automobile:
200 A-plus to start the motor, 20 kV
Figure 4—The RS-232 level translation driver circuitry is shown
along with the main input, output, and power connector for the
EFI system. A standard DC-37 connector is used.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
17
As in practically all embedded sys-
tems, there are inputs and there are
outputs. In this case, your inputs are
various sensors measuring engine
parameters and your outputs control
fuel injectors and relays. So, let’s start
with the inputs (see Figure 2).
Arguably the most important sensor
in this system is the MAP sensor,
which monitors intake manifold vac-
uum. The sensor used here is the
Motorola MPX4115. The MPX4115 is
an integrated pressure sensor contain-
ing the sensing element, amplifier,
and temperature compensation cir-
cuitry all in one package. And, it
yields an analog output that is propor-
tional to applied pressure (absolute,
not gauge). The output of the MAP
sensor is filtered by R2 and C4 and is
supplied to channel 0 of the ADC in
the microcontroller.
Engine temperature measurements
are sensed by negative coefficient
thermistors mounted in the intake air
stream (MAT) and engine coolant liq-
uid (CLT). The sensors used in this
design are standard OEM devices used
by General Motors since the 1980s
(GM part number 12146312). These
sensors yield a resistance of 100 k
Ω
at
–40°F and 2000
Ω
at 90°F.
In order to sense the resistance of
the sensors, they are configured as
part of a voltage divider circuit: R4 for
the MAT sensor and R7 for the CLT
sensor. One side of each sensor is tied
to ground. The resultant divider volt-
age is filtered by R5 and C6 for the
MAT sensor and R8 and C8 for the
CLT sensor, and protected from over-
voltage by D2 and D3.
Real-time sensing of throttle position
is required by the CPU in order to pro-
vide more fuel during periods of rapid
throttle opening. The standard throttle
position sensor (TPS) is a simple 10-k
Ω
potentiometer attached to the throttle
shaft with a constant voltage (5 V in
this case) across the potentiometer.
The wiper terminal of the pot will
therefore provide a variable voltage of 0
to 5 V. This voltage is filtered by C10
and R9 and clamped by diode D4, and
then applied to ADC channel 3.
Other input sensors include battery
voltage (needed to adjust the injector
opening time), which is derived by the
pulsing away to spark the plugs, loads
like headlights, heater fans switching
on and off, alternator charging, etc.
To combat these nasty enemies, this
power supply has several tricks up its
sleeve. The first is the combination of
D14 and D16, which clamp reverse
voltage spikes to –12 V (see Figure 1).
D13 permits positive polarity voltage
to pass only to D15, which clamps
this voltage to 22 V, eliminating the
over-voltage effects of switched loads.
U5 is a linear 5-V regulator designed
for automotive applications; this part
by itself can handle reverse and over-
voltages. Couple the regulator with
the preceding diode clamping circuit
and the result is an extremely robust
power supply. Remember, that which
does not kill you makes you stronger.
The CPU of choice for this application
is the Motorola MC68HC908GP32.
This CPU is a member of the HC08
family of microcontrollers, providing a
full integration of features. The CPU
core runs at an internal bus speed of 8
MHz, which is derived from an inter-
nal phase-locked loop clocked from a
32.768-kHz crystal. The GP32 version
has 32 KB of on-chip flash memory
with direct in-circuit programming. In-
circuit programming allows for the
storage and run time reprogramming of
constants, which is extremely desirable
in this application.
There are 512 bytes of on-chip RAM,
which is more than adequate for this
application. Other features include
two 16-bit, two-channel timers, SPI
and SCI communication channels, and
an eight-channel, 8-bit ADC. One key
feature is that the operating range of
the GP32 is from –40°F to 85°F; this
application will experience a wide
range of temperatures.
The CPU oscillator circuit comprises
a 32.768 watch crystal, two capacitors,
and two resistors. The on-chip PLL
clock circuit requires the external loop
filter network C19, C20, and R20. The
microprocessor has an internal powerup
reset circuit, so no external circuitry
is required. There are two power sup-
ply filter circuits. One consists of C18
and L1 providing power to the internal
PLL clock and L2, C21, and C22,
which is the analog power supply for
the analog-to-digital converter.
18
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
The low-impedance types
(known as peak-and-hold injec-
tors) require a different drive
strategy. These injectors like to
have higher peak current applied
(say, 4 A) while they’re opening,
and a lower hold current (1 A or
so) to keep them open. To provide
this relative current control, Q2 is
driven fully on while the injector
is opening. When a predetermined
time that is sufficient to ensure
that the injector is open (based on
injector impedance and supply voltage)
has elapsed, the drive to Q2 is
switched to a PWM mode. This is
accomplished using the PWM mode of
the timer channel, with a frequency of
15 kHz and a duty cycle that keeps
the average current through the injec-
tor at the desired hold value.
Direct control of a fast idle solenoid
is provided by Q5 (spikes limited by
D9), which is opened when the engine
is first started and not at a fully
warmed temperature. The fast idle
solenoid provides an air bypass around
the throttle plates to provide addition-
al air in the intake manifold. The
operation of the electric fuel pump is
also controlled by the microcontroller
(via a relay) using Q3.
Tuning of parameters while the
engine is running is key to a success-
ful injector control unit. This unit
uses a standard RS-232 interface to
talk to a host PC, which is running a
custom application that allows the
download and tuning of the relevant
parameters. Figure 4 shows the stan-
dard circuit that provides the RS-232
electrical voltage ranges using a
MAX232. Also shown is the main
connector in which the power, input,
and output signals interface to the
board. Note that half of the connector
pins are dedicated to engine ground;
several amps may flow back to the
engine ground circuit, and the added
pins help alleviate any power dissipa-
tion issues with the connector.
Figure 5 is the engine wiring dia-
gram for the various sensors, injectors,
and relays. The fuel injector controller
is designed to be powered when the
ignition key is in the on position,
which occurs via a relay. The coolant,
air, throttle, oxygen sensors, as well as
ground return from the controller are
tied to engine ground at a common
point. Figure 5 shows several high-
impedance injectors tied together in
parallel in two groups of four. Also
check out the finished product in
Photo 1.
EMBEDDED CODE DESCRIPTION
To properly control an engine, you
have to read in all of the sensors, com-
pute the required fuel needed, and
energize the injectors for a computed
period of time (measured in millisec-
onds). But there’s more to it than
meets the eye. For instance, fuel will
7
8
9
10
11
20
21
22
23
24
26
28
30
32 33
37
35
34
DC37 Connector
Ground to engine block
Fuel pump
Air
temperature
sensor
Fuel pump relay
Coolant
temperature sensor
Exhaust gas oxygen sensor
Fuel injector(s)
Ignition coil
(negative terminal)
or
TACH terminal
on aftermarket
ignition system
Main relay
12-V Battery
(not switched)
12-V Battery
(switched)
Fast idle solenoid
Throttle position sensor
Figure 5—The various sensors, injectors, relays, and power control wiring is done as illustrated. Note that the EFI
controller is directly grounded to the engine block in order to ensure accurate ground reference for the sensors.
resistor divider consisting of R3 and R6,
and the exhaust gas oxygen content
sensor (O2). The O2 sensor is a special
device that generates a small voltage
(approximately 0.6 V) when the ratio
of gas to air is less than 14.7. Once
again, the common theme of filtering
(R1 and C2) and limiting (D11) is used.
This fuel injection system is of the
speed/density variety, meaning that the
amount of air consumed (and required
fuel) is deduced from the manifold
absolute pressure and the revolutions
per minute at which the engine is oper-
ating. To determine revolutions per
minute, a timing signal is tapped off of
the ignition circuit (ignition coil pri-
mary circuit or tachometer drive). This
signal is applied to a 4N25 optoisolator
providing immunity to damage from
over-voltage. The phototransistor in
the optoisolator is biased by R11 and
then fed into the interrupt pin IRQ1 of
the microcontroller.
Figure 3 is the schematic for the
various output drivers for fuel injec-
tors and relays. Starting with the fuel
injectors, there are two separate but
identical fuel injector drivers (we will
describe only one of them). The timer
output compare/PWM channel is fed
into the totem pole drive circuit of Q1
and Q4, which in turn provides gate
drive (via R12) to Q2. Q2 pulls low the
fuel injector, and zener diode D6
crushes the over-voltage.
Let’s take a moment to discuss fuel
injector impedance. There are two
common electrical impedances for fuel
injectors, high impedance (roughly 12
to 16
Ω
) and low impedance (1.2 to 2.5
Ω
). The high impedance flavor (also
known as saturated) provides its own
current limiting, because of its compa-
rably high resistance, and can be driv-
en directly by Q2.
Photo 1—The assembled unit (with cover removed) is ready
for installation. The LEDs on the front panel are indicators for
power and input triggering from the ignition coil. The case is a
standard unit available from LMB.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
19
tend to condense on the walls of the
manifold if the throttle is opened
quickly, thus leaning the fuel/air mix-
ture and requiring an enrichment of
fuel to be added. Also, when it’s cold,
the engine will want a richer mixture
than when it’s warmed up. Ditto
when you initially crank over the
engine, it wants more fuel.
The important thing to note here is
that the injector is controlled as a
function of time. Open the injector
longer and it will transfer more fuel.
Excluding the injector opening time,
the relation to fuel delivered versus
time is mostly linear. Guess what?
You need some sort of time function
to schedule injector open time.
Here comes the MC68HC908GP32
to the rescue. This part features a flex-
ible 16-bit timer that is incremented
by the bus clock after being divided by
a software-selectable prescaler. More
importantly, the timer section has a
module register that causes the timer
value to reset to zero and generate an
interrupt when the timer value equals
this modulus value. With careful
selection of timer prescaler and modu-
lus register values, you can generate
an interrupt at a periodic rate.
Bruce Bowling is an applications engi-
neer with Arrow Electronics in
Columbia, MD. His experience
includes large-scale control system
design for particle beam accelerators
and military weapon test and evalua-
tion. You may reach him at bbowl-
ing@earthlink.net.
Al Grippo is a staff scientist at the
Free Electron Laser Facility at
Jefferson Laboratories in Newport
News, VA. Previously, he was the cor-
porate scientist for Analysis and
Technology in Chesapeake, VA. His
experience includes computer model-
ing and simulation and complex
process control for military and
physics research. You may reach him
at grippo@jlab.org.
SOFTWARE
To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2002/138/.
RESOURCES
J.R. Heywood, “Internal Combustion
Engine Fundamentals,” McGraw-
Hill, New York, NY, 1988.
J. Hartmann, “Fuel Injection
Installation, Performance Tuning,
Modifications,” Motorbooks
International, Osceloa, WI, 1993.
SOURCE
This is exactly what was done with
this controller: the values were cho-
sen such that an interrupt is generat-
ed once every 0.1 ms, which becomes
the master control clock. All time
events, like injector open/close, are
based on this master clock. In addi-
tion, you can count the number of
times the interrupt occurs and gener-
ate slower clock times, like millisec-
onds and seconds.
Figure 6 demonstrates what happens
within the controller. The block of
code on the left consists of initializa-
tion and a main calculation loop. This
loop, which computes the required
fuel needed (and hence, the injector
energize time) executes whenever the
processor is not in an interrupt state.
For the exact details of what is com-
puted, refer to the source code provid-
ed on Circuit Cellar’s ftp site.
As you can see, on the right side of
Figure 6 are the various interrupts.
The timer interrupt routine is the
main time clock function described
earlier. The IRQ interrupt is triggered
every time there is an ignition event
and is used to determine engine revo-
lutions per minute and trigger the
start of an injection event.
The ADC interrupt routine is called
when an ADC conversion is complet-
ed. And, the SCI receive and transmit
sections deal with data to and from the
RS-232 interface. There are also a few
subroutines used for interpolation,
dividing large unsigned numbers, and
flash memory programming. The
flash memory programming routine is
important in that it allows you to
reprogram various constants (down-
loaded via the RS-232 PC interface)
while the engine is running. This rou-
tine is extremely useful when tuning,
in fact, it is difficult to live without.
I
Set up phase-lock loop, RTC, serial, interupts
Initialization of ports and variables
Sample MAP sensor and save as barometer
Copy configuration and VE variables from flash memory to RAM
Copy flash memory burn routine from flash memory to RAM
Ordered table search routine
Linear interpolation routine
32 × 16 Unsigned multiply
Flash memory programming routine
Increment 100- s count
Check for new injection event
Check for injection event complete
Check for PWM enable event
Check revolutions per minute and turn off pump
if engine stalled
Check/increment milliseconds
Initiate new ADC conversion
Check/increments 0.1 s
Check/increment seconds
Increment ASE and EGO step counters
Enable fuel pump
Check for injection enable and schedule injection
Transfer byte to transmit register
If last byte to transmit, then disable Transmit mode
Retrieve new ADC reading
Average with last ADC reading and store
Increment ADC channel pointer
Retrieve SCI character
If "A," enable transmit of all real-time variable
If "B," jump to flash memory burn routine
If "C," enable transmit of SECL variable
If "V," enable transmit of entire VE table
If "W," receive offset and new byte to save
Perform table look-up for barometer and air density correction
Perform table look-up for coolant and MAP linearization
Determine if in Fast-Idle mode
Compute revolutions per minute, determine if engine is
cranking or running and flood-clear
Calculate warm-up and after-start enrichment
Calculate acceleration enrichment and enleanment
Calculate EGO enrichment
Calculate VE from 2-D table interpolation
Compute total enrichment value (acceleration, barometric
pressure, air density, EGO, and warm-up)
Compute VE contribution
Compute MAP and barometric pressure
Calculate REQ_FUEL
Calculate battery voltage compensation
Calculate final pulse width
Initialization and main calculation loop
Subroutines
Timer interrupt routine
IRQ interrupt routine
ADC conversion complete interrupt routine
SCI receive interrupt routine
SCI transmit interrupt routine
Figure 6—For the MC68HC908GP32 engine con-
troller, there is one main calculation loop that per-
forms the fuel/pulse width calculation and several
interrupt routines that provide timer functions, seri-
al communications, and service for IRQ interrupts
and ADC sampling.
ou’re almost
ready for nighttime
bicycling. As I told you
last month, when some
of my biking buddies persuaded me to
join their team in a 24-h relay bike race,
I decided to build my own lamp for the
evening legs of the trek. The project
consists of a light controller and battery
charger system. I’ve already covered
the first task of creating the light con-
troller; now, it’s time to finish the
project with the battery charger system.
Designing and debugging the soft-
ware and hardware for the lamp con-
troller was a relatively safe activity.
The worst thing that happened was I
applied too much voltage to the lamp
during a careless moment and the fil-
ament burned out.
Developing the software for the
smart charger required a little more
attention, because the care and main-
tenance of NiMH batteries is critical.
The reason can be seen in the chem-
istry of such batteries. Although the
discharge characteristics are similar
to NiCad batteries, the charging char-
acteristics of the two types of cells
are significantly different.
The NiCad charge is endothermic
(i.e., absorbs heat from its surround-
ings), and it is relatively tolerant of
overcharging. On the other hand,
NiMH charging is an exothermic
reaction, which produces heat. Also,
overcharging should be limited. The
chemical equations for charging a
NiMH battery are:
[1]
[2]
The former equation is for the nega-
tive electrode and the latter equation
is for the positive electrode.
While the cell is charging, the
externally supplied source of current
causes hydrogen protons to migrate
from the positive to the negative elec-
trode, where they are absorbed into
the metal alloy’s interstices denoted
by the (H) in Equation 1.
The cell is designed so that the pos-
itive electrode reaches full capacity
first. It then will generate oxygen gas
that diffuses to the negative electrode
where it is recombined. During minor
overcharge, this mechanism ensures
that pressure equilibrium is maintained
within the cell. However, if seriously
overcharged, it is possible that oxy-
gen, or even hydrogen, will be gener-
ated faster than it can be recombined.
What this means is that along with
producing heat, the charging battery
internal pressure may rise sufficiently
to cause a safety vent to open to
reduce the pressure and prevent cell
rupture. The vent reseals after the
pressure is relieved. Ideally battery
charging should be monitored and
controlled to prevent gas release.
Many NiMH battery packs contain
temperature sensors that allow chargers
in, for example, laptop computers or
electric drills to limit charging to a
maximum defined by the maximum
temperature in the battery. In addition,
to protect the battery from excessive
heat, a thermal trip may be placed in
contact with the battery pack. The
batteries I bought from CompUSA
have these features, as I discovered
when charging a battery in my car
one hot, Texas Saturday afternoon.
However, the process of monitoring
temperature requires an additional set
of connections to the battery, which
did not suit my minimalist approach.
20
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Richard Soja
Richard is back to fin-
ish up his project. He’s
been working on an
integrated PWM light
controller for bicycling
at night, which you can
adapt for your own
applications. Now that
you know how to build
the lamp controller, it’s
time to complete the
project with the battery
charger system.
y
An Integrated PWM Light
Controller
Part 2: The Battery Charger
CHARGING STRATEGY
To recapitulate, my requirements
were to use the same controller for
smart charging as was used to control
and monitor lamp power. To keep the
project simple, I had a single pair of
connections to the battery pack and
to the lamp, so there was no provi-
sion for monitoring battery tempera-
ture. Figure 1 shows the configuration
for lamp control and battery charging.
Fortunately, an interesting phenom-
enon occurs when a NiMH (or NiCad)
battery is charged at a sufficiently
high rate. As the battery approaches
and exceeds full charge, the terminal
voltage, which at first increases as
charge is pumped into the battery,
starts to decay. In addition, the volt-
age decay (–
∆
V) correlates well with
full charge and the onset of tempera-
ture and pressure increase. Figure 2
shows the typical characteristics.
Charge rates significantly affect the
voltage, pressure, and temperature
profile. The –
∆
V effect becomes more
pronounced as the charge rate increas-
es. From the profiles obtained from
two different battery manufacturers,
it appears that charge rates in the 0.1-
C region produce no measurable volt-
age drop, and thus would make it dif-
ficult to detect full charge.
Note that a 1-C value means the
battery is charged at its published
ampere-hour capacity. In my case,
the 3.7-Ah battery would be charged
at a rate of 3.7 A. The time to charge
is greater than 1 h because of a less
than 100% charging efficiency. A
0.25-C rate is equivalent to a charg-
ing current of 0.9 A.
One mitigating factor for a low
charge rate is that the temperature
and pressure seem to increase slowly,
so it probably would not cause a prob-
lem if left unattended for too long.
Note, this is how most low-cost bat-
tery chargers work.
For this project, to provide the best
detection of the –
∆
V effect, I made
sure the current sources I had could
deliver more than 0.1 C. I used two
different versions of current sources
that provided approximately 0.25 C
and 1 C charge rates each. I used the
–
∆
V effect in combination with a
time and voltage monitor to provide
some fail-safe limit, in the
event that there was some
problem with the battery
or connections.
According to one manu-
facturer, the –
∆
V that
should be detected is
between 5 and 10 mV per
cell. Tests on my own bat-
teries showed a good correlation of
around 70 mV for the 7.2-V pack. The
ADC on the HC11 resolved to approx-
imately 39 mV, so I reckoned that a
two-LSB drop in measured voltage
would be a good threshold to set for
terminating High Charge mode. One
recommended charge profile is shown
in Figure 3. It shows that prior to rapid
charge, a trickle charge may have to
be applied. This would be necessary
only for batteries that are excessively
discharged, because high currents into
a deeply discharged NiMH battery can
prevent restoration of full capacity.
Other set points on the chart are
trickle charge after rapid charge, max-
imum time, and maximum absolute
voltage. At the 1-C charge, the charg-
ing should be limited to 90 min.
when the maximum allowable voltage
is 1.8 V per cell. This would be equiv-
alent to 10.8 V on my battery pack, a
value I never saw because the thermal
trip activated long before that.
One additional characteristic must
be allowed for at the onset of rapid
charge. If the battery has been unused
for some time or is deeply discharged,
a pseudo –
∆
V effect can take place.
This is eliminated by inhibiting the
–
∆
V detection mechanism for the first
10 min. of rapid charge.
There are other charging strategies
that don’t involve temperature sens-
ing. Possibilities include detecting
temperature rise or simply profiling
the charge rate without temperature
monitoring. Make note that you
should never consider continuous
trickle charge of a discharged battery
as a feasible strategy.
REQUIREMENTS
An inspection of the charging pro-
file requirements shown in Figure 3
indicated that I needed to provide the
following list of functions. First, an
absolute voltage measurement to
detect a deeply discharged battery,
absolute maximum limit, and self-dis-
charge voltage levels. A –
∆
V detector
to detect an approximately 70-mV
change in battery voltage was on the
list. The third function was a real-time
delay to inhibit the –
∆
V detector in
the case of a deeply discharged battery.
Fourth, a charge rate controller to
provide a range of charge rates was
necessary. Also to be included was a
real-time clock with a resolution of
1 min. and range of at least 5 h to
limit the maximum rapid and trickle
charge times. At the 0.25-C charge
rate, the battery would take more
than 4 h to charge. Sixth on the list
was programmable, nested, real-time
delay loops to allow repeated signaling
to the user of the current charging
mode. The final function was an auto-
matic method of detecting either
Lamp Control or Smart Charge mode.
IMPLEMENTATION
The hardware was set up to allow
easy detection of Smart Charge mode.
The ADC measurable input range was
0 to 10 V. In Lamp Controller mode, the
battery voltage is in the 6- to 8.8-V range
throughout its discharge cycle. When
the constant current charging supply
is applied to the power input connec-
tor of the controller, the ADC pin sees
a voltage greater than 7 V when no bat-
tery is connected. The HC11 ADC input
pins are designed to accept up to 12-V
input and an injection current of a
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
21
Unit in Lamp
Controller mode
Unit in Smart
Charger mode
Lamp
Battery
Current
source
Socket
adapter
Plug
adapter
Battery
Figure 1—The lamp controller is converted to a smart charger by
inserting in-line plug and socket adapters. The arrows shown repre-
sent the direction of current flow.
0
20
40
60
80
100
120
% Charge input
Temperature
Pressure
Voltage
Figure 2—The voltage, temperature, and pressure rise
with charge time. If the charge rate is high enough, the
voltage eventually drops off.
few milliamps without detrimental
effect. The resistive divider on the
input pins ensured this was met.
So, when the charger current supply
is connected, the ADC reads a clamped,
full-scale value of $FF. This is used to
select Charger mode. Figure 4 shows
the charger functionality. The beauty
of having a purely software-controlled
strategy is that it is easy to change
parameters to suit different battery
voltages or potentially change the
strategy for different types of batteries
or operating environment. It would be
possible to incorporate different
strategies and accommodate a wide
range of battery voltages with the
same software/hardware combination.
An interesting feature of Charger
mode is that separate ADC channels
are connected to both sides of the bat-
tery terminals. This means the charg-
er can detect that no battery is pres-
ent and also, indirectly, the non-
charge battery terminal voltage. I use
the latter to implement an “intelli-
gent” trickle charge algorithm.
When charging current is switched
off, the negative terminal floats to a
value determined by the no-load voltage
of the current source minus the battery
voltage. Though the latter is unknown,
by measuring the trend in voltage, the
software can monitor the self discharge
of the battery over time and reapply a
trickle charge current as required.
The charger uses the PWM drivers
and interrupt handlers from the lamp
controller. This results in a minimum
nonzero PWM duty cycle of 13%,
which is higher than the recommended
5% or so for trickle charge. My modified
trickle charge strategy is to apply 13%
charge for a reasonable time, then
remove current and monitor the self-
discharge of the battery. If the battery
appreciably decays, the 13% charge rate
is reapplied. It would be simple to mod-
ify the kernel software to provide a 5%
or 3% charge rate suggested by some
manufacturers, albeit at a reduced fre-
quency that is immaterial to the battery.
Because the lamp controller drivers
and interrupt handlers work like a
mini operating system, the control
strategy is implemented by some sim-
ple operations (see Figure 4). Interrupt
handlers update program variables to
provide various resolutions of real-
time clock and battery on and off
voltages for both battery terminals.
Neither initialization nor hardware
control operations are necessary.
One seemingly simple function,
establishing certain real-time clock
delays, did require some thought.
Establishing clock delays wasn’t as
simple as testing for equality with a
counter value. The approach fails dur-
ing two conditions, which isn’t an
anomaly of my system, but applies to
systems that use free-running coun-
ters that can be reset. It can be best
explained graphically. Figure 5 shows
how a counter increases monotonical-
ly until it reaches its maximum value
and then resets and continues to
count again. This process lasts until
22
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Listing 1—This certainly isn’t a time delay loop! It exits after a 2-s real-time clock delay or when the push
button is released, whichever comes first. It will still work if you add code that makes the real-time test late.
TSTKEYOFF
EQU
*
LDD
RTFRC
ADDD #TWOSEC
STD
RTSTOP
//Save abs value of t/o as frc tick
value
SEC
TSTKEYO1
EQU
*
//While key not released
//Do some other long time duration activities here if necessary
BRSET KEYSTAT,#KEYREL,TSTKEYO2
LDD
RTSTOP
//Get absolute value of timeout
SUBD RTFRC
//Get distance back to frc value
CPD
#RTMAX
//If it's less than max time, no t/o
BLO
TSTKEYO1 //and not timeout
TSTKEYO2
EQU
*
RTS
//KeyReleased in 2s = key released
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
23
the counter is stopped or forced to
another value by some hardware or
software condition.
Here’s the problem: When a software
time delay is defined in terms of the
free-running counter, there is an oppor-
tunity to miss the exact time-out of
the delay if only equality is checked.
This is because the setup of the counter
compare value or testing procedure is
independent of the counter increment
process. Under certain conditions, the
latency of performing the counter
setup and test would be greater than
the tick time of the counter.
Let’s look at an example. Suppose
you needed a time delay of 100 real-
time counts. To do this with a free-
running counter, software reads the
current counter value, adds 100, and
then stores the result in a variable (call
it StopValue). The delay is implemented
by then comparing the StopValue with
the current value of the free-running
No
Set rapid charging level
Wait 10 min.
Vmax = battery voltage
Wait 5 min.
Vnext = battery voltage
Battery
voltage less than
0.8 V/cell?
(Vnext – Vmax)
<–
∆
V
Signal charging complete
Turn off charger
Wait 10 min.
Battery
voltage <
Vthreshold
Set trickle charging level
Has transfer
time elapsed?
Yes
Turn charger off
Enter Battery
Charger mode
Signal fault
Wait 10 min.
Signal charge restoration
Set trickle charging level
Yes
Vnext >
Vlimit?
Has rapid
charge time
elapsed?
No
No
Yes
Vmax = MAX (Vmax, Vnext)
Yes
Yes
No
Yes
No
Figure 4—The flowchart for –
∆
V battery charger is straightforward.
Battery voltage in red
Charge current in blue
Rapid charge
Modified trickle charge
–
∆
V
Figure 3—Here, you get a good idea of the charging
strategy used in my smart charger.
for lateness, I could not use a simple
equality test; an equality test might
occur after the counter has incre-
mented past the point when its value
is equal to the terminating condition.
The test can’t be a simple subtrac-
tion between the current free-running
counter and the counter value when
the event takes place, because the
free-running counter value could be
numerically greater or less than the
event time as a result of the counter
resetting. The solution is to compute
the difference between the free-run-
ning counter and the event time, and
then compare the result to a predeter-
mined future/past boundary. If the
result lies inside the future/past
boundary, the event time is now or
has passed. The effect of using a
future/past boundary is that it reduces
the dynamic range of the initial offset
by the value of the future-past range.
The
TSTKEYOFF routine in Listing 1
shows a typical code segment that
implements the functionality. This
type of mechanism is an intrinsic
implementation feature of some hard-
ware timer systems such as the time
processor unit (TPU) found on the
highly integrated Motorola MPC555
and MPC565 microcontroller units.
The TPUs on these MCUs have hard-
ware that checks for lateness in the
delay values that software writes to the
hardware comparator. And, the hard-
ware automatically forces the event
associated with the match to
occur, if the event is consid-
ered to be in the past. This
eliminates the software over-
head needed to check for
lateness, such as I imple-
mented in the HC11 code.
Fortunately, the HC11 has
sufficient bandwidth and
hardware resources to imple-
ment a reliable, adaptable
smart charger for NiMH bat-
teries. This has provided me
Richard Soja graduated from Aberdeen
University, Scotland, in 1974, with a
BS in Engineering Science. He is a
senior principal staff engineer at
Motorola, Austin, Texas, and has more
than 17 years of experience designing,
implementing, managing, and sup-
porting hardware and software embed-
ded control applications. Fixing flat
tires and home PC network adminis-
tration are currently interfering with
mountain bike racing. You may reach
him at rsoja128@aol.com.
RESOURCES
Eveready Battery Co.
(800) 383-7323
data.energizer.com/datasheets/
frames.htm
NiMH battery information
Panasonic
www.panasonic.com/industrial/
battery/oem/chem/nicmet/
with a trouble-free, inexpensive
solution that doubles as a light
controller. Recently, I was able
to test the ability to remotely
monitor and control the battery
charger via the Internet.
The debug kernel in the smart
charger allows me access to the
hardware and software resources on the
chip by executing PCBUG11 on my
PIII 500-MHz home PC. From a remote
PC, I am able to log onto the home
PC via a nice freeware package called
Virtual Network Computing (VNC). I
can now have true plug and forget, or
remote control, if I need to observe
and tinker with the charging process!
The integration of the lamp con-
troller and smart charger opens up an
interesting possibility. The controller
could be integrated mechanically
with the battery giving it the smarts
to determine more precisely its state
of charge. Charge state during charge
and discharge could be updated and
stored in the nonvolatile on-chip EEP-
ROM in the form of a time count
indicating the estimated time avail-
able. This would benefit not only
cyclists like myself, but also other
recreational users such as pot-holers,
spelunkers, and professionals such as
firemen and rescue workers.
I
24
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Event occurs when counter
value is inside this range
Initial offset (<$FFFF)
Future
Past
Future
(for next cycle)
Past/future boundaries
Figure 6—Defining a boundary to indicate a time in the past or
future allows checking for lateness.
counter. Remember that a sepa-
rate process updates this counter.
In my case, an interrupt handler
updates the counter. In other
systems, it could be implement-
ed in hardware or by an OS task.
If the loop that compares the
free-running counter with
StopValue uses an equality compare,
then two potential disasters could
occur. One, the latency of the initial
read, add, and store operations could
exceed the delay required. The second
case could occur if the delay loop is
more than just a null loop, containing
other operations, including an inner
delay loop. Then, the real-time count
could advance past the StopValue
point before the comparison is made.
The solution to the read-add-store
initialization is to make sure you add
at least a count value that exceeds the
latency. This technique is used in the
initialization of the real-time clock
interrupt handler to phase displace
the real-time clock interrupt and off-
load battery read routine.
The solution to prevent the second
disaster requires the concept of past and
future time domains. Apart from real-
time clocks, the solution is also used in
systems that have to monitor the posi-
tion of a rotating object, such as the
crankshaft of a car engine or an electric
motor, in which the angular position
of the shaft is reset after every rotation.
The concept of past and future is
delimited by defining a boundary
counter value in terms of an offset
from the current counter value (see
Figure 6). The initial offset defines the
time delay to the event that will take
place. In my case, the event is just a
test for terminating the software
delay loop. Because I needed to allow
$0000
$FFFF
Figure 5—A 16-bit free-running counter starts at zero and counts monot-
onically to $FFFF, then resets to zero. The process repeats forever.
ith the arrival
of the Universal
Serial Bus (USB), PCs
finally have a general-
purpose interface that includes a
power supply line. A device that
draws 0.5 mA can get its power from
the computer or hub it connects to.
Being able to use bus power is con-
venient for users and reduces the
product’s cost and weight.
But, it isn’t quite as simple as
hooking up to the bus supply and
forgetting about it. To help in man-
aging and conserving power, USB has
a few rules and requirements that all
devices must obey. Additionally, there
are design decisions that can ensure
that a device is as flexible and easy
to use as possible.
This article will introduce you to
power management under USB. The
focus is on what designers need to
know about power use for both self-
powered and bus-powered devices.
POWERING OPTIONS
From its beginning, the PC has had
two interfaces suitable for use with
many peripheral types: the RS-232
serial port and the parallel printer
port. Neither includes a power supply
line. Yet the ability to use bus power
is so irresistible that some devices
use various schemes to borrow the
small amount of current available
from unused data or control outputs
in these interfaces.
With an efficient regulator, you can
get a few milliamps at a steady volt-
age from a serial or parallel port.
Another approach is to kludge onto
the keyboard connector, which does
have access to the power supply of
the PC. With USB, you don’t have to
resort to these tricks.
To understand how to take advan-
tage of USB’s power, you need to
know a little about the bus and how
devices connect to it. The full specifi-
cation is available from the USB
Implementers Forum.
Devices connect to the bus in a
tiered star topology (see Figure 1).
Every bus has a host and one or more
hubs. The host controls the bus traffic
and contains a root hub with ports
that face downstream, away from the
host. An external hub has one port
facing upstream, toward the host, and
one or more ports facing downstream.
Downstream-facing ports can connect
to other devices, including additional
hubs. A bus can have up to five exter-
nal hubs in series and up to 127
devices, including hubs, in all. A sin-
gle PC can support multiple buses.
USB 1.x supports two bus speeds,
low speed at 1.5 Mbps and full speed
at 12 Mbps. The USB 2.0 specification
released in 2000 adds a new high
speed at 480 Mbps. Devices of differ-
ent speeds can exist on the same bus.
A USB cable has four wires; D+ and
D– form a half-duplex differential line
that carries the data. Full-speed
devices have a 1.5-k
Ω
pull-up on D+
and low-speed devices have a 1.5-k
Ω
pull-up on D–. High-speed devices
attach as full speed and remove the
pull-up when switching to high speed.
The VBUS wire supplies a nominal
5 V, and Gnd is the ground reference.
The specification classifies devices
as self-powered or bus-powered. A
self-powered device can use whatever
power is available from its own sup-
ply, plus up to 100 mA of bus current.
A bus-powered device doesn’t have
its own supply and is further classi-
fied as high or low power. A high-
26
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Jan Axelson
No Power Supply
Required
USB has opened a
whole new chapter in
the development of
peripherals. In order to
get the most out of it
you need to under-
stand the requirements
covered in USB speci-
fications. Who better to
explain the process
than accomplished
author and USB
expert, Jan Axelson?
w
Powering USB Devices
power device can draw up to 500 mA
of bus current, whereas a low-power
device can draw only up to 100 mA.
These limits are absolute maxi-
mums, not averages.
Some devices need to function
when they aren’t attached to the
host. Digital cameras serve an exam-
ple. These will need their own sup-
plies. To save battery power, a
device can be designed to use bus
power when connected to the bus and
self-power otherwise.
Note that when in the suspend
state (more on the suspend state
later), all devices must sharply reduce
their use of bus current.
INFORMING THE HOST
When a device attaches to the bus,
the host computer performs an enu-
meration that retrieves information
about the device and prepares it for
use. During the enumeration process,
the host requests a series of descrip-
tors, which are data structures con-
taining the information the host will
need for using the device for its
intended purpose.
One of the descriptors is the config-
uration descriptor, which contains
two fields with information about the
device’s use of power (see Listing 1).
MaxPower tells the host how much
bus current the device will use. The
value is in units of 2 mA. This
enables a single byte to store values
up to the maximum allowed
(250, which indicates a
request for 500 mA). Two
bits in the bmAttributes
field tell the host whether
the device is self-powered or
bus-powered, and whether
or not the device supports
the remote wake-up feature
in the suspend state.
A device can support mul-
tiple configurations. For
example, a device can have
both bus-powered and self-
powered options, using self
power when available and
bus power (possibly with
limited abilities) otherwise.
When the power source
changes, the active configu-
ration must change. To
force the host to enumerate the
device again, which enables the
device to send a new configuration
descriptor, a device may contain an
FET that controls power to the bus
pull-up resistor. Switching the FET
off, then back on again, simulates
removal from and reattachment to the
bus. If the device doesn’t have a
switch, you’ll need to remove the
device from the bus before attaching
or removing the power supply.
Each configuration also has subordi-
nate descriptors with additional infor-
mation about the hardware and its
use in the configuration. A device
that supports both full and high
speeds may have an
other_speed_
configuration descriptor for the
speed not currently in use. Like the
configuration descriptor, the
other_
speed_configuration descriptor
has subordinate descriptors.
After reading the descriptors from a
device, a
Set_Configuration
request is sent by the host for a spe-
cific configuration. When there are
multiple configurations, a device
driver in the host may decide which
one to request based on the informa-
tion it has about the device and how
it will be used, or it may ask you
what to do, or it may just select the
first configuration.
After carrying out the
Set_
Configuration request, the device
is configured and ready for use. It can
draw bus current up to the value indi-
cated by the MaxPower field of its
configuration descriptor.
Because no device can draw more
than 100 mA until it’s configured, a
high-power device must be able to
enumerate at low power. It can draw
more than 100 mA only after the host
has requested a configuration with a
greater MaxPower value.
A self-powered device may also
draw up to 100 mA from the bus
before being configured. After being
configured, it can draw up to the
value indicated by MaxPower, with a
maximum of 100 mA. This ability for
self-powered devices to use bus cur-
rent means that the device can be
designed so that the host can enumer-
ate the device even if the device’s
power supply is off or not connected.
VOLTAGES
The nominal voltage between
VBUS and Gnd is 5 V, but the actual
voltage available to a device can be a
little more or significantly less. The
voltage varies slightly depending on
whether or not the port of the hub
supports high-power devices. Table 1
states the minimum and maximum
voltages available at the downstream
ports of the hub.
To allow for cable and other loss-
es, devices should be able to func-
tion with supply voltages a few
tenths of a volt less than the mini-
mum available at the hub’s
connector. In addition, tran-
sient conditions can cause
the voltage at a low-power
port to briefly drop to as
low as 4.07 V.
Because all devices attach
as low power, they all must
be able to enumerate at the
lower voltage allowed at
low-power ports. Also keep
in mind that the power sup-
ply voltage of the bus can be
as high as 5.25 V, which
may increase the consump-
tion of bus current.
A device never provides
upstream power. Even the
pull-up must remain not
powered until VBUS is pres-
ent. A self-powered device
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
27
Root
hub
Hub
Peripheral
Peripheral
Peripheral
Peripheral
Peripheral
Peripheral
Peripheral
Peripheral
Peripheral
Hub
Hub
Figure 1—USB uses a tiered star topology, in which each hub is the center of a star
that connects to additional hubs or other devices.
must have a connection to VBUS
to detect the presence of the bus
voltage even if the device does-
n’t use bus power at all.
Most USB controller chips
require a 5- or 3.3-V supply.
Components that use 3.3 V are
handy because the device can
use an inexpensive, low-dropout
linear regulator. For example,
the Micrel MIC2920A-3.3BS
has a dropout voltage of 370 mV
at 250 mA and a typical quies-
cent current of 140 µ
Α
. If needed, a
step-up switching regulator can boost
the bus voltage at the device to a
steady 5 V supply.
HUB POWER
A hub is a special type of device
that provides power to attached
devices. However, not all hubs sup-
port the attachment of high-power
devices. Moreover, if you want your
bus-powered device to be able to oper-
ate when attached to any hub, the
device must be low power.
If a hub receives power from an
external source such as AC power
from a wall socket, all of its down-
stream ports must be high power
and capable of providing 500 mA to
each port. The ports on a battery-pow-
ered hub or host computer may be
low or high power.
A hub also may be bus-powered.
Bus-powered hubs are limited because
their downstream ports can’t power
high-power devices. This is because
the hub can request no more than
500 mA from the bus and it must use
a portion of this to power itself, leav-
ing less than 500 mA total for its
downstream port(s).
If you connect a high-power device
to a bus-powered hub, the host com-
puter will refuse to configure the
device. In Windows, a message dis-
plays describing the problem and sug-
gesting an alternate port for attaching
the device if possible.
A special case is the bus-powered
compound device, which consists of a
hub and one or more downstream,
unremovable devices. An example is
a hub with an embedded keyboard
and pointing device. In this case, the
MaxPower field of the hub can report
the maximum current required by the
hub’s electronics plus its unremovable
device(s). The configuration descrip-
tors for the unremovable device(s)
report that they are self-powered,
with MaxPower equal to zero. The
hub descriptor indicates whether or
not the hub’s ports are removable.
If a hub and its embedded devices
combined use more than 100 mA, the
hub must switch power to the
embedded devices to ensure
that the compound device
draws no more than 100 mA
until it’s configured.
Because of the confusion that
can result when high-power
devices attach to low-power
ports, PC 2001 System Design
Guide
, written jointly by
Microsoft and Intel, requires
most hubs to be self powered,
with the exceptions of hubs
integrated into keyboards or
mobile systems. [1] Keep in mind
that you can easily find hubs on the
market that use self power or bus
power depending on whether or not
the supply is plugged in.
To provide more flexibility in man-
aging power, the document “USB
Feature Specification: Interface Power
Management” describes a protocol for
managing power at the interface level
instead of just the configuration level.
A draft version of the document is
available from www.usb.org.
SUSPEND CURRENT
Besides the USB limits on operating
current, every USB device has to obey
limits on bus current when in the
suspend state. The suspend state
ensures that a device consumes mini-
mal bus current when the host has no
reason to communicate with it. A
device enters the suspend state when
there is no activity on the bus for a
time or when the host sends a request
to suspend to the device’s hub.
Most suspends are global, meaning
the host stops communicating with
the entire bus. When a PC has seen
no activity for a period, it enters a
low-power state and stops sending the
start-of-frame packets that the host
controller normally sends at least
1/ms on the bus. Upon detecting that
no start-of-frame packet has arrived
for 3 ms, the device enters the sus-
pend state. Low-speed devices don’t
see the start-of-frames, but instead
watch for the low-speed, keep-alive
signals sent 1/ms by their hubs.
A host may also suspend an individ-
ual device by sending a
Set_Port_
Feature request to the hub. The
request can instruct a hub to stop
sending traffic, including start-of-
28
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Device
D + (Full speed) or D – (Low speed)
15k ± 5%
Hub
173 to 230
1.5k ± 5%
V
(3 to 3.6 V)
CC
µA
Figure 2—The allowed current in the suspend state includes the current
through the pull-up and pull-down resistors of the bus, which can be as
much as 230 µA.
Listing 1—This table in firmware contains a configuration descriptor of the device. In the bmAttributes
field, bit 6 equals one if the device is self powered and bit 5 equals one if the device supports remote
wake-up. Bit 7 must be one, and bits 0–4 must be zero. The wTotalLength field includes the length of this
descriptor and its subordinate descriptors.
configuration_descriptor_table:
db
09h
; bLength (9 bytes)
db
02h
; bDescriptorType (CONFIGURATION)
db
22h, 00h
; wTotalLength (34 bytes)
db
01h
; bNumInterfaces (1)
db
01h
; bConfigurationValue (1)
db
00h
; Configuration string (unused)
db
A0h
; bmAttributes (bus powered,
remote wakeup)
db
0Dh
; MaxPower (26mA)
frames or low-speed keep-alive sig-
nals, to a named port. The specifica-
tion defines this activity as a selec-
tive suspend.
The amount of current a suspended
device can draw depends on informa-
tion in the descriptor for the active
configuration. A high-power device
that supports remote wake-up can
draw up to 2.5 mA if the host has
enabled the remote wake-up feature.
All other devices can draw just
500 µ
Α
. The 2.5-mA and 500-µA lim-
its are averages over intervals of up to
1 s, so brief peak currents can be
greater. A device that cannot meet
these limits needs its own supply.
Five hundred microamps isn’t
much, especially when you consider
that this number includes the cur-
rent through the pull-up. As Figure 2
demonstrates, the pull-up current
flows from the device’s pull-up sup-
ply, which must be between 3 and
3.6 V, through the 1.5-k
Ω
pull-up
and the 15-k
Ω
pull-down of the hub,
to ground. In the worst case, with a
pull-up voltage of 3.6 V and resistors
that are 5% less than their nominal
values, the pull-up current is
230 µ
Α
, leaving just 270 µ
Α
for
everything else.
Although high-speed devices don’t
use pull-ups when configured to use
high speed, when the device enters
the suspend state, it must switch to
full speed with a pull-up. Therefore,
high-speed devices have the same
limit on available current.
Every device also must meet the
500 µ
Α
limit if the host happens to
suspend the bus before configuring
the device. To support the suspend
state, USB-capable microcontrollers
have the ability to shut down and
draw little current, and most can send
a remote wake-up after detecting
activity on an I/O pin. If you’re inter-
facing a USB controller without a
CPU to a generic microcontroller, you
need to be sure that your microcon-
troller and attached circuits don’t
exceed the limits.
A device should begin to enter the
suspend state after its bus segment
has been in the idle state (with no
start-of-frames or low-speed keep-
alive signals) for 3 ms. Note that the
device must be in the suspend state
after its bus segment has been in the
idle state for 10 ms.
Controller chips vary in the amount
of firmware support they require to
detect when to enter the suspend
state. For the Cypress Semiconductor
enCoRe series, the 1-ms interrupt
routine typically checks a bus activity
bit and increments a counter if no
activity has been detected. When the
count reaches three, the firmware sets
a suspend bit that places the chip in
its low-power suspend state. With the
Cypress EZ-USB series, it’s more auto-
mated. The hardware detects when
it’s time to enter the suspend state
and triggers an interrupt. The firmware
then performs any needed functions
and sets a bit that causes the device
to enter its Low-Power mode.
RESUMING AFTER SUSPEND
When a device is in the suspend
state, two events can cause it to
enter the resume state and restart
communications. Any bus activity
will cause the device to resume. And
if the host enables the remote wake-
up feature, the device may request a
resume at any time.
The host resumes by placing the
bus segment in the resume state for
at least 20 ms. The resume state is
equivalent to the data K bus state; D+
is low and D– is high at full speed,
and D+ is high and D– is low at low
speed. The host follows the resume
with a low-speed END-OF-PACKET
signal. (Some hosts incorrectly send
this signal after just a few hundred
microseconds.) The host then
resumes sending start-of-frame pack-
ets and other communications
requested by the device’s driver.
A device causes a resume by driving
its upstream bus segment in the
resume state for between 1 and 15 ms.
The device then places its drivers in a
high-impedance state to enable
receiving traffic from its upstream
hub. A device may send the resume
any time after the bus has been sus-
pended for at least 5 ms. The host
allows devices at least 10 ms to
recover from a resume.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
29
Upon resuming, the device executes
the instruction following the last
instruction that executed before sus-
pending. The controller’s hardware
normally handles resuming and
requires no firmware support.
On some early Intel host con-
trollers, a suspended port at the host
didn’t respond correctly to a remote
wake-up. In addition, using remote
wake-up requires workarounds under
Windows 98 Gold (the original
release), 98 SE, and Me. With these
operating systems, the device may
wake up properly, but the device driv-
er in the PC isn’t made aware of it, so
communications can’t resume.
The white paper “Understanding
WDM Power Management,” available
from www.usb.org, details the prob-
lem and solutions. [2] In short, a
device using these operating systems
shouldn’t place itself in the suspend
state unless the host requests it; and
the device driver requires additional
code to ensure that the wake-up
completes successfully.
OVER-CURRENT PROTECTION
As a safety precaution, hubs must
be able to detect an over-current con-
dition, which occurs when the current
used by the total of all devices attached
to the hub exceeds a preset value.
When the port circuits on a hub
detect an over-current condition, they
limit the current at the port and the
hub informs the host of the problem.
The specification doesn’t name a
value to trigger the over-current
actions, but it must be less than 5 A.
To allow for transient currents, the
over-current value should be greater
than the total of the maximum allowed
currents for the devices. Seven high-
power, bus-powered downstream
devices can legally draw up to 3.5 A.
So, a supply for a self-powered hub
with up to seven downstream ports
would provide much less than 5 A at
all times unless something goes wrong.
30
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
SOURCES
Cypress Semiconductor
(408) 943-2600
Fax: (408) 943-6841
www.cypress.com/usb
MIC2920A
Micrel Semiconductor, Inc.
(408) 944-0800
Fax: (408) 944-0510
www.micrel.com
REFERENCES
[1] Intel Corp. and Microsoft Corp.,
[2] K. Koeman, “Universal Serial
Bus: Understanding WDM Power
Management,” V.1.1, August 7,
2000.
RESOURCE
USB 2.0 specification and related
documents: www.usb.org/
developers/docs.html
Jan Axelson is the author of “USB
Complete: Everything You Need to
Know About USB Peripherals,” now
in its second edition. Portions of this
article are adapted from
USB
Complete. Jan hosts a web page with
information for USB developers at
www.Lvr.com/usb.htm.
A bus-powered
hub must have cir-
cuits that can cut off
power to its down-
stream ports. A sin-
gle switch may con-
trol all ports, or the
ports may switch individually. PC
2001 System Design Guide
requires
the ports on bus-powered hubs to
have individual switches. A self-pow-
ered hub must support switching the
entire hub to the powered off state,
and may also support power switch-
ing to its downstream ports.
The specification allows a device to
draw larger inrush currents when it
attaches to the bus. This current is
typically provided by the stored ener-
gy in a capacitor downstream from
the over-current protection circuits.
I
Hub port type
Minimum voltage
Maximum voltage
High power
4.75
5.25
Low power
4.40
5.25
Table 1—The VBUS voltage at a low-power port can be as low as 4.4 V.
hen I sat down
to write this article
last fall, the leaves on
the trees had not yet
turned their autumn colors, but the
beauty of the flowers in our garden
beds was certainly on the wane. It was
a dry summer, particularly punishing
for farmers, and our gardens weren’t
particularly splendid last year. Not
that I didn’t try to keep them well
watered, it’s just that it’s hard to beat
a steady dose of rainwater.
We’re fortunate to have built a home
on a large lake. Twelve years ago, we
chose the lot based
mainly on recreational
concerns—swimming,
canoeing, and such. I
became seriously inter-
ested in gardening about
five years back, and
decided to install an irri-
gation system to make
use of the unlimited
supply of “free” water.
Our lot is about 25
′
above the lake’s level. As
any mechanical engineer
will tell you, it’s a lot
easier to “push” water
than it is to “pull” it, so
I installed a 0.75-hp jet
pump at the water’s edge. I decided
against using a pressure tank and
switch, as the water would be needed
only when the pump was switched
on, and the maximum continuous
flow rate was desirable.
Because most of the rough land-
scaping had been done when the
house was built, I decided it would be
too much effort and expense to bury
irrigation lines throughout the 0.75
acre of lawn and gardens that I have.
Instead, I ran 1.5
″
plastic pipe on the
surface, along the side border of my
property. Six valves/garden hose fit-
tings are spaced along the 400
′
length.
For a number of years, I was content
to run down to the electrical panel in
the basement to switch on the pump
when I wanted to do some watering.
Besides being inconvenient, occasionally
I’d shut off the water valves when fin-
ished and then forget to return to the
basement to turn off the pump. One
year I damaged the pump by leaving it
on for several days! Also I was getting
lazy; I didn’t like the trouble of hook-
ing up a hose, unraveling 100
′
of it
into the desired position, attaching a
sprinkler head, and then having to
walk all of the way back to the other
end to turn on the water valve.
I decided what I needed was a con-
troller that allows me to program spe-
cific watering times and durations.
Units like this are commercially
available, of course, but I also wanted
to be able to control the water using a
small keyfob transmitter while I put-
tered around in the gardens.
32
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Brian Millier
An RF-Controlled
Irrigation System
With access to a
steady water supply,
Brian’s garden should
flourish in even the dri-
est of times. Having
caught wireless fever,
he set out to use an
AVR and some RF
products to man the
pump and close the
valves. Now, watering
only takes a press of
the green thumb.
w
Photo 1—Here’s the actual controller/receiver sitting in my family room.
Just visible in the background is a glimpse of the lake—the source of water
for the gardens. Not visible is the AC adapter used for power or the power
relay, which is located at the electrical panel in the basement.
In my last article, I described a
wireless MP3 player, which used low-
cost UHF transmitter/receiver mod-
ules from Abacom Technologies
(“Listen Everywhere,” Circuit Cellar
134). I was pleased with their per-
formance and technical support from
Abacom, so I decided to check out
Abacom’s products again.
I wanted the transmitter to fit in a
keyfob, so I chose the AT-MT1-418
AM transmitter module, which is
about the size of a penny. I also chose
Abacom’s keyfob transmitter case,
which comes in various switch
cutout configurations.
I decided to use a sensitive receiver
because I anticipated a low transmit-
ted signal level given such a small
transmitter. The QMR1 Quasi
AM/FM superhet receiver module fit
my needs. I particularly like this
module because its 1-square-inch SIP
mounts easily on a circuit board by
pins on 0.1
″
centers. I like one-stop
shopping, so of course I was pleased
to be able to get Holtek encoder/
decoder chips from Abacom, as well.
I’ll describe the chips in more detail
later in the article.
CONTROLLER/RECEIVER
If you’ve read my recent articles, it
should come as no surprise that I
used an Atmel AVR controller chip,
the AT90S8535-8PC (40-pin DIP pack-
age), for this project. This device con-
tains four 8-bit ports, eight 10-bit
ADC channels, 8 KB of flash memory,
and 512 bytes each of data EEPROM
and RAM. Like most AVR devices,
this one is easily serially programma-
ble in-circuit. You may want to refer
to my article, “My fAVRorite Family
of Micros” (Circuit Cellar 133) for an
overview of this family, along with
the details of a free ISP programmer
for these chips.
I must admit up front that I proba-
bly could have done this project with
the smaller AT90S2313 by multiplex-
ing some of the I/O pins and writing
the program in assembly language. I
decided it was more productive for
me to spend the extra $6 (Can $) on
the ’8535, whose larger flash memory
would allow me to program in BASIC,
using the BASCOM AVR compiler.
Figure 1 is a schematic of the con-
troller/receiver. Let’s start by looking
at the user interface. The user inter-
face consists of a 4 × 20 LCD and four
push buttons. The display is operated
in the common 4-bit mode; in this
case, because it saved some wiring,
not because of a shortage of I/O pins.
The four push-button switches are
individually strobed by port pins
PC0–3 and sensed by the INT1 input
of the ’8535. I hooked up the switches
this way because I originally drove
the LCD using the same four port C
lines. I had been saving the ADC
inputs of port A for future use, but
later changed my mind and switched
the LCD over to port A, leaving this
switch circuit intact.
The four push-button switches
operate this unit the same way that
many small electronic devices work.
There is a Menu button to scroll
through several menus as well as a
Select/Cursor button. The buttons are
used to position the cursor within a
time field for adjustment purposes or
to select a particular value when fin-
ished changing it. Finally, there are
plus sign and negative sign buttons
used to increment or decrement the
current parameter.
I chose to implement the real-time
clock in the software. One reason I
initially picked the ’8535 over the
slightly less expensive ’8515 is because
it includes a third timer, which may
be driven by a 32,768-Hz watch crys-
tal. I must say that my attempts to
implement the RTC using this feature
gave me some problems! Atmel’s
datasheet for the ’8535 advises you to
merely connect the 32,768-Hz watch
crystal between the TOSC pins 1 and 2
with no capacitors to ground. [1]
When I did this, I could see a reason-
able 32,768-Hz sine wave signal on
either crystal pin with my oscilloscope
using a 10× probe. I soon discovered,
though, that my clock was losing
about 1 min./h. After troubleshooting,
I found that the crystal oscillator
waveform contained serious glitches
coinciding with LCD screen refreshes.
At that point, I was using the port
pin adjacent to TOSC1 to drive the
LCD ENABLE pin. Moving the LCD
ENABLE pin over to port A eliminat-
ed the glitches, but the clock was still
slow. This was odd because I could
not see anything wrong with the crys-
tal waveform with my oscilloscope,
and the built-in frequency counter in
the oscilloscope indicated that the fre-
quency was “bang-on.”
So next, I contacted Mark at MCS
Electronics to see if he had run into
the problem. He mentioned capacitors,
which made me think that capaci-
tance to ground was probably needed
(contrary to the datasheet). It turns
out that my oscilloscope was provid-
ing the necessary capacitance, but
only when it was hooked up. Adding
22-pF capacitors to ground cured the
problem, at least with the particular
crystal I was using. However, for this
project, I decided to play it safe and
implement the RTC using Timer0 of
the ’8535 clocked by the 4.194304-MHz
crystal of the CPU, which works per-
fectly. A side effect of this was that I
couldn’t use BASCOM’s intrinsic real-
time clock function and instead had
to write my own routine.
My pump draws about 10 A when
running (much more when starting),
so I chose a Potter & Brumfield
T9AP5D52-12, which is inexpensive
and rated for 20-A continuous current.
A small 2N3904 transistor is all that
is needed to handle the 200 mA that its
coil requires. This sealed relay is small.
I haven’t used it long enough to know
how well it will hold up, so the jury
is still out on this component choice.
The controller/receiver is powered
by a 9-VDC adapter followed by a
78L05 regulator. The actual output of
the adapter is closer to 12-V, and is
enough to operate the relay coil.
Photo 1 shows the controller in place
in my family room.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
33
Photo 2—The PCB that I fabricated for the transmitter
sits below the keyfob case. You can see a bit of the thin
black wire, which forms the antenna, connected to the
tiny transmitter module.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
35
The wireless part of the controller
consists of an Abacom QMR1 receiver
followed by a Holtek HT12D decoder
chip. This receiver is one of the choic-
es recommended for use with the AT-
MT1 AM transmitter that I use. The
datasheet that comes with the pack-
age (available soon on www.abacom-
tech.com) calls the QMR1 a quasi-
AM/FM receiver module. The
datasheet doesn’t spell out if it also
works with FM transmitters, but it
sounds like it would.
In any AM transmitter/receiver
link, one thing for certain is that the
receiver will spit out a stream of
noisy data during much of the time
when its companion transmitter is
not transmitting. The QMR1 is sensi-
tive (RF sensitivity specification is
–110 dBm) and it has no squelch cir-
cuitry to suppress spurious output sig-
nals arising from any RF interference
that it might receive. With cell phone
towers cropping up all over the coun-
tryside, even my rural home is proba-
bly not “RF-quiet” anymore. I defi-
nitely see lots of noise output from
the QRM1 receiver module.
My intention is to emphasize the
need for some form of error detection/
data formatting in any AM RF link.
What I haven’t mentioned is that the
circuitry in the receiver that recovers
the data from the RF signal (called the
data slicer) is choosy about the form
of data modulation that it will accept.
For example, most data slicers work
reliably only if there is a roughly even
distribution of zeros and ones in the
datastream, even within the short-
term such as the time taken to send
1 byte of data. This means that you
cannot, for example, just feed in the
signal from a UART to an AM trans-
mitter, and expect to hook up a
UART to the receiver output.
Instead, Manchester encoding is
generally used because it guarantees
an equal number of zeros and ones in
the datastream, regardless of the par-
ticular data being sent. Furthermore,
it is good practice to send the same
data several times and check that it
matches when it comes out of the
receiver. A final precaution could
include some form of checksum or
better still, a CRC byte in the data
packet to further verify the integrity
of the received data.
Another concern is the amount of
time it takes the receiver to adjust
itself to the strength of the incoming
signal or wake up from an idle state if
that feature is present in your receiv-
er module. To allow for this, the
transmitter must send out a short
stream of known data, called a pream-
ble, to allow the receiver to get ready
for data reception, so to speak.
This is a lot tougher than your
average RS-232 serial data link! There
are many books that cover in depth
the theory of reliable RF data commu-
nication; An Introduction to Low
Power Radio
by Peter Birnie and John
Fairall is a good starting point for
those of you starting out in this area. [2]
ENCODER/DECODER
To address these concerns, it
made sense to use the inex-
pensive line of encoder/
decoder devices from Holtek
(HT12D/E) rather than roll my
own. These matching chips
address the concerns, at least
for applications that need only
to transmit the status of a
small number of switches.
There are a number of good
reasons for choosing this
device. The HT12E encoder
chip consumes only about
0.1 µA in Standby mode, so it
can be left permanently con-
nected across the small trans-
mitter battery. It comes in a
small, 20-pin SOP and fits in a
small transmitter case (the
same could be said for the
Atmel ATiny and smaller PIC
processors). To reduce parts
count and cost, it uses a single
resistor to set its internal RC
clock. RC clocks are not known
for their frequency stability;
the design of this encoder/
decoder pair allows the receiv-
er to be able to lock onto the
Figure 1—The Atmel 8535 AVR controller is at the center of the action of the irrigation controller. An Abacom QMR1 receiver
takes care of the wireless reception functions. The LCD operates in 4-bit mode.
36
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Choosing a battery for the trans-
mitter wasn’t difficult. There seems
to be only two choices in small bat-
teries: 3.6-V coin cells and the 12-V
alkaline batteries used in many
remote car starters. The HT12E
encoder would have worked fine at
3.6 V, but the output power of the
transmitter module would have been
low. Thus, I chose the 12-V batteries.
THE FIRMWARE
One of the reasons for choosing the
AT90S8535 instead of one of its little
brothers, like the ’2313, was to allow
me the luxury of programming the
firmware in BASIC. From past experi-
ence, I thought there was not enough
space in the 2-KB flash memory of the
’2313 for an application such as this
using compiled BASIC.
I wrote the firmware using the
MCS Electronics BASCOM-AVR com-
piler. It took up more than half,
4800 bytes, of the 8192 bytes of flash
program memory, confirming my
fears that it would not have fit into
the memory of the smaller ’2313
device. Incidentally, the demo version
of the BASCOM-AVR is available free
from MCS Electronics, and is fully
functional apart from the fact that its
program size limit is 2 KB.
As I mentioned earlier, problems I
had using Timer2 (designed for RTC
purposes) of the ’8535 prevented me
from using the built-in RTC routines
in the BASCOM-AVR. This had an
upside: The RTC routines
needed by this applica-
tion do not require week,
month, or year, so they
use less memory space
even though they were
coded in BASIC (Note:
The BASCOM intrinsic
RTC function is done in
assembly language).
Most of the firmware
takes care of the user
interface. An LCD with
four push buttons is easy
to build, but takes up
considerable program
space to implement a
friendly user interface.
There is a routine that
allows you to set the
transmitter’s data clock frequency
even though it may vary considerably
over time or temperature. Refer to
Figure 2 for the schematic of the
transmitter module.
Both the encoder and decoder sam-
ple eight lines (A0 through A7), which
act as device address inputs. That is
to say, a given encoder/decoder pair
can be set to operate at one of 256
discrete addresses. This strategy, for
example, prevents your neighbor’s
remote control from operating your
garage door opener.
Addressing can be done with a dip
switch, jumpers, or by cutting traces
on a PCB. Modern encoder/decoder
chipsets used in remote car starters
use, by necessity, a much more com-
plex addressing scheme because
there’s a much greater chance of false
triggering by other, unintended trans-
mitters in the vicinity. Obviously,
this leads to worse repercussions.
The data packet sent by the HT12E
consists of the 8-bit address followed
by a 4-bit data field corresponding to
the state of up to four switches con-
nected to inputs D8–D11. The
datasheets for the HT12D/E devices
don’t mention a preamble being sent
before the data, nor do they mention
a checksum nor CRC bytes for data
checking. [3, 4]
In place of this, the data packet is
transmitted three times for each
switch closure and then checked for
equality by the receiver. Holding the
switch down for any
more than an instant,
will result in the repeti-
tion of the datastream.
Presumably this is how
the lack of a preamble is
handled—the receiver
likely misses out on the
first occurrence of the
data packet, but catches
subsequent ones.
The Abacom AT-MT1
transmitter has a maxi-
mum data transmission
rate of 2400 bps. There-
fore, I set the encoder’s
oscillator of the HT12E
to 2 kHz by using a 1.5-
M
Ω
resistor across OSC1
and OSC2. [4]
The AT-MT1 transmitter is a two-
wire device. It is not modulated per se;
instead it is powered up and down in
step with the datastream. The SAW
oscillator used in this module is able
to turn on and off quickly—fast enough
to handle the maximum data rate.
The output of an encoder chip is sup-
posed to directly power the AT-MT1,
according to its datasheet. Although
the data output pin of the HT12E is
capable of sourcing up to 1.6 mA, the
AT-MT1 requires up to 9 mA at 12 V
to operate. So, in this case, I had to
add a 2N3904 emitter follower to pro-
vide the necessary current boost.
I intended to use a Linx Splatch
antenna, which is a small PCB con-
taining a 418-MHz antenna and
ground plane. Unfortunately, this
small antenna radiated much less sig-
nal than a quarter-wave whip antenna
and would not provide the range I
wanted. However, it wasn’t too great
a loss because I was having trouble
fitting everything into the keyfob
anyway. I ended up using a 6.25
″
piece of flexible wire as an antenna,
which just hangs out of the keyfob
case and doesn’t mind being stuffed
into my pocket.
Photo 2 is a close-up of the trans-
mitter PCB, which has to fit in the
case and line up with the switch
cutouts. I included the PCB layout in
PDF format along with the firmware
files, because the design of the trans-
mitter PCB is tedious.
Figure 2—There isn’t too much to the schematic diagram of the keyfob transmitter.
However, getting it to fit into the small keyfob was another matter!
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
37
clock to the current time. Another
routine enables you to enter up to six
programs. Each program consists of a
time, action (pump on/off), and a
Daily or Once-Only mode. And, a
final menu item allows you to turn
the pump on and off immediately
from the controller.
The six user-defined programs are
stored in EEPROM, so that they sur-
vive a power failure. However, because
the CPU (and therefore the RTC) will
stop if the power goes off, this is a
moot point, unless I add a battery
backup for the controller’s CPU.
When a command comes in from
the wireless transmitter, the valid
transmission (VT) line on the decoder
will go high, and its four data output
lines will reflect the state of the four
buttons on the keyfob transmitter. The
VT signal is fed into the INT0 inter-
rupt input of the ’8535 (through RC
filtering to prevent false triggering).
An interrupt service routine checks
the state of the decoder’s four outputs
and turns the pump on or off accord-
ingly. Although I fitted four buttons
into the transmitter and allowed for
all four in the controller, the firmware
currently responds to only two
switches—pump on and pump off. I
will likely think of some other device
to hook up to this in the future.
TIME’S UP
There’s no doubt that it’s much less
expensive to buy a remote control
module off the shelf than it is to build
your own, if you can find one that suits
your needs. However, if your require-
ment is unique or you can combine a
few functions into one unit, then the
satisfaction of designing your own
unit makes it all worthwhile. I find
building these wireless gadgets addic-
tive. In the back of my mind, I’m
already thinking of my next project: a
controller for air exchanger in my
home using indoor/outdoor tempera-
ture and humidity sensors and a
power line modem.
I
SOURCES
AT90S8535-8PC Microcontroller
Atmel Corp.
(714) 282-8080
Fax: (714) 282-0500
www.atmel.com
HT12D/E Decoder chip
Holtek Semiconductor Inc.
(510) 252-9880
Fax: (510) 252-9885
www.holtek.com
BASCOM-AVR Compiler/
programmer
MCS Electronics
31 75 6148799
Fax: 31 75 6144189
www.mcselec.com
To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2001/138/.
REFERENCES
[1] Atmel Corp., “8-bit AVR
Microcontroller with 8K Bytes
In-System Programmable
Flash—AT90S8535
AT90LS8535,” rev. 1041GS,
September 2001.
[2] P. Birnie and J. Fairall, An
Introduction to Low Power
Radio
, Character Press Ltd., UK,
1999.
[3] Holtek Semiconductor Inc., “2
12
Series of Decoders,” July 12,
1999.
[4] ———, “HT12A/HT12E 2
12
Series of Encoders,” April 11,
2000.
Brian Millier is an instrumentation
engineer in the Chemistry Department
of Dalhousie University, Halifax,
Canada. He also runs Computer
Interface Consultants. You may
reach him at brian.millier@dal.ca.
Author’s Note: I want to thank John
Barclay of Abacom Technologies for
the support and samples that helped
out significantly while I was putting
this article together.
he QNX real-
time operating sys-
tem (RTOS) isn’t new.
It’s been around since
the early 1980s. When I first encoun-
tered QNX in ’87 I thought, “this is a
lot better than Windows.” Today, it’s
still better than Windows for real-
time applications. In addition, QNX
has added a lot of GUI applications,
making it competitive on the desktop.
Since September 2000, we’ve been
able to download QNX real-time plat-
form (RTP) for evaluation, prototyp-
ing, personal use, or other noncom-
mercial purposes at no charge. And,
since July 2001, RTP has included the
x
86 version of QNX Neutrino 6.1.
Throughout the article, I will refer to
these as QNX unless a distinction
needs to be made.
What is QNX? QNX is a RTOS with
a microkernel architecture. It supports
MIPS, PowerPC, SH4, StrongArm, and
x
86 hardware. It is scalable from con-
strained embedded to multiprocessor
platforms. The architecture provides
multitasking, priority-driven preemp-
tive scheduling, synchronization, and
TCP/IP protocol. Utilities including
PPP, DHCP, NFS, RPC, and SNMP are
provided as well.
QNX has native message-based net-
working called Qnet. The Photon
microGUI windowing system is a
GUI with a small memory footprint.
For GUI applications, there is also an
integrated development environment
called Photon Application Builder
(PhAB), which reminds me of Visual
Basic with drag-and-drop controls.
And, don’t forget about the self-host-
ing capabilities that simplify develop-
ment. QNX is not Unix but they have
a lot in common. QNX even uses a
version of the GNU GCC compiler.
For anyone who wants to do hard
real-time work, QNX is a good place
to start. If you’ve ever attempted to
do real-time work under Windows, you
know how difficult it can be to get
deterministic timing. Windows CE is
a possibility if you want to drop $2500
(US $) in a hurry for Platform Builder.
For simple jobs, you can jump back-
ward to MS-DOS, but then you start
to have problems with software and
hardware support.
Linux is a possibility for real-time
applications, but you have to make a
tough choice. Which real-time imple-
38
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Duane Mattern
Exploring QNX Neutrino
Yes, QNX has been
around for a while.
But, that doesn’t mean
it’s outdated nor that it
isn’t a helpful solution
to some of today’s
real-time problems.
Duane takes us step
by step through every-
thing from download-
ing the eval copy to
displaying bootable
images in real time.
t
Main menu
Submenu
Editors
Notepad, jed, Vim
Utilities
File Manager, Image Viewer, Snapshot, phcalc, terminal, ica manager
MultiMedia
Mixer, MediaPlayer, Real Player G2, Real Player Readme
Internet
Voyager, Vmail, Phirc, Tin
Development
PhAB, DDD Debugger
Games
Columns, Doom shareware, Peg, Othello, Solitaire, Video Poker, Quake3 Arena
Software
Package Manager, Install Software from QNX, Manage My Software
Configure
Networking, Appearance, Video Display, Shelves, Font Server, ScreenSaver, Active
Print Jobs, Audio Level, Input Cfg
Help
Starts Voyager web browser with local help in HTML
Quick Guide
Brings up welcome screen
Shutdown
Ends Photon session, shuts down system, and reboots
Table 1—These QNX applications are available from the shelf in the Photon GUI.
mentation of Linux do you want? There
are many choices to evaluate. The list
includes RTLinux from FSMLabs,
Embedix from Lineo, Hard Hat from
MontaVista, TimeSys, and others. [1]
The different approaches to scheduling
and the supported hardware complicate
the choice. If you want to start quickly
and for free with a proven RTOS, then
QNX is a good candidate to explore.
INSTALLATION
Let’s get started by exploring the
x
86 installation. I’ve installed QNX
on generic 1997 PC hardware, a Dell
Dimension 4100, Dell Inspiron 7500
notebook, as well as the PC/104 plat-
form (Panther/K6 from VersaLogic
(see Photo 1)). As with any installa-
tion, there are quirks. Here are some
recommendations if you want to get
started quickly.
First, get a second x86 plat-
form and install QNX as the
only OS on that platform.
With a Pentium processor,
PCI bus, PS2 mouse, IDE
hard disk, and 32-MB RAM,
you shouldn’t have any
problems with the installa-
tion. Use a keyboard/video/
mouse (KVM) switch to
avoid having to give up
desktop space. If your old
hardware isn’t supported by
QNX, look for supported
hardware on eBay. I picked
up a fully supported VGA
card for $20 on eBay.
If you don’t want to use a sec-
ond box, I suggest installing QNX
into a Windows partition with a
FAT file system. This way, you
won’t have to work those ugly
issues with the boot sector and
will avoid the possibility of cor-
rupting your system. Sure, you’ll
have to use a boot floppy to boot
to QNX. But the floppy isn’t
required after the OS is running,
so you won’t suffer performance
problems because of floppy I/O.
On my Dell Dimension, I use
the Windows boot loader to
select between Win2k and
Linux. If I want to boot QNX, I
use the QNX boot floppy.
My third recommendation is
to ante up the $30 for the QNX CD.
Yes, you can save a few bucks by
downloading the 29-MB Windows
installation, but it includes only the
basic operating system. It does not
include all of the packages, so you’ll
have to install the packages over the
Internet. The download for the
CDISO image is 442 MB. It is much
easier and quicker to do the installa-
tion with the QNX CD.
It’s always good advice to make a
QNX boot floppy to use for recovering
from problems that might occur after
making changes to your system.
I have one last suggestion. I don’t like
to boot directly into the Photon GUI
because it becomes difficult to maneu-
ver in the GUI if you have a problem
with your mouse (like I did with a
Logitech bus mouse). Fortunately, there
are keyboard shortcuts you can use.
The “Windows” key pulls up the menu,
and then you can use the cursor keys
to select items from the menu. From
a window, you can use the tab, space,
and return keys to select the various
menu items. To avoid this, I prefer to
boot into a terminal interface and then
start Photon with the
ph command.
You can install QNX to its own
partition, but you’ll have to work
through the boot sector issues. The
problems you may have depend on
six conditions: which operating sys-
tem(s) you have, the order in which it
was installed, which boot loader you
want to use, if you have more than
one hard disk, the size of your hard
disk, and the age of your BIOS.
There isn’t room here to cover all
of the possible combinations (Win9x/
NT/2k, Linux, QNX, etc.). A news-
group archive site (such as groups.
google.com) can be a good place to
search for this information.
For example, go to comp.os.
qnx and search for “dual
boot.” If you decide to
install QNX on its own par-
tition, you’ll have to boot
your system from the CD.
If your BIOS doesn’t sup-
port booting from a CD, you
may use the Make Floppy
menu item displayed in
Photo 2. After you boot QNX,
you may complete the instal-
lation from the CD to a sep-
arate hard disk partition. If
you have problems with the
installation, try pressing the
escape key at the beginning
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
39
Photo 1—This is the Panther/K6, low-power (no cooling fan)
board on a PC/104 stack with a Sealevel serial card, all housed
in the VersaLogic development box. Note the IDE-to-
CompactFlash adapter in the foreground.
Photo 2—You can install QNX Neutrino from Windows
to a Windows FAT partition. The installation window
also gives an option to make boot floppy disks, should
you want to install the system on a QNX partition and
your system does not support booting from a CD-ROM.
Photo 3a—After you have booted QNX Neutrino and started the Photon GUI, you’ll
see a number of familiar applications, including a web browser (Voyager), calculator,
console, and online help. Photo 3b—The Launch push button in the lower left cor-
ner provides access to a menu of commands (called the shelf). From the shelf, you
can configure most application settings.
a)
b)
After booting into QNX, you will
see a log on screen within the Photon
GUI. Next, a welcome screen appears,
which will provide an introduction
and overview of the system (upper
left-hand corner of Photo 3a). Photo
3a shows the Photon GUI with several
windows open, including the Voyager
web browser, calculator, and a termi-
nal window.
One of the first things to do is con-
figure your network. You can use the
network configuration tool from the
shelf. The shelf is the menu shown in
the enlarged view in Photo 3b. The
network configuration tool is a front-
end to
phlip, the Photon TCP/IP, and
dial-up configuration utility.
It should start with Devices, Dial-
ups, and Network tabs (see Photo 4). If
you don’t have a Devices tab, it means
that the network driver did not auto-
matically start. But, this isn’t proof
that your hardware isn’t supported,
rather, it probably means QNX couldn’t
do it automatically. You’ll have to
troubleshoot the network start up.
The debug process is outlined in the
QNX welcome screen, under “Setting
Up Networking” and “Quick Start—
Direct Internet Connection.” The lat-
ter brings up an HTML page in the
browser and provides a “Network
Troubleshooting” section. You can see
if the driver is running in a terminal
window by piping the output from the
process status command (
ps) to grep
and searching for
io-net as follows:
40
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
of the installation when prompted.
This option uses a boot image that
does not use DMA and may solve
some installation problems.
To avoid discussing issues with
boot loaders, let’s explore the instal-
lation of QNX to a Windows FAT par-
tition. After inserting the QNX CD
under Windows, the procedure will
start if the CD auto-run feature is
enabled. The installation procedure
detects which Windows OS you are
using. If you’re running NT or
Win2k, the installation informs you
about installing to a FAT file system
and booting from a floppy. If you pro-
ceed with the installation to the
FAT32 partition, you’ll be prompted
to insert a floppy disk.
You may reboot into QNX after the
installation is complete. After boot-
ing, QNX will locate the installation
on hard disk. QNX mounts a QNX
file system that is located in a file on
the FAT file system. This whole pro-
cedure is fully explained in the
readme.txt file on the QNX
Neutrino CD.
Photo 4—From the shelf, you can configure the net-
work settings. If there is a Devices tab, it means that
the system has automatically recognized your network
card during the boot process. If this tab is missing,
you’ll have to manually start the driver for your network
card, assuming that it is supported.
ps | grep io-net
You can use
nettrap to detect net-
work cards and start the driver, but if
nettrap didn’t start the driver origi-
nally, you’ll have to do some manual
work. Compare your network driver
chipset to the supported chipsets dis-
played on the QNX web site. When
you find an appropriate driver, you
can force the system to use that driver
using
io-net.
In any event, the network configu-
ration tool allows you to assign a
fixed IP address or have one assigned
using DHCP. At this point, you
should have a functional desktop
machine. Likely, next you’ll want to
invoke the package manager to install
the various other utilities and tools,
like a C and C++ compiler.
TOOLS
You won’t be able to use the C
compiler until you install it from the
package. Follow the options under the
package manager for straightforward
directions. You can connect to the
www.circuitcellar.com
Issue 138 January 2002
41
software repository on the QNX web
site or on the QNX CD, as illustrated
in Photo 5. The packages include
Korean, Japanese, as well as Chinese
language supplements. QNX RTP
supports C and C++ with the GCC-
2.95. There is a
qcc command, how-
ever,
qcc is a front-end to GCC.
The purpose of
qcc is to provide an
abstraction layer to mask the differ-
ences between various compilers (GNU
GCC, Watcom, and Metrowerks).
There is also
cc front-end, which is
used to mask the differences between
available compilers. This front-end
also invokes the appropriate compiler
(C or C++) based on file extensions
and currently it invokes GCC/G++.
For project code management, the
make, CVS, and RCS utilities are part of
this QNX distribution. If you prefer to
do cross development, there is a cross-
compiler version of the GCC compiler
that will allow development on
Windows for a Neutrino target. But, I
haven’t used it, because self-hosting
make more sense on x86 platforms.
Besides compilers, let’s see what
else you get. In the lower left-hand
corner of Photo 3a, there is a Launch
button that is similar to the Start but-
ton in Windows. This button brings
up a number of submenus. The default
submenus are shown in Table 1.
CIRCUIT CELLAR
®
64 Bytes of User Accessible EEPROM
Photo 5—From the shelf, you can also run the
Package Manager. The Package Manager allows you
to install additional programs and applications from the
QNX web site or, as shown, from the CD-ROM. This
step has to be performed before a C compiler is avail-
able. What you see here is running from a QNX CD
from January of last year.
42
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Snapshot (from the Utilities win-
dow) is the screen/window capture
utility I used to capture images for
this article. Under the Development
menu, there is an option for PhAB,
which is the Photon Application
Builder shown in Photo 6. This is a
neat utility that is similar to Visual
Basic, except that it is C-based. PhAB
allows you to drag-and-drop various
controls to a desktop application.
You have to complete the code
stubs provided by PhAppBuilder. In
my experience, it works reasonably
well, but there are caveats. Make sure
you read the documentation before
starting a project, because certain
restrictions are imposed to prevent
PhAB from wiping out your work.
Also, not all of the controls are fully
functional. I was never able to get
horizontal charting control (PtTrend)
to function properly.
As with any package, it takes a
while to learn the nuances before
becoming proficient, but PhAB is a
quick way to get up to speed on
developing applications for the
Photon GUI. Also, if you get serious
about QNX, there is a wealth of
third-party tools. Check the QNX
web site for purchasing information.
HARDWARE
In order to evaluate QNX Neutrino,
I installed it on a PC-104 Panther
platform from VersaLogic. This system
has an AMD K6 processor and is con-
figured for low-power
operation (no-fan heat
sink). The system
requires only 5 V. It’s
being used for prototype
development and
includes Ethernet, PCI-
based video and IDE
controller, a 2.5
″
hard
disk, DiskOnChip, and
Compact-Flash. Panther
duplicates the function-
ality of a PC in a two-
card stack.
I also installed and
ran Windows 95 and
Linux on this platform.
The installation was
completed using a flop-
py disk and a tempo-
rary CD. The floppy is required
because the general software BIOS of
the platform does not support booting
from a CD. After installation, I
removed the CD from the system.
The video, mouse, and keyboard are
connected to a KVM switch so that I
can share the monitor, mouse, and
keyboard that I use with my main
desktop system. The QNX system
also may be accessed over the net-
work using a Telnet session, FTP, or
fs-cifs, which is a QNX command
that allows me to mount another file
system over the network.
EXAMPLES
Most likely you’ll be interested in
QNX if you are doing real-time work.
So, the first example shows a timer
callback function in a high-priority
process. The timer is set to trigger
every 10 ms, and because this is just
an example, the timer callback func-
tion copies the time to a buffer. The
buffer is printed to the screen after 50
iterations. Code segments for the key
function calls are shown in Listing 1.
As you can see demonstrated in the
listing,
Pthread function calls are
used to change the process priority
from 10 to 28.
The main thread sits in an idle task
until the timer triggers, and then the
timer callback function is run. The
results show a consistent time, but
there is a finite resolution and the
timer resolution can be obtained pro-
grammatically using the
clock_
getres() function. The x86 result is
Listing 1—This code is used to change the priority of a thread and create and configure a timer.
//Set the priority on the main thread to 28. 10 is normal.
threadMain=pthread_self();
iret = pthread_getschedparam( threadMain, &policy, &SchParam);
SchParam.sched_priority = 28;
iret = pthread_setschedparam( threadMain, policy, &SchParam);
*****************************************************************
A signal is set up for the timer trigger and a callback func-
tion pointer is declared
*****************************************************************
signal(SIGRTMIN,TimerCallBack);
//set own handler
SIGEV_SIGNAL_INIT(&event,SIGRTMIN);
//MACRO
*****************************************************************
A periodic timer is created, configured, and started with a
10 ms period
*****************************************************************
iret = timer_create(CLOCK_REALTIME, &event, &timerid);
//Setup the clock update rate using the itimerspec structure
itimer.it_value.tv_sec = 0;
itimer.it_value.tv_nsec = 500000000; //0.5 seconds
itimer.it_interval.tv_nsec = 010000000; //10 ms
itimer.it_interval.tv_sec = 0;
timer_settime(timerid, 0, &itimer, NULL); //Start timer
Photo 6—One of the applications available from the shelf is the Photon
Application Builder (PhAB). This is an IDE for programming the Photon
GUI. It works similar to Visual Basic by generating C code stubs. You can
see scroll bars, push buttons, check boxes, a calendar, and more.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
43
devices, one on
CompactFlash and the
other on DiskOnChip.
There isn’t enough
space here to go into
the details, but I includ-
ed code on Circuit
Cellar
’s ftp site that
specifies the steps used
to perform these tasks
and how to make a
bootable image.
WHAT’S MISSING?
One thing that would
benefit new users of
QNX RTP is introduc-
tory literature. With Linux or Windows
you can find literally hundreds of
books of information. But, you’ll find
only one book about QNX and it was
written by Robert Krten. [2] Krten’s
books is good, but it isn’t a beginner’s
books nor an introduction. So, be pre-
pared to dig into the provided help
files, use the
man command in the ter-
minal window, and search the news-
group using an archive site like
groups.google.com. Use the various
QNX web sites to obtain the informa-
tion you need to use QNX. That’s
another reason for using a separate plat-
form for QNX. You can use one platform
as a document resource while making
modifications to the QNX platform.
999847 ns (about 1 ms). You will have
to use a different approach if you need
better timing than this (see Table 2).
As a second example, the code in
Listing 2 demonstrates the functionality
of the watchdog timer on the Versalogic
Panther platform. The watchdog timer
first must be enabled in the BIOS. Next,
the port must be enabled program-
matically. After enabling the watch-
dog, the system will restart unless the
watchdog timer is written to within
250 ms. When run, the example rou-
tine in Listing 2 will reboot because
the watchdog timer will time-out.
As a third example, I created two
bootable images and then relocated
them to their prospective boot
SOFTWARE
10-ms period
1-ms period
Time from start
Delta time
Time from start
Delta time
0.000000000
0.000000000
0.000000000
0.000000000
0.009998470
0.009998470
0.000999847
0.000999847
0.019996940
0.009998470
0.001999694
0.000999847
0.029995410
0.009998470
0.002999541
0.000999847
0.039993880
0.009998470
0.003999388
0.000999847
0.049992350
0.009998470
0.004999235
0.000999847
0.059990820
0.009998470
0.005999082
0.000999847
0.069989290
0.009998470
0.006998929
0.000999847
0.079987760
0.009998470
0.007998776
0.000999847
0.089986230
0.009998470
0.008998623
0.000999847
0.099984700
0.009998470
0.009998470
0.000999847
0.109983170
0.009998470
0.010998317
0.000999847
REFERENCES
[1] Linux Devices, “The Real-Time
[2] R. Krten, Getting Started with
QNX Neutrino 2—A Guide for
Realtime Programmers
PARSE Software Devices,
Kanata, Canada,www.parse.com/
books/index.html, August 2001.
RESOURCE
Server: inn.qnx.com. Newsgroups:
qdn.public.qnxrtp.installation,
qdn.public.qnxrtp.newuser.
Table 2—Running the timer.c program produces these results. The program
measures the resolution of the default system timer in QNX Neutrino. The
resolution is approximately 1 ms.
SOURCES
QNX real-time platform
QNX Software Systems Ltd.
(800) 676-0566
Fax: (613) 591-3579
get.qnx.com
Panther platform
VersaLogic Corp.
(541) 485-8575
www.versalogic.com
Listing 2—Here is a complete C program for starting the watchdog timer on the VersaLogic Platform.
Assuming that the watchdog timer has been enabled in the BIOS, running this application will cause the
system to reboot following a watchdog time-out.
#include <sys/neutrino.h>
//ThreadCtl()
#include <hw/inout.h>
//out8()
#define PORT_WATCHDOG 0x0E0
int main()
{
unsigned char byteFromPort =0;
unsigned char byteToPort =0;
ThreadCtl(_NTO_TCTL_IO,0);
//writes to io-ops
byteFromPort = in8(PORT_WATCHDOG); //in al,E0h
byteToPort = byteFromPort | 01;
//or al,01h
out8(PORT_WATCHDOG,byteToPort);
//out E0h, al
//Kick once to start it
byteToPort = 0x5A;
//mov al, 5Ah
out8(PORT_WATCHDOG+1,byteToPort);
//out E1h, al
return(0);
//Without subsequent writes to the watchdog
}
//The system will restart in 250 ms.
WHAT YOU GET
Determinism, real-time, POSIX
compliance, self-hosting, priority-
based preemptive scheduler, and a
free evaluation copy. What more
could you ask for? Sure, your next
question will be what does it cost for
commercial use? Sorry, you’ll have to
contact QNX and ask them directly
for that information.
I
Duane Mattern is an instrumentation
and controls engineer with 10 years
of experience in the areas of model-
ing, simulation, control system
design, and implementation. You may
reach him at d.mattern@ieee.org.
ood news! It’s
time to start on a
new project, and you
get to pick the micro-
processor. You’ve decided you need a
32-bit unit, but which one? With more
than 100 different 32-bit embedded
chips available, you’re facing a lot of
choices. So, you narrow down the
choices to a few favorites and…. Wait,
you did choose a RISC processor, right?
Most programmers and engineers
would say, “Of course. All processors
are RISC nowadays, aren’t they?”
RISC is modern, faster, cooler; it’s,
well, it’s just better, right?
It’s hard for your average hip, hot-
shot, in-the-know engineer to admit
it, but a 10-year-old CISC chip may be
a better choice than the RISC chips
offered today. Not always, of course,
but more frequently than some
designers realize. CISC chips are still
going strong, outselling even the most
popular RISCs until recently. Motorola
and MIPS are the top two sellers of
32-bit processors, at 83.3 million and
50 million unit sales (1998 numbers),
respectively. Intel’s x86 (12.3 million
units), a CISC dinosaur (as is the 68K),
is also a big winner. The term CISC
wasn’t even used until RISC caught
hold. Like The Great War was renamed
World War I in light of World War II,
CISC was coined after there was
something to supply a contrast.
WHAT’S RISC ALL ABOUT?
First, let’s take a look at what RISC
really is versus what it has come to
mean. RISC, of course, stands for
reduced instruction set computer,
which suggests that the computer (or
the processor inside it) has a reduced
set of instructions. It’s like CPU Lite.
Cynically, you could say that it’s a
stripped-down form of a microproces-
sor, and you’d be partially correct.
The philosophy behind the develop-
ment of RISC was to strip the processor
down to its bare essentials. Anything
that wasn’t absolutely necessary got
jettisoned. In programmer’s terms,
that means that RISC chips often
could not do simple multiplication.
The theory was that multiplication is
simply repeated addition, so an ADD
instruction should be good enough.
Why the urge for Spartan austerity?
What were they thinking at UC
Berkeley and Stanford back in the
1980s when RISC first came to the
fore? With Moore’s Law throwing 4%
more hardware at chip designers every
single month, there doesn’t seem to
be much need to cut back. The under-
lying idea behind RISC is that com-
plex functions are more appropriately
done in software instead of hardware.
Software is easier to change, easier to
update, and faster to create. It’s quick-
er to write new code than it is to
design and build a new chip. Thus,
RISC-based computers could be
upgraded faster. Programs and algo-
rithms could be tweaked or improved
in record time. Best of all, RISC hard-
ware would be simplified and stream-
lined so much so that the chips would
run faster. Everybody wins.
Well, yes and no. It is true that
RISC chips were originally smaller,
simpler, and faster than their CISC
counterparts of the day. Dumping all
the excess baggage that processors
like the 68020 and the 80286 had
accumulated over the years made
their RISC competitors, such as
SPARC and MIPS, faster out of the
gate. In terms of clock frequency (that
much-abused megahertz number),
44
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Jim Turley
Is RISC Good for
Embedded?
When you’re gathering
materials to start your
next project, there are
tough choices. One
major decision is pick-
ing either RISC or its
predecessor, CISC.
Although comparably
ancient in the fast-
moving tech field,
CISC still makes the
grade and, in fact, is
often the better choice.
g
RISC was the clear winner. Technical
journals and business publications far
and wide hailed the advent of RISC as
a new era for computers. All the old
familiar processors seemed to be cir-
cling the drain.
Alas, it was not to be. Look around
and you’ll notice that the fastest
processor available is precisely the
last one anyone would have predict-
ed: Intel’s Pentium. That awkward,
inelegant, ungainly, graceless, mal-
adroit architecture is the fastest
processor you can buy (at 2 GHz and
counting). And SPARC? Workstations
from Sun are now powered by one of
the slowest 32-bit chips around, mar-
ket perception notwithstanding.
What went wrong? Was RISC a
sham or did Intel suddenly find the
backbone to compete head to head
with its peers? The truth is a little of
both. Certainly there was a lot of
hype surrounding RISC in the 1990s,
a little more than perhaps was neces-
sary. Some of the over-excitement
was understandable because RISC
was seen as the last chance to topple
Intel’s overwhelming dominance of
the PC business. If RISC could deliver
twice the performance at half the
price (an oft-repeated claim that never
came true), then surely the world
would abandon Intel and its hated
monopoly (oops, dominance). RISC
was the last hope of the have-nots.
At the same time, the threat of RISC
did spur the CISC vendors, including
Intel, to new heights. Motorola
extended the 68K family with the
68030 and ’040 and the x86 architec-
ture entered its next phase with the
’386 and ’486. It became a professional
challenge—nay, a crusade—for CISC
engineers to wring out the last bit of
performance from their older, more
complex circuit designs.
But, with one exception, they could
not do it. The 68K processors lagged
behind most other 32-bit chips in
clock rate, topping out at about 66 MHz
when others were in triple digits. Even
today, most 68K processors are available
only in speeds well below 100 MHz.
Does that spell the death of CISC
processors? Are they forever out of
breath and useless for modern appli-
cations? Not on your life.
Even though they often lag in terms
of clock rate, CISC chips like the 68K
and x86 still deliver adequate per-
formance, even better performance
than many RISC competitors. They
are more than worthy of considera-
tion and are often the best choice for
many embedded systems. Apart from
the flamboyance that the RISC label
provides, they’re often lousy choices
for real-world applications.
THE GOOD AND BAD
What you get with a RISC architec-
ture is a comparatively simple CPU
with a straightforward and orthogonal
instruction set. All instructions are
the same length, which makes them
align neatly in RAM. They’re also
encoded similarly, so if you’re inclined
to disassemble RISC opcodes, it’s easy
enough to do. It’s also easy to count
instructions in memory. Finally, it’s
pretty easy to calculate how many
cycles a certain routine will take to
run, because RISC instructions
almost always execute in a single
clock cycle. Just count instructions
(or bytes, dividing by four) and you’re
there, ignoring the effects of caches
and wait states, of course.
RISC is all about doing without—
without instructions or other features
you might like. First, there’s the
math. Most RISC chips originally had
neither multiply nor divide instruc-
tions. Most still can’t divide. If you’re
an assembly language programmer,
congratulations, you get to hand code
routines to multiply and divide inte-
gers. Never mind floating-point arith-
metic, most RISC chips don’t offer
that, either. To be fair, most CISC
chips don’t come with FPUs, but
they’re more common on the older
CISC processors than they are on the
newer RISC chips.
You also have to do without bit
twiddling. If your system massages
lots of I/O registers or other peripherals,
it’s more troublesome when your
processor doesn’t handle anything
smaller than a 32-bit word. Many RISC
designers apparently considered sin-
gle-bit operations heresy. For example,
to check and toggle a single bit in a
status register, you have to read the
entire register (and the whole 32 bits
of memory or I/O around it) into the
processor. Then, mask off the low- and
high-order bits you don’t want, right-
shift the result, check it against zero,
exclusive-OR it with a mask, left-shift
it back into position, and then write
it (along with the 32 bits of memory
or I/O around it) back out. Whew!
Unaligned memory accesses are
another casualty of RISC doctrine.
RISC chips were designed for work-
stations, where data was always con-
veniently aligned along word bound-
aries because the compiler put it
there. Smaller quantities (like bytes)
either didn’t exist or were zero-
padded to fit a 32-bit word. In embed-
ded systems, it’s rarely so neat.
Quantities that wrap around a
memory boundary, such as a 32-bit
number stored at an odd address, are
inaccessible to many RISC chips.
They’re unable to handle unaligned
operands. Likewise, odd-sized quanti-
ties such as a 24-bit value have to be
zero- or sign-extended when they’re
stored, thus wasting RAM.
The good news is that none of this
is noticeable to a compiler. If you’re
an assembly language programmer,
RISC will be painful. If you write
your programming entirely in C or
another high-level language with a
compiler, you won’t notice most of
these limitations. That is, unless
you’re interested in code density.
CODE DENSITY
Size, of course, is not important.
Unless you’re an embedded program-
mer or engineer and you have to
shoehorn 10 lbs of code into the
proverbial 5-lb bag, then squeezing
code size is a big deal. Many embed-
ded designers spend more money on
the RAM and ROM inside a system
than they do on the microprocessor.
Memory is a defining (or limiting)
characteristic of many systems.
Marketing would rather cut features
than spend another penny on memo-
ry. If the programmers can’t fit the
code into the memory budget, it isn’t
going in, and that’s that.
This is where code density becomes
a big deal. Code density describes how
tightly packed an executable program
can be. It’s the memory footprint of a
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
45
program, and it changes
significantly from one
processor to another. If
you haven’t experienced
this before, you might
think that one compiled
C program is just like
another, that it doesn’t
matter what chip is actu-
ally executing the code.
That’s a big mistake.
The exact same C pro-
gram compiled for differ-
ent chips will produce
completely different memory foot-
prints. This isn’t a mistake nor a fault
of the compiler. It’s a natural charac-
teristic of some CPU chips to produce
denser binary code than other chips.
And RISC chips suck at it.
Figure 1 shows the relative code
density of some popular 32-bit micro-
processors. As you can see, the differ-
ence can be as much as 2:1. Even
though these chips are executing the
exact same program (i.e., same source
code) and producing the same results,
some can do it in half the code space
as others. That’s code density.
You also can see that the CISC
chips all have better code density
than the RISC chips. Remember that
one of the guiding principles of RISC
is that hardware should be simplified,
with all complex operations done in
software. That means your RISC chip
will need more software to do the
same work. Most RISC chips have no
instruction for division. If you want
to divide two numbers, you do it in
the software (Yippee!).
There’s nothing you can do about
this in your code or compiler. The
compiler has to work with the hard-
ware instructions it’s given. If your
processor has a reduced instruction
set, the compiler has to make up for it
by producing more software.
CODE COMPRESSION
Another reason that CISC chips
have better code density is because
their instructions tend to be shorter.
By definition, 32-bit RISC chips have
32-bit instructions. A 32-bit CISC
chip, on the other hand, probably has
some 8-bit, 16-bit, 32-bit, and some
even bigger instructions. This is one
of the features that make CISC chips
complex, but it also makes them
more practical in embedded systems.
Why do you care about instruction
bits? Because if a 68020, for example,
can fit an ADD instruction into just
8 bits of program memory but a MIPS
R4000 requires 32 bits, you’re throw-
ing away three-quarters of your pre-
cious memory every time your pro-
gram adds two numbers together. It
doesn’t take long before that wastage
adds up, if you’ll pardon the expres-
sion. And the MIPS chip can’t add any
faster than the 68K, so you don’t get
anything for your trouble other than
the privilege of saying you have a
RISC-powered system.
Recently, some of the RISC vendors
came up with clever solutions to this
problem. The solution generally is
called code compression, but that’s a
misnomer. Nobody’s actually com-
pressing code, as with PKZIP. Instead,
they’re altering their chips’ instruc-
tion sets a little so that not all
instructions are 32 bits long.
The three primary examples of this
are ARM, ARC Cores, and MIPS. They
each have similar code compression
schemes called Thumb, ARCompact,
and MIPS-16, respectively. In all three
cases, the chips can optionally augment
their usual 32-bit instruction sets
with a smattering of 16-bit instruc-
tions. Their respective C compilers
can now choose to sprinkle 16-bit
instructions into the code, making
the binary executable smaller.
How much smaller depends on
many things. And, as you already
know, cutting through the marketing
hype is never easy. In real tests, how-
ever, the shrinkage seems to average
around 20% to 30% and
depends on the program.
Mind you, that’s just the
compression of the code
space; data storage does
not compress. Still, it’s
a step in the right direc-
tion and makes these
three RISC architec-
tures more attractive
than they might have
been otherwise.
There’s a catch though.
In two cases (the ARM
Thumb and MIPS MIPS-16), your code
has to explicitly switch between 32-bit
mode and 16-bit mode. You can’t mix
the two instruction types, so you
have to segregate code that runs with
16-bit operations from code that runs
using 32-bit instructions. First, you
must find portions of code that will
run entirely with 16-bit instructions,
which is not a slam dunk.
You see, the trade-off for the shorter
instructions is their limited repertoire.
For example, 16-bit code cannot handle
interrupts, cache management, memory
management, exceptions, or long
jumps. Fortunately, the Thumb and
MIPS-16 compilers sort this out for
you. The ARCompact from ARC doesn’t
have this limitation because it doesn’t
switch between the two modes. It
freely intermixes instructions of both
sizes, so you don’t have to sweat over
how to segregate your programs.
A different, and typically over-engi-
neered approach is the CodePack sys-
tem from IBM for embedded PowerPC
chips. Unlike the other three com-
pressed-RISC instruction sets, IBM
actually does compress its executable
binaries, just like using PKZIP on the
object code. You compress the program
after you’ve compiled, assembled, and
linked it. Then, store the compressed
version in ROM or on your disk.
Certain embedded PowerPC chips have
extra hardware added that decompresses
instructions as they are fetched from
memory. Figure 2 shows how each
instruction is cracked and compressed
in halves. The system is tricky and
there are a few odd side effects.
First, your code is completely
inscrutable because it isn’t stored in
the normal object code format. The
46
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
10%
20%
30%
40%
50%
60%
70%
80%
90% 100% 110% 120%
ARCompact
MIPS-16
Thumb
68K
x 86
ARM
MIPS
PowerPC
SPARC
1.20
1.00
1.00
0.91
0.84
0.70
0.60
0.60
0.60
Figure 1—The size of a program is determined by the chip it runs on. RISC processors gen-
erally have poorer code density than CISC processors, although some of the compressed
RISCs are closing the gap.
48
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
code is compressed, and that makes it
hard to disassemble. That might be an
advantage if you want to protect your
code from prying eyes. CodePack
effectively encrypts your software as
well as compresses it.
Second, CodePack does funny
things to performance, because it has
to decompress software on the fly,
which sometimes takes longer than is
usually expected. Handling branches
and jumps is particularly tricky for
PowerPC processors equipped with
CodePack, because the branch target
is not easy to locate when it’s
encrypted somewhere in a big block
of code lying in ROM.
Third, each CodePack program uses
its own compression key, therefore,
different programs are compressed dif-
ferently. That means compressed
binaries are incompatible—they won’t
run on other PowerPC chips unless
you supply the key.
Finally, CodePack promises the
same 30% compression factor that
ARC, ARM, and MIPS offer. For all of
its complexity, it isn’t significantly
better. Still, IBM has done an
admirable job flashing its engineering
muscle to come up with something
completely different.
RISC POWER
One advantage RISC chips have
over their baroque brethren is power
consumption. As a rule, RISC chips
use less power to run than do CISC
chips. This is obvious: If the circuit
design of a RISC processor is simpler
and more streamlined, it stands to
reason that it should use less power.
Fewer transistors to wiggle means less
energy expended to wiggle them.
A few RISC families have made a
name for themselves in this area,
most notably ARM. ARM processors
have a reputation for ultralow-power
consumption that is, sadly, almost
entirely bogus. Sure, ARM processors
use less power than, say, an Intel ’486,
but so does the Hoover Dam.
To be fair, ARM processors are low
power, but so are almost all RISC
processors of the same era. Compared
to other processors circa 1994, an
ARM7 was admirably power efficient.
In 2002, however, there are plenty of
RISC processors and even some CISC
processors that easily beat ARM in
the race for lowest power. MIPS,
SuperH, ARC Cores, and others all
have lower power cores.
The low-power advantage of RISC
is important if you’re making smart
cards, thermostats, or cell phones. On
the other hand, for other applications,
it’s less important, as long as you
don’t need a fan in your box. For the
first category, RISC processors are a
good choice. Watch out though, what
you save in CPU power you may
spend for memory power.
Code density plays a role in power
consumption, so chips with better
code density may use less system
power overall because they don’t
make as many memory accesses.
Each fetch from ROM or read/write
access to RAM burns a little power.
The more you can minimize that, the
better. There’s no hard and fast rule
here, so it’s impossible to say that a
2× increase in code density is worth a
2× increase in power, for example.
Each application is different, but bear
in mind this relationship if you’re
power-constrained.
PERFORMANCE
Performance is the big, fat target
that everyone shoots for. Better per-
formance was one of the primary ben-
efits of RISC, so RISC chips are
always faster, right? In a word, no.
First of all, performance is a tricky
word. Drag racing microprocessors is
not without perils, because everyone
Opcode
Opcode
Rt Ra
Opcode
Rt Ra Rb
00 nnn
01 nnnnn
100 nnnnnn
101 nnnnnnn
110 nnnnnnnn
111 opcode (16)
8
32
64
128
256
128
32
16
1
256
Combinations
Combinations
00
01 nnnn
100 nnnnn
101 nnnnnnn
110 nnnnnnnn
111 literal (16)
Figure 2—CodePack from IBM compresses 32-bit
PowerPC opcodes into as little as 9 bits. The upper
and lower halves of each instruction are compressed
separately. In some cases, infrequently used instruc-
tions may actually get bigger.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
49
is interested in a different kind of per-
formance. For example, what’s good
for media processing may not be good
for network processing. Suffice to say
there is no one processor that excels
at all tasks. Every CPU instruction
set is a compromise.
That said, you should choose a
CPU with an instruction set archi-
tecture (ISA) that is suited to your
particular application. Two chips
running at the same speed (let’s say,
100 MHz) may deliver radically dif-
ferent performance because of differ-
ences in ISA. That’s why companies
continue to tinker with instruction
sets to this day, and why new CPUs
with user-defined instruction sets are
starting to catch on.
The majority of RISC instruction
sets are more or less equal; after all,
they’re supposed to support only the
bare essentials, correct? In reality,
every RISC architecture has been pol-
luted over the years with features
creeping in that do not adhere to
RISC policy. However, as a first-order
approximation, RISC chips are generic
and interchangeable.
Over in the CISC camp, however,
there are chips with all kinds of inter-
esting instructions that can be incred-
ibly useful or totally irrelevant to
your system. Sometimes it’s hard not
to wonder where some of these odd-
ball instructions came from, or what
other programmers are using them
for. Other times you wonder how you
got along without them.
One of my favorites is the TBLS
instruction found on several 68300
family chips from Motorola. TBLS is a
table look up and interpo-
late instruction. Most
programmers will never
use it, but it’s a lifesaver
if you need it.
The TBLS instruction
allows you to create a
complex geometric func-
tion from a sparse table of
data points. TBLS search-
es through a table of val-
ues that you create, locat-
ing the nearest two
matches to any number
that you specify. It then
figures out, through linear
interpolation, the exact value in-
between those two data points. In
essence, TBLS connects the dots in an
x, y scatter graph, returning the y value
for any x value as shown in Figure 3.
Seems strange? You bet it is. But,
it’s vital if you’re doing motion con-
trol. The alternative is to code hun-
dreds of different geometric functions,
with all kinds of exceptions and
boundary cases. Keep in mind that
TBLS is a single instruction that exe-
cutes in about 30 clock cycles.
SWITCHBLADE VS. SWISS ARMY
KNIFE
In a nutshell, RISC means giving up
features and functions in return for
faster clock speeds. If you’re a speed
demon and clock speed means every-
thing to you, then go for it. You’ll get
higher clock rates (as well as better
marketing buzz) using a 200-MHz
RISC processor than you will with a
75-MHz clunker.
However, you may not get better
performance and you’ll probably
spend more money. A fast processor
needs to be fed with fast RAM, fast
ROM, and fast I/O. Your whole bus
structure likely will have to be faster.
And caches will play a much bigger
role in performance when your speed
demon spends 90% of its precious
time stalled on cache misses.
There’s no denying that RISC has a
certain prestige to it. It’s perceived as
new, exciting, and the way forward. It
seems counterintuitive that CISC
processors are still going strong. Yet
CISC persists for good reasons. As a
class, their code density and integra-
tion are better and they deliver more
useful performance in the form of spe-
cialized instructions for bit manipula-
tion, memory accesses, looping, deci-
sion trees, and so on. RISC has a cer-
tain abstract elegance, but in this
business, elegance doesn’t count.
Sometimes slow and steady really
does win the race.
I
65,536
16,384
Independent variable
Dependent v
a
riab
le
32,768
49,152
y
x
Figure 3—The TBLS (table look-up and interpolate) instruction in some
68300 chips can interpolate missing values from a sparsely populated x-y
graph. Amazingly, this is done in a single 16-bit instruction.
SOURCES
ARCompact
ARC Cores, Inc.
44 0 20 8236 2800
Fax: 44 0 20 8236 2801
www.arccores.com
ARM Thumb
ARM Ltd.
(408) 579-2200
Fax: (408) 579-1205
IBM Corp.
(800) 426-4968
www.chips.ibm.com
Pentium
Intel Corp.
(408) 765-8080
Fax: (408) 765-9904
www.intel.com
MIPS-16
MIPS Technologies, Inc.
(650) 567-5000
Fax: (650) 567-5150
www.mips.com
68000 Processor
Motorola, Inc.
(847) 576-5000
Fax: (847) 576-5372
www.motorola.com
Workstation
Sun Microsystems, Inc.
www.sun.com
Jim Turley is an independent analyst,
columnist, and speaker specializing
in microprocessors and semiconduc-
tor intellectual property. He is the for-
mer editor of Microprocessor Report
and Embedded Processor Report and
host of the annual Microprocessor
Forum and Embedded Processor
Forum conferences. You may write to
him at jim@jimturley.com or visit his
web site at www.jimturley.com.
oday’s micro-
processor-based
electronic and electro-
mechanical equipment
often can be designed to accommodate
add-on accessories. Add-on hardware
must live with the design constraints
of the original firmware or provide a
means of upgrading firmware in the
field. Suppose the add-on hardware
could patch the application at run time
to take advantage of the new hardware.
A common way to patch code at
run time is to put hooks (function
pointers in C) at strategic points in
the application. These hooks point to
function pointers in RAM, which can
be patched. For example, you may
decide that
putch may change, so
you define a default ROM version
called
DefPutch, and then declare:
void (*putch)(byte) = DefPutch;
To define a patch, compile a new ver-
sion of
putch for an absolute location in
memory. To patch the ROM code, you
would load the patch code into the RAM
location you compiled for and then
change the function pointer for
putch
to point to the new code. This method
may be used with assembly, too. Either
way, there are serious drawbacks.
First, the patch code is native and,
on many platforms, absolute. This
greatly complicates the use of multi-
ple add-ons. Plus, you have to freeze
the ROM if the add-on code is to
reuse sections of ROM code.
In addition, you need to provide
enough hooks to address every antici-
pated need. Invariably, a need comes
up that you didn’t anticipate, so the
add-on code has to replicate a big
chunk of the application in order to
work. This bloated code eats up system
resources that may be scarce already.
Last, changing the hardware design
or moving to a new processor will
break existing add-on code. Accessories
in the field that can’t practically be
updated will end up obsolete.
Besides flexibility in the interface
between add-on code and the applica-
tion, you need a way to handle run-
time variations and provide extensi-
bility. If you want to enable end users
to write add-on code, you can’t just
give them your source code and tell
them to buy a compiler tool chain.
An interpreter such as Lua, TCL, or
Java could provide a virtual machine
to isolate add-on code from the imple-
mentation details of your application.
But, interpreters are slow, usually
bulky, and don’t really address the
interface issue. It’s better to compile
add-on code at startup.
One solution is to implement a com-
puter language (preferably not a new
one) in a way that solves these prob-
lems. A late binding mechanism that
renders all subroutines able to be
patched at run time would solve part of
the extensibility problem. Any subrou-
tine could be patched with a relatively
small amount of machine code. And,
although a token interpreter offers
some extensibility, complete extensi-
bility requires removing the wall
between application and add-on code.
FORTH TO THE RESCUE
Flexibility can be attained if add-
on code is compiled at boot time.
The compiler needs to quickly trans-
late source code in the add-on mod-
ule to machine code at startup. It also
needs to be able to execute com-
mands that bind the new firmware
features into the application. The
50
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Brad Eckert
Extensibility for Small
Embedded Systems
Using a dialect of
Forth, Brad shows us
how to combine run-
time compilation and
immediate execution
of add-on firmware in
order to make an
embedded system
extensible. New hard-
ware introduces itself
to the original firmware
making the upgrade
process much easier.
t
combination of run-time compilation
and immediate execution renders the
application extensible.
Extensibility is a key feature of the
Forth programming language. Forth is
an industry-proven computer language
originally developed for real-time
control. This language is used by the
IEEE1275 Open Firmware standard to
boot up millions of Sparc and PowerPC
workstations. On a workstation
motherboard, Open Firmware probes
the buses for add-on cards and loads
driver code from a ROM resident on
the card. The driver code is in tok-
enized form, meaning that numbers
instead of ASCII strings represents
Forth keywords. The most often used
Forth keywords are represented by
1-byte tokens, hence compact code is
created. Semantically, it’s still proces-
sor-independent Forth source code.
A dialect of Forth, called Tiny
Open Firmware (TOF), implements
the features of IEEE1275 that are use-
ful to small, embedded systems. TOF
uses subroutine/native threading in
which Forth keywords (tokens) are
converted to subroutine calls or in-
line machine code. TOF adds an extra
level of indirection to each subrou-
tine call in the form of a RAM-based
jump table. Instead of calling a sub-
routine directly, compiled code calls
into an array of jump instructions.
For each subroutine call, the extra
overhead is one jump instruc-
tion. On some processors, there
is a pipeline stall penalty, but
it’s still an efficient way to
achieve late binding.
The RAM-based jump table,
called the binding table, is ini-
tialized from ROM at startup.
You can think of a TOF-based
system as an object with hun-
dreds or thousands of late-
bound methods. You may patch
any ROM-based subroutine by
putting new code in RAM and
changing the appropriate bind-
ing table entry to jump to it.
All code that uses it will be
redirected to the new version.
Besides giving the application
fine-grained patching ability,
the binding table enables rapid
compilation. By the way,
Firmware Studio, a freeware Windows
program, implements TOF for several
processors, and is available with the
full source code (www.tinyboot.com).
DIFFERENT KIND OF LANGUAGE
Forth is a computer language that
has a simple syntax and many key-
words. This is in contrast to Algol-
style languages that have a complex
syntax and few keywords. If you’re
familiar with C or Pascal, try to forget
about syntax as you learn about Forth.
Forth is compiled, yet it has no
compiler in the traditional sense.
Essentially, the language consists of a
population of subroutines and an
interpreter. Subroutines are called
words in Forth language. The inter-
preter can invoke words that perform
compilation actions.
There are two things that charac-
terize Forth, its interpreter mecha-
nism and collection of words. Forth is
a definition tool whose lexicon con-
forms to a language specification. It is
a programming language, compiler,
debugging tool, assembler, and operat-
ing system. As you see, Forth is many
things to many people. There are
numerous implementations and mul-
tiple threading mechanisms. Despite
their differences, all Forths have
syntax based on blank-delimited
strings in common.
Just as Newtonian Physics has
F = ma at its core, Forth has a simple
interpreter at its core. Figure 1 shows
a typical Forth interpreter. A Forth
interpreter evaluates blank-delimited
strings taken from an input stream
such as a console or file, usually in
one pass. This implementation uses
subroutine/native threading, meaning
that it uses call instructions to
invoke Forth words. Simple Forth
words that can be done with one or
two machine instructions are in-lined
instead of called.
This simple interpreter gives Forth
its characteristic RPN syntax. For
example, typing
1 2 + at the console
leaves
3 on the stack. Operators per-
form simple transforms on the top of
a data stack. Parameters are implicitly
passed between Forth words via the
data stack, so less code is wasted
shuffling parameters around. Implicit
parameter passing also allows a natural
syntax, because the source needn’t be
cluttered with parameter declarations.
The data stack is a LIFO list used
to hold intermediate values such as
numbers and addresses of words and
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
51
Error
Start
Get next input word
Search dictionary
Word
found?
Immediate
word
In Compile
mode?
Is word a
number?
In Compile
mode?
Compile call
or in-line code
Execute
word
Compile code
for a literal
Put number
on stack
Yes
No
Yes
No
Yes
No
No
Yes
Yes
No
Figure 1—Forth interpreters evaluate blank-delimited strings
from an input stream such as a console or file. Whatever the
implementation, this kind of interpreter is the essence of Forth.
Words
Descriptions
:
Creates a header for #S, enters Compile mode
(
Comment: Discards input up to the closing parentheses
begin
Marks a backward reference, pushes 0x489A onto the stack
#
Compiles a call to #. Binding table grows downward from 0xFFFF
2dup
Copies in-line code for 2dup
d0<>
Compiles a call to d0<>
while
Compiles code to do a conditional branch and marks a forward refer-
ence, pushes 0x48B2 onto the stack
repeat
Lays down a backward branch to the address marked by begin,
resolves the branch offset at the address left by while
;
Lays down a return instruction, exits Compile mode
Immediate words are in italic
Table 1—The interpreter performs these duties for each of the keywords.
data. Forth also makes use of the
return stack for temporary storage.
For stack pointers, usually one stack
uses the stack pointer of the CPU and
the other uses a register.
Forth is made up of an interpreter
and a large number of keywords.
These keywords are small subroutines
held in a data structure called the dic-
tionary. The dictionary consists of a
linked list of headers and accompany-
ing code. Each header contains the
name of the word, a flag byte, a link
to the next header in the dictionary,
and possibly a link to the executable
code. Each word has an immediate
flag to denote whether or not it’s an
immediate word.
Essentially, the language is the com-
piler. Some keywords perform compi-
lation actions, and you can always
define new ones. The word
: begins a
new Forth definition. It creates a new
header and sets a flag referred to as
state. When the state flag is set, the
interpreter is in Compile mode. The
word
; is an immediate word (its
immediate flag is set) that ends a defi-
nition and clears the state flag.
Immediate words are typically used to
form loops and control structures.
Firmware Studio is a Windows-based
Forth implementation that uses the
algorithm shown in Figure 1 to compile
ROM code for a target processor. The
dictionary consists of a linked list of
headers and a ROM image. Firmware
Studio assigns each new word an exe-
cution token (
xt) and stores it in the
header structure of the word. Each
word in the system has a different
xt.
This is a key feature of TOF.
TOF uses two compilation modes,
Static and Dynamic. Both compile
call instructions. In Static mode, the
destination is the address of the word.
This is typical of subroutine threaded
Forths. In Dynamic mode, the desti-
nation is computed from the word’s
xt so as to compile calls into the
binding table. The binding table is an
array of jump instructions in RAM,
initialized at startup. Most words are
compiled in Dynamic mode.
Take a look at typical definition in
Table 1. The 68K/ColdFire implemen-
tation compiles the ROM code shown
in Listing 1.
TOKENIZED CODE
Firmware Studio has a specialized
interpreter, known as a tokenizer (see
Figure 2). Instead of compiling
machine code, the tokenizer converts
Forth keywords into tokens. The
resulting tokenized code is semanti-
cally equivalent to its textual Forth
source; it is stripped of comments and
stored in a compact form. The tok-
enizer is the part of TOF that runs on
the host PC. The host knows the
token assignments of Forth keywords
and can compile tokenized code.
Tokenized code may be used as boot
code for add-on hardware.
For interaction with the target hard-
ware, tokenized code is sent to the
target over a communication link for
immediate evaluation. Typically, con-
sole input is tokenized and sent to a
free part of RAM in the target. Then,
a program resident in the target evalu-
ates the tokenized code. Tokenized
code may also be stored in the pro-
gram ROM to archive temporary fea-
tures, thus packing more features into
a space-limited application.
As shown in Figure 2, token values
between 0x20 and 0xFF are encoded
using 1 byte, and others are encoded
using 2 bytes. Two-byte values con-
catenate the lower five bits of the first
byte with the second byte, giving a
possible range of 0x0000 to 0x1FFF.
Host words, which execute on the
host PC and mostly serve as defining
words, are parts of the tokenizer resi-
dent in a special word list. The tok-
enizer has a state flag, which defining
words use to keep semantic consis-
tency with the original Forth source.
When a ROM image is built, token
numbers are assigned to word names.
These token assignments can be
saved to a file. A token file serves as
an interface specification that con-
nects add-on code to ROM routines.
This file can be used instead of the
original source code to set up token
assignments. It can be given away
without revealing proprietary source
code, enabling third parties to write
add-on code. Also note that tokenized
code serves as input for the evaluator.
THE EVALUATOR
The evaluator is a Forth program
resident on the target hardware (see
Figure 3). It converts tokenized Forth
source to machine code. The evalua-
52
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Listing 1—The compilation process relies on blank-delimited strings. These strings are keywords (see
Table 1), many of which perform a simple compilation action. The 68K/ColdFire implementation of TOF
compiles this machine code.
0000489A 4EB90000FB50 #S: JSR 0xFB50(xt:200) #
000048A0 2015 MOVE.L (A5),D0
000048A2 2B07 MOVE.L D7,-(A5)
000048A4 2B00 MOVE.L D0,-(A5)
000048A6 4EB90000FCB2 JSR 0xFCB2(xt:141) D0<>
000048AC 2007 MOVE.L D7,D0
000048AE 2E1D MOVE.L (A5)+,D7
000048B0 4A80 TST.L D0
000048B2 67000006 BEQ 0x48BA
000048B6 6000FFE2 BRA 0x489A:#S
000048BA 4E75 RTS
Error
Start
Get next input word
Search dictionary
Word
found?
Host
Is word a
number?
Execute
word
Encode
the number
Compile token
for a literal
No
Yes
Yes
No
Yes
Compile
token
No
Figure 2—The tokenizer is a specialized Forth inter-
preter that replaces keywords with numeric tokens.
The resulting tokenized code is semantically equivalent
to its textual source.
tor is like a traditional Forth inter-
preter except that it computes the
location of Forth words instead of tra-
versing a header list looking for them.
The evaluator is the part of TOF that
runs on the target hardware. It uses
the token value as an index into the
binding table. This index is used as the
call destination for compiled words.
Every word is preceded by a header
byte containing an immediate flag. To
get this flag, the index is used to extract
the address of the code from its bind-
ing table entry and the byte immedi-
ately before the code is fetched.
Numbers are represented by an
immediate word, like
(LIT8), followed
by one or more data bytes.
(LIT8) and
similar words fetch data from the
input stream and sign or zero extend
it if necessary. The evaluator fetches
bytes sequentially from the input
stream until the end token, which ends
the evaluation, is executed. Listing 2
is a simple tokenized Forth word.
Token values between 0x1000 and
0x1FFF are regarded as relative
tokens. The evaluator subtracts
0x1000 and adds the highest unused
token value of the last evaluation ses-
sion. This has the effect of mapping
the relative tokens of each add-on
peripheral onto a different set of
unused absolute token values.
Consider the case in which your
ROM has
xt values up to 0x480,
peripheral A has
xt values ranging
from 0x1000 to 0x1021, and peripheral
B has
xt values ranging from 0x1000
to 0x1014. The words of peripheral A
will be mapped to
xt values 0x481 to
0x4A2 and the words of peripheral B
will be mapped to 0x4A3 to 0x4B7.
The evaluator is the TOF version of
the classical Forth interpreter. Instead
of feeding it textual source, you feed
it tokenized source. This source can
come from a host PC, nonvolatile
memory in add-on peripherals, pro-
gram ROM, or any other data sources
available at run time.
PUTTING IT ALL TOGETHER
TOF removes the wall between
your application and add-on code.
Add-on boot firmware is free to
invade the application and do any-
thing it wants to any hardware or
code. You control the add-on code, so
you know your guests are reasonably
well behaved. The software equiva-
lent of a bouncer can keep out
unknown code.
A typical system has some kind of
expansion bus. At startup, TOF probes
each module on the bus looking for
boot code. If it finds it, the evaluator
verifies its boilerplate and checksum
and then evaluates the boot code.
TOF continues probing the bus until
all boot code has been evaluated.
Add-on modules usually aren’t
merely generic hardware. They are
designed to supplement the applica-
tion. As such, their boot firmware
patches part of the application to
make use of the new hardware. A typ-
ical boot program defines driver code
and an application extension for the
new hardware, initializes it, and links
the code into the application.
The evaluator can handle boot code
from multiple modules, each device
containing tokenized source that’s
compiled to native machine code at
startup. Installation instructions for
the end user reduce to “plug it in.”
For debugging, the tokenizer and
evaluator together act as a normal
Forth interpreter. Keyboard input is
tokenized by the host PC, sent to the
target, and evaluated. The resulting
output is read and displayed by the
host PC. Because most Forth code is
inherently reentrant, the debugger has
its own execution thread that lets the
application run while debugging is
underway. TOF supports live debug-
ging with which you can probe and
patch a live, running system.
In closing, I want to reiterate that
Tiny Open Firmware brings self-
installing, plug-and-play hardware to
small embedded systems. A TOF
implementation is small, typically
under 32 KB for 68K/ColdFire and 20
KB for 8051 processors. Its efficient,
late-binding mechanism ensures that
all ROM-based routines may be
patched, and enables rapid compila-
tion of processor-independent add-on
code. Run-time compilation of add-on
code simplifies applications whose
configurations will change as cus-
tomers modify their systems.
I
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
53
Done
Start
Still
evaluating?
Execute
word
Yes
No
Get next token
Look up header
Immediate
word
In Compile
mode?
Compile call or
inline code
Yes
No
Yes
No
Figure 3—The evaluator is a Forth interpreter whose
input stream consists of tokens instead of text. It uses
tokens as indices into a table of pointers.
Listing 2—The tokenizer associates a token value with each keyword. In this example, words associated
with tokens E2, F0, and F2 are immediate words.
E1 02 06 : STARS
4B 0
F0 DO
02 05 STAR
F2 LOOP
E2 ;
Brad Eckert holds a degree in Physics
and is currently a hardware/firmware
engineer. He’s been designing and
programming embedded systems for
about 15 years.
SOURCE
ave you ever
wanted, I mean
really wanted, to do a
project and all that stood
in the way was getting the right parts?
Well, this is it for me. I’ve been thinking
about doing this project for months and
just never got up the energy to pound
the distributors’ web pages for the hard-
ware I’ll need. I’ve also wanted to listen
to Pink Floyd recordings lately. In fact,
I’ve purchased so many Pink Floyd CDs
that lead guitarist David Gilmour paid a
visit to the Florida room last week. Of
course, the first thing he asked about
was my new jet-black Telecaster. He
was under the impression that I needed
some tutoring. Bad tunes travel fast and
David, after hearing my rendition of
“Money,” decided to stay the week.
The week with David was great, but
another musically inspired treat was
yet to come. While David coaxed mel-
low Pink tones from my Telecaster, I
relaxed and in a moment of total clar-
ity, realized I had the answer to the
parts quandary that had inhibited
beginning “the” embedded project.
THE PROJECT
Over the past couple of years, I’ve
written a ton of PIC code that I apply
to various gadgets. Even with the most
glamorous of PIC programmers, it has
become a burden to find the files and
then hook up all of the necessary PCs,
serial ports, and programmers to serv-
ice a reader or client’s request for
functional embedded PIC hardware.
The ultimate solution to this problem
would be to have my production hex
files reside inside the PIC programmer
in nonvolatile memory. Then, by sim-
ply executing a script, the desired hex
file would be invoked and transferred
to the program memory of the PIC.
Sure, I could dedicate yet another $900
PC to this task, or I could use an SBC
for a little over 25% of that $900. As
a bonus, I could cart around the SBC
with my laptop and clone PIC parts
wherever and whenever I pleased.
The SBC-based PIC program reposi-
tory I’ve described will have to com-
municate with an external PC to ini-
tially get the production hex files into
its memory. The easiest way to do
this is via a serial port. Serial ports
are on almost everything that com-
putes. So, using a serial port enables
any Palm, Linux, Windows, or DOS-
based computer to have access to the
SBC firmware vault and vice versa.
Windows is a good thing on the
host PC, but a bad thing if used as the
SBC OS. The problem is writing
around Windows to get to the SBC
hardware. Also, Windows needs more
resources than DOS does to operate.
An RTOS would be overkill and a
simple dump-and-display monitor
won’t cut it either. I’ll be working
with ASCII files and need a minimal
file system and an operating environ-
ment that can support it. The OS I
choose must allow me to write direct-
ly to the SBC I/O pins that will con-
trol the PIC programming operation.
I don’t like fighting with user-
unfriendly compilers and IDEs when I
develop firmware. With Windows, I
can use a decent C compiler that is
hopefully coupled with a fancy IDE to
write the SBC code. Because the SBC
doesn’t need to be a 32-bit machine, I
have to choose a compiler that will
generate good 16-bit code and run in a
32-bit environment. The resulting
code better be tight, because I’m not
planning to incorporate a spinning
drive of any kind on the SBC.
54
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Fred Eady
h
APPLIED
PCs
Everyone has a proj-
ect that lingers on the
to-do list for months,
just waiting for the
right parts to come
along. Fred decided
he had to hunt down
the right parts on the
’Net. First, he had to
determine what parts
he needed and how
they would work with
what he already had.
“The” Embedded Project
Part 1: Specifications and Components
Good old Datalight. Like the name
implies, Datalight is a ray of light in
the darkness of an embedded world. I
found a CD containing the SDK V.2.0
and loaded it. Lo and behold, there
was a full version of Borland C++ 5.02
and the entire set of electronic manu-
als and a help document. I took a
quick look at the Target Expert from
the Borland compiler and sure enough
there was a selection to create a DOS
standard (
.exe) application. With that
bit of knowledge, the C compiler
selection process was complete.
When I think of Datalight, I think
of ROM-DOS. ROM-DOS supports
flash memory disks and acts just like
Bill’s DOS 6, but it’s much smaller and
like its name implies, it can be put into
ROM on an SBC. I hear the new version
of ROM-DOS even does the Internet.
With ROM-DOS, the file system ques-
tion is taken care of and I know I can
get to the 82C55 of the MMT-188EB
unhindered. It also includes a file trans-
fer utility that allows me to download
my PIC hex files into the flash memo-
ry disk using the serial port and
HyperTerminal or ProComm.
Life is good. I have a C compiler
and an OS that will fit my needs. The
law of embedded computing states
that nothing is free. With the addition
of ROM-DOS to the project, I have to
add dedicated onboard flash memory
or EPROM to my SBC requirements.
I’ve got a bunch of great SBCs on
the Florida-room shelves just begging
for work. What I need is an SBC vol-
unteer that can live happily with the
Datalight/Borland architecture. After
shuffling through a few boards, the
stickers on the SBC’s CPU and
EPROM in Photo 1 made the SBC
selection process simple.
The MMT-188EB is a Midwest Micro-
Tek product and is perfectly suited for
my project. It features a 20-MHz
80C188EB microprocessor, 512 KB of
SRAM, and just under 2 MB of usable
flash memory. The serial port is there
as well as an IC full of 82C55-based
I/O that can be bit-banged. The MMT-
188EB has I/O provisions onboard for
upgrades, and I’m considering adding
an LCD and some buttons.
My MMT-188EB doesn’t include an
Ethernet interface (I won’t need one
here), but it has just about every other
bell and whistle including a couple
So, the playing field has been
defined. On the hardware side, I need
a 16-bit SBC equipped with a serial
port, which can run a minimal file
system-capable OS. The SBC I select
must support a flash memory disk
and some simple bit-addressable I/O.
The development software needs to
run under Windows, be easy to use,
and generate 16-bit code.
AND THEN THERE WAS
(DATA)LIGHT
I decided to attack the problem
inside out. That is, I would choose
the C compiler environment and then
find suitable hardware to complement
it (how innovative). The first C compiler
that came to mind was the trusty old
Borland 3 I wrote my first 8748 pro-
grammer code with decades (yes,
decades) ago. BC3 was and still is a
native DOS/WIN3.1 16-bit C compil-
er, and is found in some of the C pro-
gramming trainer packages today.
From experience, I know it’s easy to
use, will run in a Win98 DOS win-
dow, and generates good 16-bit code.
It didn’t take long to find the 12 BC3
diskettes in the Florida-room archives.
I decided on the spot that there is (or
will be) a better compiler in here. I
tried to remember past articles for
some help and bingo! I managed to
recall that Datalight released an SDK
that contains a version of Borland C,
and thought it just might be in the
Florida room. It amazes me that I can
squirrel away something and then
walk right up to it months later.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
55
Photo 1—After I saw the light, all I had to do was read
the labels to select a complementary set of hardware
and software. The MMT-188EB is perfect for this appli-
cation, because it’s simple enough to quickly put into
action and complex enough to do the job.
Photo 2—It’s difficult to believe I’ve kept this sample
for almost 10 years! Even though I’m sure this sample
will work in “the” project, I thought it would be worth
my time to investigate the National LM2574 simple
switcher family a little further.
Figure 1—As I write this, I’m still oscillating between step-down and step-up electronics. This circuit has been bat-
tle tested using the 4053 and a linear regulator.
status LEDs. In fact, my SBC is a fully
loaded MMT-188EB and includes ADC,
DAC (nice), a real-time clock, and
addressable RS-485 capability in addi-
tion to the multitude of standard stuff.
POUNDING FOR PARTS
Most folks surf the ’Net for infor-
mation. Not me. I pound the ’Net for
information. It’s like shopping for
Christmas. I already know what I
want when I get to the mall. I hit the
store, beeline to my predetermined
coordinates, procure the item, and
haul. I had successfully exercised the
same idea in relation to parts shop-
ping on the Internet until I shopped
for “the” project.
The flash memory-based PICs I’m
targeting require a programming voltage
of 13 VDC in addition to the 5-VDC
supply voltage. In the past, I’ve used
standard linear voltage regulators to
drop a higher voltage down to the 13-
and 5-V levels. Although the program-
ming and supply voltages actually can
be applied and extinguished manually,
it’s always a good idea to allow the
boss processor to automate the appli-
cation of the critical voltages.
The current requirements for the 13-
and 5-VDC supplies are minimal and
in the dust for the former and 50 mA
for the latter. So, even if I double the
maximum current values, I won’t
need any heavy-duty voltage regulator
circuitry for the programmer module.
In programmers past, I’ve switched
these voltages using a 4053 for the
high voltage and standard switching
transistors for the 5-VDC supply. For
this project, I decided to reach out to
the newer switching regulators and
use their SHUTDOWN, or on/off, pins
to control the programming voltages.
STEP (DOWN) AEROBICS
I decided to start with the 5-VDC
step-down switcher first. I plan to use
one of the 1-A or better wall warts
that can be purchased from some of
the advertisers in Circuit Cellar. The
MMT-188EB requires 5 VDC only at
about 600 mA max. The MMT-188EB
document recommends the power
supply be able to supply 1 A of current.
I store stuff like a pack rat and some-
times manage to remember I have it. I
couldn’t remember when I got it, but I
knew I had one of those National
simple switcher samples tucked under
something. After hunting down the
sample box, to my surprise, the sam-
ple literature was dated 1992 and
signed by a marketing guy who’s prob-
ably either history or a CEO by now.
The vintage LM2574 simple switcher
sample and the marketing letter are
shown in Photo 2. As you can imagine,
the 1992 time stamp made me ques-
tion if there’s something better avail-
able now. So, I began pounding the
National web site and the run-in-and-
get-what-you-need-and-haul theory
went up in smoke. My screen was full
of simple switchers for every girl and
boy and those LM317s and 7805s with
all their support switching circuitry
were beginning to look good again.
I was determined to use switchers
and there had to be a way to cut to the
chase. Well, see the diskette in Photo 2?
Could it be that this program has too
survived and flourished like the parts
it was designed to support? You bet. A
flick of the wrist and a well-placed
mouse click started the download of
Switchers Made Simple (SMS) V.6.22.
I was saved. Or maybe not.
MAKING THE SWITCH(ER)
National’s SMS is a Java applet that
asks some simple questions, allows
you to choose a device, and puts
56
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Photo 4—This screen shot is much easier to navigate than the pages of the Digi-Key catalog. I could have nar-
rowed the field even further by specifying package types rather than ignoring them in the Input panel.
Photo 3—Great, I can narrow down the sea of switchers depending on how much I want to spend or whether or
not a control pin exists on the part. I couldn’t wait to compare the circuit behavior using my substitute components.
www.circuitcellar.com
CIRCUIT CELLAR
®
together a recommended set of com-
ponents to give you the voltages you
request. I measured the no-load voltage
of a 9-VDC unregulated wall wart and
it was 14 VDC. My goal is to never
stress the wall wart into a situation
less than 9 VDC. So, I entered the
high- and low-input voltages accord-
ingly into the SMS panel in Photo 3.
I’m working on the 5-VDC step-
down circuit, therefore, the output
voltage window is loaded with
5 VDC. I did some reading and deter-
mined that the maximum current
draw on the 5-VDC programming
voltage is supposed to be 50 mA. I
doubled this figure to compensate for
my engineering fear factor. So, for
kicks I entered 100 mA in the output
current window. The only other
switcher option I’m concerned about
is the SHUTDOWN pin.
After I answered the questions on
the Input Panel, every simple switcher
that could fulfill my wishes was listed
(see Photo 4). The neat thing about
this panel is that you can school
yourself about simple switchers by
simply reading through the datasheets,
which are easily selected in the far
right fields. After pondering and read-
ing a bunch of datasheets, I settled on
the LM2594-5.0 for the 5-VDC pro-
gramming supply. I also purchased
some LM2594-ADJ parts just in case
this got to be too much fun. The
resulting simple switcher schematic I
received is shown in Photo 5.
I thought I was cruising
along until I saw the red
in Photo 6. After reading
the release/install notes
on the National site, it
seems the LM259X parts
and Java-based SMS
V.6.22 don’t get along
sometimes. The note stat-
ed that LM259X designs
tend to be unstable as far
as the V.6.22 software is
concerned. And if I read
between the lines correct-
ly, the actual design may
not work either.
The fix is to go back to
SMS V.4.3 or specify the
LM259X-ADJ and spike
the design with a Cff (feed
forward) capacitor. So, I loaded V.4.3.
Although the application is DOS-
based (see Photo 7), I got differing
component values, but again life is
good. I’ll use V.4.3 numbers and
V.6.22 parts for my project.
To me, there’s nothing worse than
not having the right parts on hand
when I’m in project mode. After toy-
ing with SMS, I decided that just
doing the math wasn’t making me
feel warm and fuzzy. I didn’t want to
commit to buying certain inductor
and capacitor values and then find out
I needed another value of one or the
other for real-world operation.
The newer SMS favors Coilcraft
inductors and the V.4.3 is hung on
Schott inductors. The simple switcher
datasheets suggest Panasonic HFQ
capacitors and the SMS programs like
Vishay-Sprague and Nichicon devices.
Most of the time capacitors are capac-
itors, but in switching applications,
the fine points of “capacitorism” must
be adhered to for best performance.
Pounding the Panasonic web site
and various other distributors’ web
sites revealed that the HFQ line is
obsolete. So, according to the
Panasonic web site, the best choice
for replacing the HFQ caps in my
application is the FK series. Just in
case, I gobbled up every SMT FK
series value I think I’ll need between
22 and 470 µF with working voltages
beginning at 16 and ending at 35.
The Coilcraft inductor parts called
out in V.6.22 proved to be valid and
up-to-date products. The Schott parts
were available from Digi-
Key, however, I could buy
a kit of Coilcraft parts for
the price of a five Schott
inductors. I’ll probably
ultimately need a 330-µH
inductor value. To be
safe, I picked up a couple
Coilcraft designer’s kits
so I’ll have a full range of
inductances to experi-
ment with.
The kits are useful.
And, Coilcraft will
replenish any of the
inductors you use from
your kit if you register
with the company. Of
course, the kits are just
that, designer’s kits, and
Issue 138 January 2002
57
Photo 6—This shot shows the dreaded phase margin warning. Instead of substituting parts
and changing component values to satisfy this warning, I decided to feed the same input
parameters into the older SMS and see what happens.
Photo 5—This looks nice, but, according to the SMS V.6.22 software, it won’t work. I could tweak the output capacitor
and inductor values to come up with a working circuit, but that defeats the purpose of the SMS application. Besides,
do I trust my manual calculations or the SMS output? The National folks are working on correcting this problem.
58
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
paycheck on. No matter how it
comes out in the end, simple
switchers will assure “the” project
will not be complicated and the
MMT-188EB guarantees that indeed
it will be embedded.
I
I also considered
raising the input
voltage and using
the step-down
approach for the 13-V
programming sup-
ply. Doing every-
thing including the
MMT-188EB power
with step-down cir-
cuits may be a bet-
ter answer than con-
verting to obtain the
13-VDC program-
ming voltage level.
So, I won’t trash this
idea until I’ve tested the original
LM78S40 idea. The MMT-188EB
power at this point is definitely a
step-down circuit no matter which
programming voltage scheme I end up
applying. My preliminary LM78S40
step-up circuit is depicted in Figure 1.
BEGINNING “THE” PROJECT
Soon, I will have all of the necessary
components to assemble “the” embed-
ded project. That means I’ve got lots
of work to do between now and the
next issue. Next time, I’ll show you
the completed power supply modules,
flash memory programmer circuitry,
describe the MMT-188EB firmware
that will direct the switching regula-
tors, and program the PIC.
I’m going to experiment with a
number of configurations and possi-
bly some other step-up ICs, so don’t
be surprised if I introduce additional
ideas in the next column. There are
a couple of things you can bet your
not intended to be used as your pro-
duction inventory. I purchased kits
C105 and C111 online directly from
Coilcraft (see Photo 8).
That about covers shopping for the
step-down circuit. The catch diode I
selected is the General
Semiconductor SGL41-40, which is
also one of the recommended parts
according to SMS V.6.22.
STEP UP OR FALL DOWN
It’s been a couple of days now and I
have finally decided how to approach
this area of the project. The simple
switcher is a great step-down solu-
tion. So, I took a look at the step-up
product line from National. I figured
this was like buying a car. If you have
a decent experience with a certain
manufacturer, you’ll usually stick
with that manufacturer and be
pleased. Not so for step-up simple
switchers. My application doesn’t
need 3- or 5-A back ends. In addition,
currently, the newest member of the
step-up family isn’t readily available.
The next series of logical thoughts
were spent on a LM78S40 design.
The LM78S40 is easy to use and can
be obtained easily from many
sources. To use it here, I would have
to add simple circuitry to emulate
the SHUTDOWN pin on the newer
simple switcher step-down switch-
ers. I want to keep the parts count
down and believe it or not, the
LM78S40 doesn’t use many more
parts than the simple switcher step-
up configurations. And note that the
latter would also need my SHUT-
DOWN pin emulation circuitry.
SOURCES
SDK
Datalight, Inc.
(800) 221-6630
(425) 951-8086
Fax: (425) 951-8094
www.datalight.com
SGL41-40 catch diode
General Semiconductor, Inc.
(631) 847-3000
Fax: (631) 847-3236
www.gensemi.com
MMT-188EB
Midwest Micro-Tek
(605) 697-8521
Fax: (605) 692-5112
www.midwestmicr
FK series capacitors
Panasonic
www.panasonic.co.jp/semicon/
e-index.html
SOFTWARE
To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2001/138/.
Fred Eady has more than 20 years of
experience as a systems engineer. He
has worked with computers and
communication systems large and
small, simple and complex. His forte
is embedded-systems design and
communications. Fred may be
reached at fred@edtp.com.
Photo 8—Kit C111 is the big inductor package. I like
the free refill policy because it makes it easy to keep a
variety of inductance values in the Florida room. I’ve
placed a much smaller 330-µH inductor from kit C105
next to its 330-µH first cousin from kit C111.
Photo 7—Like “the” project, this is 16-bit programming in action. Using the same
input parameters I used in SMS V.6.22, this version of SMS correctly specified
the LM2594-5, which is the 500-mA version, changed some components, and
didn’t have a phase margin problem.
www.saelig.com • saelig@aol.com
English for happy, prosperous &
blessed -- which is what I want my
customers to be!) to bring unique,
easy-to-use control and instrumenta-
tion products to USA from Europe.
• Over 50 different DIN-modules for:
analog i/p & o/p, thermocouple i/p,
digital i/p, relays, on 2000m network!
9pin > 9pin . . . . . . . . . . .
self-powered . . . . . . . . .
digital data on
PC FlashATA cards
software function
modules—finish quickly.
RS232, interrupts, sleepmode,
pre-emptive multitasking, easy to
attach LCD or keypad.
• CANbus adapter—recompile or log
Self-contained in
2" x 3" plastic box,
logging/alarm system
standalone or with PC.
see what’s new at www.saelig.com!
Industry-standard
card for PC’s
• Master, Slave or Bus monitor
• Low volt ICA93LV for 3V ic’s . .
power & information on 2-wires!
Boards for PCI/ISA/PCMCIA/PC104/VME/compPCI
Drivers for WIn95/98/NT,VxWORKS, pSOS, Lynx,
nce in a while I
take my own
advice. Back in
September 2001, I
described a four-decade, sweep fre-
quency, squarewave generator and
signed off saying, “This should also
have given you some good ideas for
future projects,” (“An Exponential
Sweep Frequency Generator,” Circuit
Cellar
134). It worked for me! I built
myself a manually tuned 10-Hz to
100-kHz sine wave generator with its
own frequency meter.
My original application required a
swept frequency clock generator.
After saying how exponential fre-
quency control gives you linear musi-
cal pitch, I couldn’t help thinking
that readers might prefer a sine wave
output. Never someone who turns
down a technical challenge, I figured
out how to get a sine wave from the
74HCT4046 chip by using some neat
analog signal manipulation.
This time, rather than an external-
ly applied voltage, the generator’s fre-
quency control element is a 10-turn
potentiometer (available as a special
order from Radio Shack, part no. 900-
8589). You no longer need to stabilize
the temperature of the current gener-
ator chip, because the reference volt-
age of the potentiometer changes
automatically to compensate for the
ambient temperature. [1]
The potentiometer has a resolution
of around one part in 5000, so you can
make small frequency changes. Each
turn corresponds to about 1.33 octaves.
Because it isn’t evident from the
potentiometer what frequency is
being generated, I added a four-digit
frequency meter using a PIC16C54
microcontroller. This meter would be
a useful building block for other proj-
ects that need audio frequency read-
out. On the other hand, you can leave
it out if you want to tune by ear or
match another signal.
Thus, I designed this project as two
separate units. Both fit into the wide
case shown in Photo 1. The frequency
generator section alone can fit into a
narrow case. Only the front panel size
changes. In this article, first I’ll explain
how to build the sine generator, then
describe the add-on frequency meter,
and cover the mechanical details last.
CHOOSE THE METHOD
My starting point was the existing
square wave 74HCT4046 oscillator
(Radio Shack part no. 276-2913). How
could I get a sine wave from it?
There are two basic methods, filter-
ing and shaping. Filtering is easier at a
fixed frequency. You take a square wave
or, better still, a triangular wave, and
filter out the higher harmonics, leaving
a pure sine wave at the fundamental
frequency. Unfortunately, the filter has
to tune over the same range as the input
signal. There is an ingenious way of
doing this over a small range [2], how-
ever, it isn’t practical over four decades.
That leaves shaping. A triangular
wave is fed into a nonlinear circuit that
rounds off both its peaks into an approx-
imation of a sine wave. One commer-
cial chip, the ICL8038, uses an array of
transistors with different bias voltages
to do this job. This chip also contains a
tunable generator with triangle and
square wave outputs. I was tempted by
it, but, unlike the 74HCT4046, it isn’t
easy to tune over a wide range.
Normally, the ’4046 uses a single
tuning capacitor that has a half ramp
on each end. That is, each end in turn
is level for half a cycle, then its volt-
60
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
FEATURE
ARTICLE
Tom Napier
After some thought
about one of his past
articles, Tom decided
that bigger and better
things were just
around the corner for
the project. Following
up, he used analog
signal manipulation
to get a sine wave
from the 74HCT4046
chip he used in the
earlier project.
o
A Wide-Range Audio
Generator
age ramps up during the other half
cycle. Unfortunately, the ramps are
curved at their lower ends.
Substituting two matched timing
capacitors, each grounded at one end,
gives you two beautifully straight
ramps, each from 0 to 1 V. As each
capacitor ramps up, the other is
clamped to ground. The peak ramp
voltages, and hence the output fre-
quency, are a function of V
CC
, a fea-
ture that came back to haunt me.
FROM RAMP TO TRIANGLE
Two half ramps are not the ideal basis
for a sine wave output. For that you
need a triangle, a voltage that ramps up
and then back down again. You can
achieve this by buffering the two capaci-
tor voltages and subtracting one from
the other, but you still have to subtract
a square wave to get a triangle.
There’s a style of design that I often
disparage as, “the triumph of ingenu-
ity over common sense.” One symp-
tom is that you keep adding tweaks
and corrections to avoid admitting
that your original design approach
was faulty. I was quickly beginning to
feel that way about this design.
There are three approaches to preci-
sion analog design. One is to work
out exact component values and to
use, for example, 0.1% resistors.
Another is to scatter trimmers all
over the board and spend a long time
adjusting them. The third approach is
to use 1% resistors and pick out pairs
that match. I used the last method.
The circled numbers in Figures 1 and 2
indicate components that should be
selected to equal each other.
Some trimmers are still necessary.
There are parameters, such as the
exact ratio of the chip’s ramp ampli-
tude to its square wave output, which
can’t be predicted in advance. Still,
the result was highly gratifying, a
good clean triangle, apart from narrow
spikes at the turn around points.
The spikes arose because the step at
the end of each ramp has a time con-
stant that is a characteristic of the
individual ’4046, about 1 µs with the
timing capacitors shown. The steps are
canceled by subtracting the square wave
output of the chip. Slowing down the
square wave with an RC filter improved
the final sine wave output enormously.
Now, it’s well shaped up to 200 kHz.
One trimmer adjusts the level of
the injected square wave, a second
corrects the DC offset, and the third
adjusts the exact shape of the sine
wave. All of these need an oscillo-
scope for best adjustment.
FROM TRIANGLE TO SINE
While researching triangle-to-sine
conversion circuits, I discovered
something that nearly caused me to
abandon this project. A similar gener-
ator design was published as long ago
as 1974. [3] Instead of a VCO chip,
this design used separate comparators
and op-amps. Its timing capacitor was
charged and discharged by two vari-
able current generators, which were
turned on and off by the square wave
output of the comparator.
This configuration had two disad-
vantages. First, the tuning resistor
was live. That is, it swung up and
down with the square wave, not
something I’d care to try with a 10-
turn potentiometer mounted on a
front panel. Also it required matched
PNP transistors to generate the posi-
tive charging current. I wanted to
stick with a readily available NPN
transistor array, the CA3046 (Mouser
Electronics stocks the CA3046 as part
no. 511-CA3046 for $1). I borrowed
the shaping circuit and carried on.
This shaper relies on the exponential
voltage/current characteristic of two
matched transistors. It works remark-
ably well if the input amplitude is well
controlled. Photo 2 shows the typical
result. Because the shaper’s output is a
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
61
Figure 1—This part of the schematic shows the expo-
nential current generator, tunable oscillator, and part
of the triangle wave generator.
differential current, I used this to set
the output amplitude by putting a
variable resistor between the two col-
lectors. This gives a clean sine output
at all amplitudes. (One inherent feature
of a sine shaper is that any residual
spikes on the peaks of the triangular
wave are attenuated to insignificance.)
The front panel amplitude control
also carries the power switch so that
when it’s turned on, the output ampli-
tude is zero. It’s a good idea to start
off low and adjust the level upward as
needed because this generator can put
out a 6-V peak-to-peak signal.
I left room on the front panel for a
slide switch to select a square, trian-
gular, or sine output. As Photo 3
shows, board space was too tight to fit
the extra components.
OUTPUT AMPLIFIER
To get an output of a few volts peak-
to-peak that can drive loads down to
8
Ω
, I used the venerable LM386
(Radio Shack part no. 276-1731).
Operating at its minimum gain of 20,
it has a bandwidth around 350 kHz. It
can handle a 100-kHz output but has
trouble driving a small load resistor
near the top end of the range.
I decided to run the LM386
between the 5- and –5-V rails to get
an output with no DC offset. Exact
balance can be achieved by using pin 7
of the chip as a trim input, for exam-
ple, by connecting it via a 470-k
Ω
resistor to a 10-k
Ω
trimmer between
the power rails. I didn’t bother, so I’m
living with a –50-mV output offset.
One snag is that the inputs of the
chip are referred to the negative power
rail. This is normally ground, but in this
case is –5 V. I had to AC couple the sine
shaper output currents to the amplifier
because they are referred to the positive
supply. The signal has to be substantial-
ly attenuated to drive the LM386, but
this avoids loading the current sources.
WIDE-RANGE TUNING
As in its square wave predecessor,
the oscillator is tuned with a current
between 0.1 µA and 1 mA. The cur-
rent, and hence the output frequency,
changes by one decade for every 60 mV
or so change in the voltage between the
bases of the reference transistor and cur-
rent source transistor. Unfortunately,
this 60-mV scale factor changes with
the ambient temperature, so you have
to compensate for it.
COMPENSATING FOR TEMP
Like before, I used the CA3046
multiple transistor arrays (Q1–Q5 in
Figure 1) to generate an exponential cur-
rent. The transistors are nearly the same
temperature, so you use one as a ref-
erence and one as the tuning current
source. A third corrects the control fac-
tor for temperature changes and the
remaining two become the sine shaper.
The emitters of Q1, Q2, and Q3 are
connected. Note that Q1 and Q3 are
already connected internally. Q3 has
its base grounded and has a 1-mA ref-
erence current fed into its collector.
An op-amp adjusts the common emit-
ter voltage until the collector of Q3 is
at ground potential. Thus, the refer-
ence current is the reference voltage
divided by the series resistor.
If the base of Q1 is grounded, its col-
lector current will almost exactly equal
the reference current, assuming the
transistors are well matched and at the
same temperature. As you make the
base of Q1 more negative, its collector
current—tuning control—falls. The ratio
between the current of Q1 and reference
current is an exponential factor of the
difference in base voltage multiplied by
a factor that is dependent on the tem-
perature (see “An Exponential Sweep
Frequency Generator”). The base of
Q1 is driven from the tuning poten-
tiometer via a buffer amplifier and an
attenuator. The full-scale potentiome-
ter voltage, which actually represents
the lowest frequency, is about –2.5 V,
so the attenuator has a ratio of 10:1.
Q2 is driven by a second reference
current. You may set its collector cur-
rent by adjusting its base voltage with
62
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Figure 2—The remainder of the triangle and sine shaper is shown with the output amplifier and amplitude control. Circled numbers indicate components that should match.
an op-amp and a second attenuator.
This attenuator has a 40:1 ratio.
The second reference current is one
tenth of the first. So, at any tempera-
ture, the base voltage of Q2 is precisely
what you need to generate a 10:1 cur-
rent ratio. This forces the output voltage
of the op-amp to be precisely what you
need to drive the tuning potentiometer
and generate a four-decade range.
This technique works only when
the control voltage is a fraction of an
adjustable reference. A DAC with an
external reference would be another
suitable control device.
THE MACHINE HAS LIMITS
This generator won’t satisfy an audio
purist. Its sine shaping circuit does a
decent job but is unable to generate a
sine wave with less than about 1% of
third harmonic distortion. Run it into
a notch filter and you’ll see what I
mean. The LM386 will generate even
more distortion if you drive it too
hard. It dislikes inductive loads; if you
connect an 8-
Ω
speaker it may sound
fine, but high frequency oscillations
can be present too if you don’t put a
damping network across the speaker.
When operating open loop, the fre-
quency of the ’4046 tends to drift with
temperature. Although you are apply-
ing a well-defined tuning current, the
thresholds of the on-chip comparators
have a slight temperature coefficient.
And, you mustn’t forget the tempera-
ture coefficient of the tuning capaci-
tors. All told, the output frequency
will drift as much as 1% with ambi-
ent temperature changes.
At the bottom of the frequency scale,
the tuning current is a fraction of 1 µA.
The 10-Hz square wave output shows
detectable jitter at its edges. These limi-
tations are a small price to pay for the
convenience of one-knob tuning.
One more warning: The triangle
generating circuit requires the square
wave output to have a fixed ampli-
tude. It won’t hurt the generator to
hang a cable and termination resistor
on the square wave output, but don’t
expect to get a clean sine wave at the
same time. Given more board space, I
would have added an output buffer.
The ’4046 is designed to have its
frequency locked to an external signal
and it contains three phase detectors for
such applications. These are not used
here but it wouldn’t be difficult to add
a current from a phase detector output
to the tuning control. This would let
you generate a sine or triangular wave
phase locked to an external square wave.
DISPLAYING THE FREQUENCY
It’s time to mix and match. You
now know how to build a four-decade,
square wave generator, get a triangle
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
63
Photo 1—The sine wave generator with its digital fre-
quency display fits a 6
″
× 4
″
plastic box.
Figure 3—This one-chip frequency meter can show frequencies up to 99.99 kHz. The display drivers are generic NPN and PNP TO-92 switching transistors.
tor’s square wave output. The meter
didn’t take much effort, it’s a stripped
down version of one I designed years
ago (“Count the Digits,” Circuit
Cellar
121). This one uses a 4-MHz
crystal, four-digit LED, 16C54A PIC
chip, and a few transistors (the firmware
is on Circuit Cellar’s web site) The
crystal that clocks the PIC deter-
mines the accuracy of measurement.
The input frequency is applied to
the timer pin of the PIC. Three PIC
registers act as a 16-bit counter with
an overflow flag. These are cleared,
and then allowed to count for 0.5 s.
At the end of this time period, the
count will be between five and
50,000. This binary number is dou-
bled and converted to decimal to give
a measurement of the input frequency.
The conversion gives a fixed point
(99.99 kHz) display, so changes of less
than 10 Hz are lost. As the sine gen-
erator can output more than 100 kHz,
the meter flags an overflow by show-
ing a dash for all four digits. The
leading zero is suppressed for frequen-
cies below 10 kHz.
wave from the oscillator chip, and
convert a triangle into a reasonable
approximation to a sine wave.
You can put the sine generator
board in a small box or build a fre-
quency indicator module that will fit
alongside it in a wider box. You may
not need an audio generator. If you
would just like a compact device to
indicate audio frequencies, read on.
The four-digit frequency meter in
Photo 4 is almost independent of the
rest of the generator. Its only connec-
tions are to 5-V power and the oscilla-
64
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
The LED is driven one digit at a
time by converting successive deci-
mal digits into seven-segment format
and putting the result on the 8-bit
port of the PIC. Seven bits drive the
display segments and the eighth is the
decimal point. The 4-bit port of the
Photo 3—The sine generator is squeezed onto a 2.6
″
×
3.2
″
prototyping board with isolated pads. Orthogonal
point-to-point wiring connects the components.
Photo 2—The output waveform is an adequate
approximation of a sine wave.
driver sets the peak current. I used a
16-pin resistor array, the second
“chip” on the board.
With some firmware changes and
an added decoder chip, this meter
could be extended to five or six digits.
Its 4-MHz crystal limits it to frequen-
cies below 960 kHz. However, with a
faster crystal it can measure frequen-
cies to almost 5 MHz.
MECHANICAL STUFF
The generator fits into a plastic box
with a 5.75
″
× 1.25
″
panel and a depth
of 4.25
″
. You may buy the box as a spe-
cial order from Radio Shack (part no.
910-3942). The box has slots about
PIC selects which digit is to be illu-
minated. Each digit is driven for 1 ms
every 4 ms, giving the appearance of a
continuous display. Display of the
previous frequency continues during
the pulse counting period so the dis-
play updates twice per second.
The mean current through an illu-
minated segment is 5 mA, but because
each digit is lit only a quarter of the
time, a peak current of 20 mA is
needed. Up to seven segments of any
digit may be illuminated, so the
device that controls which digit is on
must pass up to 140 mA. The PIC’s
ports can’t supply enough current to
drive either the segments or digits,
therefore I buffered them with NPN
and PNP switching transistors con-
nected as emitter followers.
For this job, I used the common
cathode displays sold by Radio Shack
(part no. 276-075). This means that
the seven-segment drivers are NPN
transistors and the four-digit drivers
are PNP transistors. The generic ones
sold in packets of 15 will do. A 100-
Ω
resistor in series with each segment
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
65
0.5
″
behind the front panel. These slots
hold a subpanel that carries the poten-
tiometers, hiding their mounting nuts.
The square and sine output connec-
tors are BNCs fastened to the front
panel. Their signal and ground connec-
tions protrude through holes in the
subpanel and are wired to the circuit
board. The other main features of the
subpanel are a cutout in its lower edge
and four small screw holes. This is
where the frequency meter is mounted.
FREQUENCY METER
The frequency meter is L-shaped.
One board carries the display and the
other carries the counter chip and LED
drivers. The display board was a head-
ache. Wiring up several identical chips
in parallel is always tricky because it
requires conductors to run with 0.05
″
spacing. Usually I mount such chips
on perfboard and use thin sleeved bus
wire to hook up corresponding pins.
This time I decided to make a PC board.
Running traces between chip pads
is simple if you’re using a profes-
sional drafting program and photo
Photo 4—The frequency meter is a compact stand-
alone module with many possible applications.
Call 530-297-6073 Fax 530-297-6074
See our new site www.jkmicro.com
DOS & Web server pre-installed
Realtime multitasking available with eRTOS
In-Circuit-Programmable Xilinx CPLD
512K SRAM, 512K Flash standard
66
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
LEDs. Using Plexiglas would improve
the visibility of the display.
The drive circuit is mounted on a
second board at a right angle to the
first. Twelve wire wrap pins are sol-
dered into holes in the display board.
These are then soldered side-on to the
traces on the driver board. For the
driver board, I used the type of proto-
typing board that has continuous cop-
per strips on it. As Photo 5 shows,
there’s lots of space to run wires on
the component side of the board to
complete the circuit.
I used one trick to make things eas-
ier. The NPN drive transistors all
need to have an input to their center
(base) pin and an output from the
emitter pin. I handled that by bending
their collector pins at right angles and
wiring them to a 5-V bus wire on the
component side of the board. The
base and emitter pins go in adjacent
holes, which have a knife-cut through
the trace between them.
A useful maxim: Don’t make hard-
ware difficult when software is easy.
The display chips are hooked up to
the most convenient PIC pins.
Because a look-up table translates
numbers to display segments, it can
be arranged to make the wiring easy.
Three wires link the counter to the
rest of the circuit. This helps to isolate
the display switching currents from
the sine generator. Figure 3 shows the
schematic of the frequency meter.
GENERATOR BOARD
The generator board layout is the
fruit of some three days of fudging and
fitting. It uses join-the-dots
technology; that is, the base-
board is a prototyping board
with an isolated pad round
each hole. Components are
inserted and soldered, then
bus wire interconnections are
made among them. Teflon
sleeving goes on all wires
that cross other wires. I put
the chips in sockets to make
debugging easier. After you
test it, glue this board to the
front subpanel.
I used the box as a jig
while the glue set. A screw
toward its rear edge fastens
the board to one of the pillars molded
into the box. There is a cutout in one
edge to clear the pillar that holds the
top of the box in place.
A cutout in the front edge of the
board provides clearance for the ter-
minal area of the amplitude poten-
tiometer. To get the potentiometer to
fit in the box, you need to clip off the
ends of the terminals and solder from
the rivets to the board. The switch is
wired in series with the 9-VAC input.
Note that the potentiometer must be
fitted to the subpanel before the board
is glued in place.
The BNC output connectors are
hardwired to the board. Two three-pin
connectors couple the board to the
tuning potentiometer and the display
board and a four-pin connector sup-
plies power to the board.
THE NEED FOR CLEAN POWER
The power supply illustrated in
Figure 4 is conventional. It connects
via a 5.1-mm coaxial connector to a
9-VAC, 300-mA wall transformer. A
pair of rectifier diodes and reservoir
capacitors supplies ±12 VDC to the 5-
and –5-V three-terminal regulators
that power the circuit.
Late in the design process, I discov-
ered two gotchas. One was that,
because the frequency display takes
some 80 mA, the 5-V regulator was
dissipating more than 0.5 W even
with no audio output. At maximum
Photo 6—Internal space is tight. The empty space was
left by the power supply, which moved to the back
panel to keep things cool.
plotting. It isn’t so easy when you’re
laying out the board by hand with
tape. It’s also tricky to drill holes in
the correct positions. My solution
was to use a scrap of perforated proto-
typing board that had solid copper on
one side. You can easily run traces
between pins when the pins have no
pads round them.
The only pads were one for a cath-
ode pin on each display chip and 12
for the connector to the driver board.
The rest of the wiring was done with
thin bare wire, direct from the display
pins to the adjacent bus strip on the
board. Where a wire crossed a bus, I
covered it with plastic sleeving.
To make the display flush with the
front panel, I cut a piece of bare perf-
board and used it as a spacer between
the display chips and PC board. Small
screws and 0.125
″
spacers hold the
display board the correct distance
above the subpanel. If you have a
piece of red Plexiglas, you could
mount it in the cutout in the front
panel and omit the spacer under the
Photo 5—The main board of the meter uses copper-
striped prototyping board. This view shows the compo-
nents and wiring on the top of the board.
Figure 4—The power supply unit has outputs of regulated ±5 V and
raw 12 V. The three-terminal regulators are held against the back
panel by the same screws that hold the board in place.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
67
output this rose to 1.5 W. Even the
lower dissipation is a bit much to
have inside a sealed box containing
sensitive equipment.
The answer was to replace the
plastic back panel with an alu-
minum one. Both the regulators and
PSU circuit board are bolted to it.
Make sure you don’t forget that the
heat sink of the negative regulator
must be insulated from the back
panel and the mounting screw.
Photo 6 shows the final configuration.
The other gotcha was an odd one.
Let me explain. When the displayed
frequency changes, the LED currents
change. This imposes a tiny voltage
change on the 5-V supply, just suffi-
cient to change the oscillator fre-
quency. The meter changes to show
the new frequency, changing the 5-V
supply and changing the frequency
again. As a result, the output fre-
quency was switching between two
values every 0.5 s.
Fixing this required stabilizing the
supply to the oscillator chip and
adding two resistors to a jam-packed
board. A 78L05 regulator supplies
both stabilized power to the oscilla-
tor and a reference for its control cir-
cuit. This meant bringing the unregu-
lated 12-V supply onto the generator
board; luckily, there was a spare pin
on the connector.
LOOSE ENDS
If you omit the frequency meter,
the generator can be fitted into a
smaller box. You may even want to
build the two parts in separate boxes,
each with its own power supply,
allowing them to be used independ-
ently. Add a 1-k
Ω
resistor in series
with the frequency meter input to
protect the 16C54 from static. And
connect a 100-k
Ω
resistor between
the input and ground so the input
doesn’t float when it is not in use.
After everything is built and work-
ing, you need to adjust the trimmers
using a frequency around 1 kHz. Look
at pin 7 of U5 with a scope and adjust
VR2 until you see a clean triangle
with no little steps at its tips.
Now, switch the scope probe to the
output and set VR5 to give an output
of about 2 V peak-to-peak. Adjust
VR3 until the positive and negative
half cycles have the same shape, and
then set VR4 to give a good approxi-
mation to a sine wave. The output
should be neither too pointy nor too
flat at the top (see Photo 1). There are
all sorts of clever ways of finding the
best setting, but they are probably not
worth the effort because you won’t
get a perfect sine wave.
So, now I have one more piece of
home-built test gear on my bench.
This manually tuned generator is a
useful complement to the thumb
wheel-controlled, NCO-based, preci-
sion sine generator that marked my
debut in Circuit Cellar back in
December 1997.
I
Tom Napier has been a space scien-
tist, health physicist, and designer of
space data receivers. Now, he pro-
vides electronics consulting services
and writes about his design projects.
SOFTWARE
To download the firmware, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2001/138/.
REFERENCES
[1] T. Napier, “Reference stabilizes
an exponential current,” EDN,
October 25, 2001.
[2] G. Deboo and R. C. Hedlund,
“Automatically tuned filter uses
IC operational amplifiers,”
EDN
, February 1, 1972.
[3] R. Dobkin, “Wide Range
Function Generator,” 115,
National Semiconductor, July
1974.
SOURCES
CA3046
Mouser Electronics, Inc.
(800) 346-6873
(817) 804-3848
Fax: (817) 804-3899
www.mouser.com
74HCT4046, LM386, box, poten-
tiometer, seven-segment displays
Radio Shack
www.radioshack.com
he Infrared Data
Association would
have you believe we
need wireless data com-
munications using infrared light. Most
of us automatically think, “Infrared,
oh yeah, my TV remote uses IR.”
After all, those hand-held timesaving
devices that help support our couch
potato lifestyle communicate using a
40-kHz modulated infrared beam.
The data rate of your IR remote is
not what would be considered high. It
doesn’t have to be high to command
changing a channel or muting a com-
mercial. Typical IrDA communica-
tion deals with moving more informa-
tion than just changing the channel.
And so IrDA continues to evolve,
beginning with serial infrared (SIR)
(115 Kbps or less), adding fast infrared
(FIR) (up to 4 Mbps), and looking
toward very fast IR (VFIR) (16 Mbps).
The IrDA standard does not include
TV remote communication.
The Infrared Data Association is
the non-profit trade association with
representatives from computer and
telecommunications hardware, soft-
ware, components, and adapter com-
panies throughout the world. Like
most standards organizations, the
IrDA ensures interoperability between
all types of devices. In this case, it
regards devices using infrared light to
communicate. The present standard
requires devices to be in proximity to
one another. That is, within line of
sight and not more than 1 m between
transceivers. What this assures is a
secure, one-to-one connection.
Doesn’t this seem limited to you?
You might be thinking that you
could do this by just making a direct
connection between devices. And
you’d be correct, at least for limited
applications using agreed on hardware
and universal connectors. But, you
have to look at the bigger picture.
By using the IrDA standards, the
physical connections are no longer
necessary. That removes the fragile
connector and cable from potential
problems. This allows the engineers
to focus on their devices and not how
they will interface with all other pos-
sibilities. It isn’t hard to imagine how
devices could easily interact with one
another. Today’s PCs and notebooks
communicate with printers and
PDAs. Soon your credit card may be
transacting with ATMs and such via
line-of-sight IR communications.
STANDARDS MAKE IT HAPPEN
I dislike having to attend most
meetings, however, I do appreciate
the need for them and the benefits
that can come to pass. The Infrared
Data Association, founded in 1993,
has defined a set of protocols for the
use of IR in the cordless transmission
of data. A set of three mandatory pro-
tocols (and a growing list of optional
protocols) make up the IrDA standard.
The three protocols are link manage-
ment (IrLMP), link access (IrLAP), and
physical signaling layer (IrPHY).
IrPHY, the bottom layer protocol,
describes the requirements of the
physical cordless hardware. The IrLAP
protocol layer is responsible for estab-
lishing a reliable connection and the
structured transfer of data among
devices. At the top, the IrLMP proto-
col supervises multiple channels of
communications through the IrLAP
and IrPHY. As part of the IrLMP, the
Information Access Service (IAS)
keeps track of the connected devices,
available services, and link parameters.
68
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Jeff Bachiochi
What Good is IrD, Eh?
t
FROM THE
BENCH
The
IrDA has
been
hard at
work
creating
a host of protocols. In
the first part of this
series, Jeff looks at
the protocol that cov-
ers the requirements
of the physical cord-
less hardware.
Part 1: Cordless Protocol
IrPHY
To conform to IrDA standards, the
devices used must meet certain crite-
ria. Let’s look at the requirements to
see what’s most important. The medi-
um for data transmission is infrared
with a peak wavelength between 850
and 900 nm. On the transmission side,
an IR LED is a directional device,
meaning the plastic package forms an
integral lens. The lens confines its
radiant output into a conical beam
pattern to either concentrate it in a
narrow beam (small angle) or spread
out over a wide beam (large angle).
IrDA defines the area of interest to
be a beam width of no less than 30°,
±15°. Maximum and minimum inten-
sity specifications are therefore defined
within this beam width. This specifi-
cation assures communication by
accepting a certain amount of mis-
alignment between communicating
devices while preventing radiated
energy from potentially interfering with
other devices within the same room.
The minimum intensity is required
to assure a connection at the maximum
distance. For standard IrDA, that dis-
tance is 1 m. A newer low-power
specification reduces the distance to
about 30 cm. Maximum intensity
eliminates flooding the room with
interference. Additional requirements
include minimum rise and fall times,
pulse widths based on the data rate,
and edge jitter tolerances.
On the receiver side, the IR sensor
must have at least the same 30°, ±15°,
cone of reception to accommodate
misalignment of a communicating
device. The receiver must be sensitive
enough to receive IR pulses of the
minimum intensity at the maximum
distance of 1 m (for standard devices).
While at the minimum distance, the
IR receiver must withstand becoming
saturated by a bombardment of IR from
the transmitter’s maximum intensity.
To cover this wide range of intensity,
some receivers contain a kind of gain
control. Specifications require the
receiver to return to maximum sensi-
tivity within a specified time, which
is based on whether the device is of
the standard or low-power variety.
IrDA specifies a bit error ratio (BER)
of not more than 10
–8
(one in 100
million). If the transmitter or the
receiver doesn’t live up to the specifi-
cations, then a dropout in communi-
cations could occur.
The specification could have
allowed TTL serial data to directly
couple to the IR transmitter and
receiver. However, that would require
the maximum transmitter current to
be sustained over the full bit time.
This would necessitate large power
requirements because current can be
high through the transmitting LED to
get maximum radiance. Many portable
devices use the IrDA protocol, so bat-
tery life is a serious issue. In order to
reduce transmitter current to a mini-
mum, the specified IrDA IR pulse
width is significantly shorter than a
bit time. Table 1 shows the details.
Devices sending data at 115.2 Kbps
or slower use an asynchronous format
in which an IR pulse is transmitted
for each space (zero) bit time (see
Figure 1). Signaling rates from 576 Kbps
to 1.152 Mbps use a synchronous for-
mat in which an IR pulse is transmit-
ted for each space (zero). Data rates of
4 Mbps use a synchronous format in
which each two bits are translated
into a single pulse during one of the
four 0.5 bit times, which make up the
2-bit time period.
THE RANGE
The range or distance between com-
municating IrDA devices is directly
related to the output power of the IR
transmitter. Initially, all devices were
required to communicate over a guar-
anteed distance of 1 m. Today, this
requirement is based on the device
type. You may be willing to trade
range for lower power requirements of
the portable device.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
69
S 1 1 0 1 1 0 0 0 S
TX
NRZ
Asynchronous
IRTX
RZI
1 1 0 1 1 0 0 0
TX
4 ppm
Synchronous
IRTX
0001 0010 0100 1000
Figure 1—The upper plots shown here show UART
transmission and the associated IRTX pulses pro-
duced. The lower plots show how higher data rates
using synchronous data combine bit pairs to produce a
single time slot IR pulse.
Decoder
RX
RESET
TIR1000
IRRX
Encoder
TX
16CLK
IRTX
16 1
6
7
9 10
16 1
16
16CLK
TX
IRTX
16
1
3 4
16 1
16
16CLK
IRRX
RX
Figure 2—This Texas Instruments device produces an IR pulse delayed by 0.5 bit time from the TX = 0 bit. A
received IR pulse produces an RX = 0 bit immediately upon reception.
Searching for discreet
IR transmitters and
receivers is a real pain.
Determining from the
device’s specifications
whether or not it com-
plies with the minimums
for the IrPHY standard is
often an exasperating
experience. Not all
devices are specified the
same way. LEDs are used
as IR transmitters. These
are specified by a number
of important parameters.
The infrared spectrum
begins at about 760 nm,
the upper limit of the vis-
ible spectrum. IR LEDs
specify the frequency
where their maximum
light output is generated
and a bandwidth parame-
ter (similar to a band-
pass filter) where the output drops to
50% of the maximum. The emission
angle is given in either total degrees
or in degrees (plus or minus) about
the mechanical centerline. This is the
angle at which the radiance falls to
50% of the maximum output.
Although these are important, each
is a no brainer. Interpreting irradiance
is more difficult. I’ve seen the irradi-
ance given in milliwatts (at a known
distance and area) and milliwatts per
centimeter squared (at a known dis-
tance). The IrDA specs are milliwatts
per steradian (mW/Sr). A steradian is a
square area equal in width and height
to the distance from the source.
At 1 cm, the area is 1 cm
2
; at 1 m,
it’s 1 m
2
. Notice that the area increases
by the square of the distance yet the
total irradiance is identical per stera-
dian. Unless a device is specified for
milliwatts at an area that’s the square
of the distance or is specified at 1-cm
distance, you must convert milliwatts
or milliwatts per centimeter squared
into steradians. I selected a Fairchild
QED523 IR LED to experiment with.
Selecting an IR receiver is more dif-
ficult. Packaging may consist of a
photodiode, phototransistor, photo-
darlington, or even additional circuitry,
as with photologic. Although the
reception angle and frequency sensi-
tivity may be similar among devices,
the sensitivity, drive capability, and
switching speed are not. Signal condi-
tioning is necessary to help increase
the advantages of a device.
IrDA minimum specifications
require 4 µW/cm
2
. I selected a Fairchild
QSE157 OptoLogic receiver, which
includes a photodiode, amplifier,
Schmitt trigger, output driver, and
voltage regulator. Under test conditions,
this device would receive an IrDA
transmission at only about 0.5 m (1 m
is the specification for standard units,
so this would fail as a stan-
dard device but pass as a
low-power device).
Fortunately, there is an
easier approach (and more
compact) than to select
individual components.
Prepackaged, IrDA-
approved transmitter/
receiver pairs are available
from many manufacturers,
including Agilent, Infineon,
Rohm, Vishay, and Zilog.
Photo 1 shows the proj-
ect, a simple serial IrDA
interface using a Zilog
ZHX1810 IrDA transceiver.
The present IrDA protocol
defines the communication
as bidirectional with data
rates from 9600 to 4 Mbps
(up to 115 Kbps with a
standard UART). Data is
framed (packetized) and
protected by using a CRC (CRC-16 or
CRC-32). The IrPHY layer is responsi-
ble for passing the frames only. The
upper layers of the protocol pack and
unpack the frames.
UART TO IrDA
Data transmission via a UART
needs to be only slightly modified to
be considered IrDA-compatible. As
stated earlier, to reduce the IrDA
power requirement to a minimum,
the actual IR on time is reduced to a
minimum of 1.62 µs (or a maximum
of 0.1875 bit time) during each 0 bit
time. Some additional circuitry is
required between the UART and IR
transmitter/receiver to encode/decode
serial bit timing and IR pulses.
This is usually accomplished by
providing a 16× (data rate) clock to a
circuit, which will divide each bit
time into 16 time slots. Some systems
can provide this clock because their
70
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Decoder
RX
RESET
MCP2120
IRRX
Encoder
TX
BITCLK
IRTX
1
6
7
9 10
16 1
16CLK
TX
IRTX
16
0
1
1
3
8
9
8
9
16 1
16CLK
IRRX
RX
16
0
1
Figure 3—The Microchip MCP2120 shown here produces an IR pulse delayed by
0.5 bit time on all TX = 0 bits. A received IR pulse produces an RX = 0 bit delayed by
a 0.5 bit time from the received IR pulse.
Signaling rate
Modulation
Minimum pulse width
Nominal pulse width
Maximum pulse width
9600–115,200 bps
RZI asynchronous
1.41 µ s
0.1875 bit time
0.1875 bit time (2.5% bit
time or 600 ns)
576,000–1,152,000 bps
RZI synchronous
17% bit time
25% bit time
30% bit time
4,000,000 bps
4 ppm synchronous
23% (48%) bit time
25% (50%) bit time
27% (52%) bit time
(adjacent pulses)
Table 1—As IrDA data rates have increased modulation techniques also have changed. The latter modifications were implemented to prevent infinitely smaller pulse widths.
NETWORK & COMMUNICATIONS SIMULATION
Powerful & easy-to-use PCB layout & editing
Reroute while move (full rubberbanding)
Component push & shove with springback
Extensive copper placement capabilities
Benchmark test leader with superior routing results
Combination of grid-based/gridless routing available
Highly flexible router provides complete control
Optimal part placement improves routing performance
Supports manual wire pre-placement
Powerful, yet easy-to-use fast, accurate simulation tool
Model & simulate end-to-end communications systems
Analog, digital & mixed system design capability
Industry-leading block libraries — channels,
encoders/decoders, modulators/demodulators
View simulation results in various methods
— time domain, frequency domain, xy plots,
log scale, eye diagrams and power spectra
SCHEMATIC CAPTURE, SIMULATION & PROGRAMMABLE LOGIC
Advanced modeless schematic capture
Library of 16,000 parts supplied, with 12 million online
Analog, digital and mixed-mode simulation
Patented co-simulation of SPICE, VHDL and Verilog
Suite of “virtual instruments” including oscilloscope,
wattmeter, spectrum analyzer & network analyzer
Design collaberation across the Internet
sales: 800.263.5552 • http://www.electronicsworkbench.com
That’s why we are the EDA supplier
of choice to over 150,000 users
worldwide.
72
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
UART may already have a 16× clock.
The Texas Instruments TIR1000 in
Figure 2 is a standalone IrDA
encoder/decoder (TL16C550C UART
has a data out 16× clock).
Although the TX serial data of the
UART is high, no IR pulses are creat-
ed. When the TX serial data goes low
(start bit), the TIR1000 starts count-
ing 16× clock cycles. At the end of
the seventh cycle, the IRTX output is
driven high. The IRTX is driven low
after three 16× clock cycles. This IR
pulse generation (equal to 0.1875 bit
time) is repeated if the TX serial data
is sending another 0 bit after the six-
teenth 16× clock cycle.
IR reception is done similarly.
Because the IR pulse is shorter than a
bit time, the circuitry must lengthen
the IR pulse into standard bit timing
for the UART. So, whenever an IR
pulse is seen at the IRRX input, the
TIR1000 drops its RX output for 16
16× clock cycles (1 bit time). A lack
of IRRX input pulses keeps the RX
output high. Notice that with this
scheme (transmitter/receiver), the
received data is delayed (in this case,
0.5 bit time) from the transmitted
data but does not cause problems
because the data timing is based on
the start bit.
When a 16× clock is not available,
there are other options. The
TOIM4232 from Vishay or MCP2120
from Microchip are similar devices
that contain an optional clock genera-
tor (see Figure 3). Data rate selection
is by jumper or via TX serial data
(while a mode pin is active). This
means that a UART can change data
rate (and the 16× clock), but this
device will not know there is a
change unless a software change rou-
tine is used to update the device.
You must take this into considera-
tion if it will be necessary to change
data rates within your application.
The default (initial) connection data
rate for IrDA is 9600 bps, so you must
at least run at 9600 bps to be IrDA-
compatible. Changing the data rate is
an option and not a requirement.
IR ENCODER/DECODER
You probably know Microchip as a
microprocessor manufacturer, so you
can easily guess the company’s
approach for the MCP2120. I consid-
ered using Microchip’s least expensive
processor, the PIC12C508. Microchip
was the first company to recognize
the potential merit of a microproces-
sor with low pin count. Although this
device has an internal RC oscillator,
which requires no crystal for applica-
tions not requiring high accuracy tim-
ing, I chose to use an external crystal
to achieve higher accuracy over tem-
perature and voltage. This limits the
I/O available to four, the minimum
necessary for this project (see Figure 4).
There are essentially two signals
that must be looked at for this appli-
cation, TX from the serial port and
IRRX from the IR receiver. Because
the IrDA protocol is half-duplex, I
won’t have to do two things at once,
however, the transmit path will have
priority over the receive path. The
shortest loop, which includes testing
for both signals, is shown in Listing 1.
The numbers in parenthesis show
the instruction cycle count for the
loop as five cycles. Using a standard
crystal frequency of 3.6864 MHz
(divides evenly into standard data
rates), you get an execution cycle
time of 1.085 µs, or:
The five-cycle loop will therefore take
5.425 µs to complete. The fastest bit
Photo 1—On the prototype, you really notice the small
size of the IR transceiver from Zilog.
74
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
that. An external T0CKI input must
be low for two clocks + 20, or:
The minimum received pulse is 1410 ns
(1.41 µs), so you’re in like Flynn.
The SEND_BIT and RECEIVE_BIT
routines are not fancy. I use in-line
cycle counting to assure things happen
at the right times. During the
SEND_BIT routine, I wait 0.4375 of a
bit time before enabling the IRTX
pulse for 0.1875 of a bit time. At
around 0.9375 of a bit time, I start
watching TX for another low. If I see
TX low, I jump to the top of SEND_BIT
again without going back to the loop.
If TX stays high, I jump back to the
loop routine to look for more action.
During the RECEIVE_BIT routine, I
clear the timer (to get ready for the
next IRRX pulse), wait 0.4375 of a bit
time, and then clear the RX output bit.
I start testing the timer for zero at
around 0.9375 of a bit time (no pulse
yet). If it has incremented within 0.125
of a bit time, I jump back to the top of
the RECEIVE_BIT routine without
setting the RX output bit (for another
continuous 0 bit time). If the timer
doesn’t increment during the sampling
period, I wait out the rest of the bit
time, set the RX output bit, and jump
to the loop to look for more action.
time of the TX serial output is 104 µs
(1/9600). So, you can see that pulse if
you are in the loop watching.
The shortest IRRX pulse is 1.41 µs
(the minimum acceptable pulse dura-
tion). There is a good chance you will
miss an IRRX pulse while in the loop.
The loop would be fast enough if you
increased the crystal frequency 10
times, however, 36.864 MHz is faster
than the 4-MHz maximum of the
PIC12C508, so that’s out.
An interrupt could solve this prob-
lem. Unfortunately, the PIC12C508
has no interrupts available. It does,
however, have a wake-on-pin-change
function. Note though that by the
time the oscillator starts from sleep,
you’ve missed a whole bunch of IR
pulses, so that won’t help either.
The saving grace here is that an IR
pulse won’t repeat for at least 104 µs,
which gives you plenty of time to do
something after you’ve seen the IRRX
pulse. About the only peripheral the
12C508 has is an 8-bit timer.
Although the timer doesn’t have an
overflow interrupt, it does have a
clock input for the timer. This means
that an external (selectable rising or
falling) edge will increment the timer.
You can read the cleared timer to
determine if an IR pulse has been
detected (timer can’t be zero). Now, if
only the IRRX pulse fits within the
input specifications. Let’s look at
Listing 1—This minimum timing loop of 5.425 µs will most likely miss a minimum IRRX pulse of 1.41 µs.
LOOP
BTFSS
GPIO,TX
; (1) skip next if TX bit is
high
GOTO
SEND_BIT
; (2) TX was low so go
produce an IR pulse
BTFSC
GPIO,IRRX
; (3) skip next if IRRX (low
pulse)
GOTO
LOOP
; (4/5) go look for more
stuff happening
RECEIVE_BIT
…
; routine to produce a ‘0’
for one bit time
GOTO
LOOP
; go look for more stuff
happening
SEND_BIT
…
; routine to produce an IR
pulse
GOTO
LOOP
; go look for more stuff
happening
www.circuitcellar.com
Issue 138 January 2002
75
ed, this requires extra I/O and soft-
ware with respect to solutions like
the MCP5120. However, when you
have complete control of the design,
these things are easily implemented.
Next month, I’ll rise up a little
higher on the IrDA layer ladder.
I
SOURCES
IrDA Specifications
Infrared Data Association
www.irda.org
MCP2120 Infrared encoder/decoder
Microchip Technology Inc.
(480) 786-7200
www.microchip.com
TI1000 Standalone IrDA
encoder/decoder
Texas Instruments, Inc.
(800) 336-5236
www.ti.com
TOIM4232 SIR Endec for IrDA
applications
Vishay Semiconductor GmbH
49 0 7131 67 2831
www.vishay.com
ZHX1810 Slim series SIR
transceiver
Zilog, Inc.
(408) 558-8500
Fax: (408) 558-8300
www.zilog.com
Microcross, Inc.
(478) 953-1907
www.microcross.com
RESOURCES
Infineon Technologies AG
www.infineon.com/us/opto/irdt/
content.html
Vishay Semiconductor GmBH
http://www.vishay.com/products/
optoelectronics/IRDCproduct.html
Jeff Bachiochi (pronounced BAH-key-
AH-key) is an electrical engineer on
Circuit Cellar’s engineering staff. His
background includes product design
and manufacturing. He may be reached
at jeff.bachiochi@circuitcellar.com.
SOFTWARE
To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2001/138/.
www.zilog.com/products/parts.asp?
id=ZHX1810
CIRCUIT CELLAR
®
Figure 4—The smallest available 8-pin microprocessor is used to encode and decode data between a UART and IR transceiver.
GIMME MORE
Although this project covering the
IrPHY layer of the IrDA standard was
specifically designed for the default
9600 bps, higher rates are possible.
Communication rates up to 57,600 bps
look feasible using this crystal. The
lack of extra pins limits practical expan-
sion of the project, however, it is func-
tional for those instances when the
minimum is all that’s necessary and
cost and real estate are at a premium.
Changing the data rate to achieve
faster communications is not an easy
task, because the UART can’t tell the
encoder/decoder what’s happening
(except where a 16× clock from the
UART is used). Although communi-
cating this change can be handled
with additional hardware configuration
inputs or via software commands, each
requires special nonstandard hard-
ware or drivers. This is not impossi-
ble; you just have to plan for it when
you’re designing the application.
As far as this project goes, if the
clock could be provided to the ’508
from the system, an extra I/O pin
would be released for use. With this pin
as a configuration input, your applica-
tion could use this input to signal a
change in the data rate and send out a
character (e.g., 0FFh). The ’508 could
measure the bit time and configure
the timing of the routines to corre-
spond to change. As I previously stat-
admit to being a
pack rat. For sure
there’s going to be
one heck of a yard sale
when I kick the bucket. Going
through dusty boxes out in the garage,
I recently came across my first hard
disk drive. I’m not sure why I saved it
all these years, but maybe someday
I’ll bronze it like the kids’ baby shoes.
A memento of my own personal won-
der age of computing, I suppose.
I have the yellowing manual,
Shugart SA600 Rigid Disk Drive OEM
Manual
, August 1983, right here in
front of me. Of course by then, com-
pany founder Al Shugart was long
gone from the company that bore his
name, having started Seagate
Technology in 1979.
The history of Al Shugart and the
hard disk drive goes back much fur-
ther than that, all the way to the mid
’50s when IBM (where Shugart worked
from 1951 to 1969) introduced the
first commercially available unit.
Shown in Photo 1, Random Access
Method of Accounting and Control
(RAMAC) must have made quite an
impression. The refrigerator-sized cab-
inet with 50 2
′
disks and vacuum tube
electronics weighed in at 1015 lbs. For
all that size, it packed a whopping 5-MB
(actually mega-7-bit EBCDIC) storage
space and a price tag roughly equiva-
lent to $10,000 per megabyte. Most
units were rented (rather than pur-
chased), for around $4000 (in mid ’50s
dollars) a month. Stick that in your
laptop and tote it!
In my mind, the hard disk deserves
a place on the marquee right up there
with multi-GHz CPUs and megabytes
of RAM. Fact is, the ability to crunch
through data at blinding speed isn’t
that useful if there’s no place to put
it. Furthermore, anybody who under-
stands what’s going on under the hood
knows a fast disk is just as important
as more megahertz (and more wait
states) when it comes to delivering
faster PC performance that’s visible
on the screen.
It’s only fitting that one of the most
interesting sessions at last summer’s
Hot Chips 13 conference wasn’t about
chips at all, but rather about develop-
ments on the disk front. Yeah, we’ve
come a long way, baby.
MORE BITS = MORE BRAINS
A presentation by Mr. Y.
Hashimoto of Toshiba explored that
company’s “1.8
″
Super Small Slim
HDD.” Super Small Slim is a lot of
adjectives, but I think a picture is eas-
ily worth three words (see Photo 2).
I suppose I would put the emphasis
on “slim.” In fact, better make that
anorexic. Targeting PC card plug-in
applications, Toshiba manages to
cram up to 5 GB in a skinny 5-mm
form factor. For those of you out there
who are metric-challenged, the drive
is less than 0.25
″
thick!
This isn’t a case of some miracle
eat-a-bunch-of-grapefruit diet at play.
Rather, staying thin calls for counting
every calorie, starting with the spindle
motor. By switching to an inner rotor
magnet design using a thin steel base-
plate, motor thickness is cut nearly in
half compared to Toshiba’s 2.5
″
disks.
Although it would be tempting to
downsize across the board, note that
the 1.8
″
drive, in the interests of
ruggedness, still uses the same size
ball bearings as the larger 2.5
″
unit.
The thin-is-in trend continues with
the electronics. Toshiba pushes the
envelope with so-called Chip Scale
76
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Tom Cantrell
i
SILICON
UPDATE
Recently,
Tom found
the first
hard drive
he owned
and was immediately
reminded of how far
disk drives have
come since the early
days. Now, he won-
ders just how much
better can hard disk
drives get?
Disko Boogie
FLASH CHALLENGE
On the desktop, a hard disk’s figure
of merit tends to boil down to three
factors: capacity, speed, and price.
However, the latest units target a
much broader application spectrum in
which other specs come into play.
Perhaps the best example is the
IBM Microdrive (see Photo 3). This
pioneering 1
″
unit made a lot of hay
when it was introduced a couple of
years ago with 340 MB on tap. At Hot
Chips, Mr. Thomas Albrecht from
IBM upped the ante, describing the
latest 1-GB Microdrive incarnation.
With more storage and bigger form
factor, Toshiba targets their 1.8
″
drive
as kind of a sneakerNet (i.e., the unit
can be walked between PC card slot-
equipped notebooks, PDAs, and such).
By contrast, IBM’s drive squeezes
into the even tinier CompactFlash (CF)
card format, which expands the
reach to nontraditional hosts
such as digital cameras and MP3
players. In these applications, the
competition isn’t so much other
disk drives as it is silicon, namely
flash memory.
Conventional wisdom has it
that flash memory should be
replacing disk drives, not the
other way around. But the fact of
the matter is, the disk drive wiz-
ards have more than managed to
hold their own (see Figure 2).
Does it make sense to use a
disk drive in a digital camera or
MP3 player? There are a number
of issues to consider beyond
a simple cost to bit compar-
ison. For instance, I’ve got a
pretty spiffy digital camera
with a 32-MB CompactFlash
card. For casual picture tak-
ing, the CF card is able to
hold a couple of dozen
decent quality shots.
However, I also use the
camera to take pictures for
my articles in Circuit
Cellar
. To maintain full
fidelity from my bench to
the printed page requires
maximum resolution and
no compression. At those
settings, 32 MB is only
enough room to store four
pictures. Furthermore, resolution will
continue to creep up with each new
generation of cameras.
Albrecht used the Canon QV3000
as an example. Even at a whopping
10-MB per shot, a 1-GB Microdrive
could handle up to 100 high-quality
(2048 × 1530) uncompressed pictures.
On the MP3 player front, Albrecht
showcased a forthcoming unit designed
by e.Digital (see Photo 4). Thanks to
the 16:1 MPEG audio compression
scheme, the unit delivers about a
minute of sounds per megabyte of
storage. That means the Microdrive-
based unit can store a dozen or more
CDs worth of tunes versus the one or
two CDs a typical (64- or 128-MB)
flash memory card could accommodate.
That’s all well and good, but there
are a few possible stumbling blocks
to consider. For example, unlike the
and “et” (extremely thin)
BGA packages. The result
is that the total thickness
of the assembled circuit
board and ICs is a mere
1.0 mm (that’s less than
one-twentieth of an inch).
Speaking of electronics,
while the size of the drives
keeps shrinking, the intelli-
gence doesn’t. Many of the
mechanical challenges asso-
ciated with downsizing,
such as shock detection,
compensation, and vibra-
tion cancellation call for
even more brainpower.
As you can see in Figure 1,
disk drive electronics is a
great place for embedded chips to strut
their stuff. In particular, note the sys-
tem-on-a-chip trend of integrating
nontrivial processing (for example,
32-bit ARM CPU) and memory (for
example, 2-Mb SRAM, 2-Mb
SDRAM) elements on the same die.
Besides cutting size, integrating
memory and logic boosts perform-
ance by minimizing cumbersome
interconnects. Thanks to all the MIPs
and buffering, the drive can transfer
data at up to 66.7 MBps, far faster
than the delivery of the actual bits to
or from the disk. However, in most
applications, throughput will be
somewhat less depending on the host
interface (e.g., ATA or PC card) and
access mode (e.g., DMA or I/O).
Remember the good old days when
drives were characterized as sounding
like a jet taking off? By contrast, at
22 dB idle, the Toshiba drive is liter-
ally whisper quiet.
As an aside, I noticed an article in
the local newspaper recently that dis-
cussed potential real estate develop-
ment near an airport. The article
cited a variety of regulatory and
health agencies that advise against
development in areas exceeding
55 dB. That proposed limit just hap-
pens to exactly match the acoustic
noise specification for that old SA600
out in the garage. Even though that
level is more like a Cessna than a
747, the new, quieter hard disks are a
boon for applications in which drives
should be driven, not heard.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
77
Flash Microdrive 2.5
″
HDD 3.5
″
HDD
1994
1996
1998
2000
2002
2004
2006
Year
0.001
0.01
0.1
1
10
100
$/MB
Figure 2—Confounding the predictions of some, disks not
only remain competitive with flash memory, but in fact are
increasing their cost-per-megabyte lead. IBM positions the 1
″
Microdrive in the gap between high-capacity disks and entry-
level flash memory cards.
Figure 1—Ironically, better chips help disk drives stay competitive in the battle with
flash memory. The electronics buried in the Toshiba 1.8
″
drive include a 66-MHz
ARM CPU and half a megabyte of RAM.
GMR-Head amp
Differential amp
with shock circuit
(Sony CXA3566)
VCM
SPM
Disk
HDA
GMR-Head
MPU
ARM7TDMI
66 MHz
SRAM 2 Mb
SDRAM 2 Mb
Serial FROM
2 Mb
R/W Channel
PCB
HDC (ASIC)
PCMCIA and ATA Interface
(Ultra-DMA 66 Mbps)
HDC
Buffer controller
Recording controller
ECC
Head positioning servo
controller
Motor driver
Spindle motor
controller and driver
VCM controller
and driver
Power supply
original RAMAC, which typically had
it’s own air conditioning system and
reinforced concrete floor, a disk drive
in a camera or MP3 player is going to
have a bit of a rougher go.
When a fumble-finger foul-up
inevitably comes to pass, the Microdrive
has a pretty good chance of survival.
It’s able to tolerate best-in-class non-
operating shock of up to 1500 g (up to
175 g operating) without damage.
Compare those numbers with the cor-
responding specs for my old SA600 in
the garage, a wimpy 30 g (10 g).
Recalling Newton’s words of wisdom
(force = mass × acceleration), it’s not
hard to figure out why the IBM unit is
so much more robust. The Microdrive
is a mere 16 g, versus 5.2 lbs for my
spinning boat anchor of yore.
Yea Newton giveth, but when com-
pared to flash memory, Newton also
taketh away. It requires a lot more
energy to spin a disk than move some
electrons. And when it comes to
portable gadgets like cameras and
MP3 players, minimizing power con-
sumption is the name of the game.
On the face of it,
power consumption
would appear to be a
showstopper for disk
drives in AA class (i.e.,
few hundred milliamp-
hour capacity) applica-
tions. When reading
data, the Microdrive
consumes about 1 W,
easily 10× the power
required by a flash
memory card.
However, a clever
design can mitigate the
problem. The trick is to
exploit the fact the Microdrive can
deliver data faster than your ears
(MP3) or even eyes (MPEG-4) need it.
Thus, by incorporating a low-power
SRAM data buffer, the duty cycle for
powering the disk can be
reduced from always on
(like a CD) to rarely on.
Considering an MP3 player
with a 1-MB SRAM as in
Figure 3, the disk duty
cycle would be only about
5%, just a few seconds of
disk activity for 1 min. of
audio. A beneficial side
effect of buffering is that
it enables shock protec-
tion because there’s plen-
ty of spare time to wait
for the disk to stabilize
and then retry.
THE WALL
So, what’s next? NanoDrives the
size of a penny? New materials?
Smarter chips? Just as with silicon,
there’s a lurking concern that the his-
torical more-for-less march of disk
technology will run out of gas.
Searching for answers, I came
across an excellent paper on the
subject from, surprise (not), IBM.
[1] In “The future of magnetic
data storage technology,” authors
Thompson and Best start by plot-
ting the historical trends for den-
sity, speed, materials, and such,
and then examine the likely
impediments to further progress.
So far, much as with chips,
moving forward has been a con-
ceptually simple process of scal-
ing. That’s not to minimize the prac-
tical challenges involved, but as well-
said in the article, “An engineer from
the original RAMAC project of 1956
would have no problem understanding
a description of a modern disk drive.”
When it comes to capacity, the sim-
plest figure of merit is areal density;
simply put, the number of bits per
square inch of disk surface. As shown
in Figure 4, the march of progress has
not only continued, but in fact accel-
erated. That’s because of technology
improvements such as magnetoresis-
tive heads and brainier chips, as well
as an overall more competitive mar-
ket and quicker turning designs.
Recognizing that pushing in one
dimension always pulls in another
yields some interesting insights. For
example, simply increasing density
has the ostensibly good side effect of
increasing data throughput. Same for
boosting the revolutions per minute,
which also reduces latency. But, when
it comes to speed, there can be too
much of a good thing if the electron-
ics are no longer able to keep up.
There’s the simple matter of getting
enough magnetism onto the tinier bit
cell as it flies by. That calls for new
materials (more coercivity), lower fly-
ing heights, and such, leading to
another own set of compromises and
tradeoffs. Then there’s the problem
finding chips that can work as the
raw data rate inexorably climbs
towards 1 Gbps and beyond.
Indeed, it’s interesting to note that
the 1-GB Microdrive is detuned to
spin at only 3600 rpm versus 4500 rpm
78
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Year of availability
10
6
10
5
10
4
10
3
10
2
10
1
10
–1
10
–2
1985
1990
1995
2000
2005
2010
2015
2020
2025
Areal density (Gb per square inch)
35.3 Gb per square
inch demo
Travelstar 18GT
Ultrastar 36ZX
Nonmagnetic
storage/
holography
Atom-
level
storage
Atom surface density
Figure 4—Will the wall come tumbling down? Not for a few years any-
way. With the superparamagnetic limit looming, things will get interesting.
Figure 5—Disks historically use longitudinal recording that
magnetizes a bit cell relative to the direction of head travel.
As that approach hits the wall, perpendicular recording into,
rather than onto, the media may come to the rescue.
Recording
medium
Inductive write
element
Perpendicular
magnetization
Shield
Track width
Read element
GMR sensor
Read current
Write current
Total is 105 mA
at 3.3 V
Total is 100 mA
at 3.3 V
Total is 370 mA
at 3.3 V
MP3 player
electronics
70 mA at 3.3 V
MP3 player
electronics
70 mA at 3.3 V
MP3 player
electronics
70 mA at 3.3 V
Buffer RAM
1 MB
15 mA at 3.3 V
Flash memory
card
35 mA at 3.3 V
IBM
microdrive
300 mA at 3.3 V
IBM
microdrive
300 mA at 3.3 V
5% Duty cycle
15 mA Average
Figure 3—A little SRAM goes a long way towards reducing power con-
sumption in a Microdrive-based MP3 player. The caveat is that the buffer-
ing scheme works best in applications with sequential access, in which the
disk bandwidth far exceeds the required data bandwidth.
for the original 340-MB version. So,
one argument is that drives will get
smaller, not just because it’s cute, but
because they have to in order to keep
velocity in check as density increases.
On the other hand, there’s the argu-
ment that hard drives best serve
applications that exploit their capaci-
ty advantage over flash memory.
The cost of a disk drive includes a
lot of overhead (motors, controller
chips, packaging, etc.) besides just the
head and disk. By contrast, flash
memory scaling is mainly a matter
of choosing an appropriate density
chip and deciding how many to use.
Thus, the cost per megabyte compet-
itive advantage of disks is best
exploited at maximum capacity. As of
today, that means a 1-GB, 1
″
drive
makes much more sense than a theo-
retical 250-MB, 0.5
″
drive, because
the latter is subject to direct competi-
tion from flash memory.
Looming on the horizon is the
scary-sounding superparamagnetic
effect. I’m no physics major, but you
don’t have to be a rocket scientist to
imagine that there might be problems
as the magnetized particles on the
disk surface get smaller.
Essentially, the direction of the
magnetic field of each particle fluc-
tuates randomly at temperatures
above absolute zero. That’s fine as
long as the fluctuations for all of the
particles in a bit cell combined do
not exceed the threshold for bit
reversal (i.e., turning a zero into a one
or vice versa).
Things get dicey near the super-
paramagnetic limit though. Scaling by
a factor of two can change the bit
reversal time from 100 years to 100 ns!
As the paper states, in the latter case
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
79
Photo 1—Talk about a cool setup. For a mid ’50s com-
puter installation with an IBM RAMAC disk, air condi-
tioning wasn’t an option, it was a must.
you’re dealing with something that is
a “permanent” magnet in “only a
philosophic sense.” However, a disk
that delivers only philosophically
accurate data isn’t going to cut it.
According to Thompson and Best,
current designs will start to experi-
ence superparamagnetic pain at areal
densities of about 40 Gb per square
inch. For a reference point for that
number, the current 1-GB Microdrive
delivers 15.2 Gb per square inch.
WHAT’S NEXT
Considering the historic pace, it
appears that trouble is lurking just
around the corner. However, as with
chips, reports of the demise of disks
may be premature.
Remember, the 40-Gb per square
inch wall presumes business as usual
(i.e., simple scaling of existing
designs). But there are a number of
outside-the-box alternatives, some or
all of which will come into play.
New write-head materials and
geometries offer a brute
force way out by increas-
ing the strength of the
magnetic field for
writes, thereby increas-
ing the stored energy den-
sity. Some of the burden of
declining signal to noise
ratio (SNR) can be shouldered
by smarter chips handling increasing-
ly clever and robust coding and error
correction schemes.
It turns out the behavior of a bit
cell near the superparamagnetic limit
depends to a degree on its shape.
Magnetic particles near the edge of
the cell are more of a problem than
those in the center. Maximizing the
area relative to the perimeter calls for
bit cells that are more square in
aspect ratio (1:1) than today’s long
skinny (16:1) ones. That approach
comes with the understanding that
something has to give, namely the
track-to-track spacing, which calls for
corresponding advances in write-head
precision and track following.
Taking the area-versus-perimeter
strategy even further leads to the con-
cept of perpendicular recording. In
perpendicular recording, the magnetic
field is stored vertically relative to the
head (see Figure 5). Wouldn’t it be
grand if you could make the disk a
tiny bit thicker rather than being
stuck with 2-D solutions?
The perpendicular recording con-
cept isn’t new, but until now it hasn’t
made it out of the lab. I get the feeling
the concept is like one of the last-
round swingers in a singles bar. It may
start to look a lot more attractive as
the clock winds towards closing time.
TERABIT OR BUST
The good news is that if some or all
of these techniques pan out, it will be
possible to boost the areal density sig-
nificantly. Maybe we’ll get to some-
thing like a 10-GB 1
″
Microdrive (i.e.,
150 Gb per square inch).
80
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
SOURCES
REFERENCE
[1] D.A. Thompson and J.S. Best,
“The future of magnetic data
storage technology,” 4.33, IBM
Journal of Research and
Development, May 2000.
Tom Cantrell has been working on
chip, board, and systems design and
marketing for several years. You may
reach him by e-mail at tom.cantrell@
circuitcellar.com.
Unfortunately, history would lead us
to believe that will be less than a
decade away, even presuming progress
slows as disks run into the wall.
Beyond that, who knows? It could
be that disks will have to make the
big switch from being a homogeneous
film to becoming a patterned media.
That could get expensive though,
because now each blank disk would
have to be masked like an IC wafer.
But there’s also hope (and more than a
bit of hype) for micromachined drives,
holographic 3-D storage, and even
atomic force microscopy (AFM).
Only one thing is for sure. As long
as there’s insatiable demand for bitmaps
and bloatware, the quest for more
storage will never cease. We’ve come
a long way from the original washing-
machine jukeboxes and my homely
SA600, but the disko beat goes on and
the spinning is just beginning.
I
Photo 4—In 1998, the Compact Flash Association
blessed a Type II specification that increased the
allowed thickness from 3.3 mm to 5 mm for Type I.
Portable devices that incorporate Type II slots, such as
this MP3 player designed by e.Digital, can take advan-
tage of the Microdrive option.
Photo 3—At about 1.5
″
on a side and little more than
0.5 oz, the 1-GB Microdrive from IBM can go where no
hard disk has gone before.
Photo 2—Here’s a
closer look at the Toshiba Super
Small Slim 1.8
″
drive. Five gigabytes
and at up to a 66 MBps data transfer rate, no waiting.
902 Waterway Place | Longwood, FL 32750 | 800·635·3355 | 407·262·0066 | Fax 407·262·0069
Visit our website @ www.micromint.com to see our complete line of OEM Solutions.
82
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
....by using real-time emulators.
HC12, HC11
8051
C166
C500
ST10
Super10
Philips XA
68300 family
Ubicom
” info see www.nohau.com/howto
Insert-ready sub-mini SBCs (small as 47x55 mm.) supporting the
Philips
achieved via GND circuitry, 6 to 8 layer PCB, by-
32 KB to 8 MB external SRAM & Flash (controller-dependent)
FlashTools enable on-board in-system (ISP) programming
C & CAN interfaces; ADC; Chip-Select signals
■ 255 Ericksen Avenue ■ Bainbridge Island, WA ■ USA 98110
IDEA BOX
THE
DIRECTORY
OF
PRODUCTS AND
SERVICES
AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.
ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2
″″ ××
3
″″
FORMAT. Call for current rate and deadline information. Send your disk and digital submis-
sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or email kc@circuitcellar.com. For more information call Kevin Dows at (860) 872-3064.
Suppliers Directory now available online. Check out our web site
www.circuitcellar.com to see who has what and how to get it!
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
83
Real Time Control and reading analog signals.
Control up to 16 STEPPER MOTORS simultaneously
Windows 95,98,00,NT; DOS, Linux,
84
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
Need to quickly get up to speed with the
PICmicro
award-winning PICmicro development
system even better. The new
172 Harvard Road
Waterloo, ON, N2J 3V3
Canada
519.886.4462
519.886.4253(fax)
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
85
86
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
87
88
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
❘ 2610 nw 147th place ❘ beaverton, or 97006 u.s.a. ❘ 503.533.0271
1 Parallel, 2 Serial, 2 USB ports
Integrated AGP Video Adapter
Integrated Sound & 120 WATT Spkrs
Logitech PS/2 Mouse & Keyboard
56K v.90 Lucent PCI Modem w/Fax
1.5GHz Intel Pentium 4 Processor
1 Parallel, 1 Serial, 4 USB & PS/2 Port
ATI Xpert 2000 32MB AGP Video Card
Sound Card & 120 WATT Speakers
107 Enhanced Internet Keyboard
Netgear PCI 10/100 Ethernet Card
P4 Mid Tower Chassis & ATX PS
40950 Encyclopedia Cr. ~ Fremont, CA 94538
1.7GHz Intel Pentium 4 Processor
1 Parallel, 1 Serial, 2 USB ports
E-VGA 64MB GeForce II AGP Video Card
P4 Mid Tower Chassis & ATX PS
Windows XP PRO & MS Intellimouse
107 Enhanced Internet Keyboard
Netgear PCI 10/100 Ethernet Card
1.5GHz Intel Pentium 4 Processor
1 Parallel, 1 Serial, 2 USB ports
P4 Mid Tower Chassis & ATX PS
Sound System & 120WATT Speakers
Windows 98, PS/2 Mouse & Keyboard
56K v.90 Lucent PCI Modem w/Fax
Tel: 510.353.1800 Fax: 510.353.0990
‘E’ FOR ECONOMICAL
COMPLETE & READY
TO LOAD ~ A RESELLER’S
DREAM COME TRUE.
A CORPORATE BUYER’S DREAM P4 WITH
64MB GEFORCE II, & NETWORK ADAPTER.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
89
90
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
92
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 138 January 2002
93
94
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
INDEX
85
Abacom Technologies
65
Abia Technology
84
ActiveWire, Inc.
74
ADAC
87
Advanced Circuit Designs Inc.
89
Advanced Embedded Systems, Inc.
22,37
Advanced Transdata Corp.
4
All Electronics Corp.
84
Amazon Electronics
79
American Raisonance Corp.
9
Amulet Technologies
83
Andromeda Research
92
AP Circuits
17
Arcturus Networks
88
Ash Ware Inc.
82
Athena Microsystem Solutions LLC
64
ATOP Technologies
84
Bagotronics
83
Basic Micro
29
CAN in Automation
85
CCS-Custom Computer Services
91
Cedar Technologies, Inc.
92
Conitec
11
Connecticut mircoComputer Inc.
85
Copeland Electronics Inc.
85
Cyberpak Co.
25
Cypress MicroSystems
C4
Dataman Programmers, Inc.
93
Dataprobe Inc.
90
DataRescue
82
Decade Engineering
The Advertiser’s Index with links to their web sites is located at www.circuitceller.com under the current issue.
Page
87
Designtech Engineering
88
Dreamtech Computers
1
Earth Computer Technologies
92
eBookTech.com
48
ECD (Electronic Controls Design)
83
EE Tools
(Electronic Engineering Tools)
11
EMAC, Inc.
86
eMicroTools
48
Engineering Express
83
FDI-Future Designs, Inc.
93
Futurlec
90
General Device Instruments
83
Hagstrom Electronics
16
HI-TECH Software,LLC
85
HVW Technologies Inc.
84
ICE Technology
89
IMAGEcraft
88,90
Intec Automation, Inc.
71
Interactive Image Technologies Ltd.
87
Intronics, Inc.
67
Intuitive Circuits, LLC
65,84
JK microsystems
30
JR Kerr Automation & Engineering
67
LabJack Corp.
86
LabMetric, Inc.
67
Lakeview Research
93
Lemos International
2
Link Instruments
85
Lynxmotion, Inc.
15
MaxStream
91
MCC (Micro Computer Control)
87
Micro Digital Inc
10
Microchip
86
Microcross, Inc.
91
microEngineering Labs, Inc.
72,81
Micromint Inc.
30
Midwest Micro-Tek
89
MJS Consulting
90
Mosaic Industries Inc.
73
MVS
92
Mylydia Inc.
91
Narly Software
7
NetBurner
95
Netmedia, Inc.
82
Nohau Corp.
90
OKW Electronics Inc.
92
Ontrak Control Systems
C2
Parallax, Inc.
90
Peter H. Anderson
82
Phytec America LLC
91
Phyton, Inc.
91
Picofab Inc.
88
Pioneer Hill Software
86
Prairie Digital Inc.
89
Pulsar Inc.
34
R4 Systems Inc.
31
Rabbit Semiconductor
47
Radiotronix, Inc.
84
R.E. Smith
16
Remote Processing
89
RLC Enterprises, Inc.
83
RMV Electronics Inc.
Inside a Digital Joystick
Developing with Open-Source TCP/IP
Working with NiMH Batteries: Build a Charger
A Guide to Varactors
It’s a SNAP: A Flexible Communication Protocol
Using a Median Filter
Avoiding PIC-Falls
I From the Bench: Wireless Communication the IrDA Way
I Silicon Update: eZ Embedded Web
I Applied PCs: “The” Embedded Project Continued
I Above the Ground Plane: UHF Voice Radio
Page
Page
Page
Communications
PREVIEW
139
ADVERTISER’S
86
RPA Electronics Design, LLC
59
Saelig Company
3
Scott Edwards Electronics Inc.
93
Senix Corp.
84
Sensory, Inc.
82
Signum Systems
84
Sirius MicroSystems
89
SmartHome.com
30
Softools
41
Solutions Cubed
92
Spectrum Engineering
82
Square 1 Electronics
89
Systronix
86
TAL Technologies
C3
Tech Tools
93
Techniprise Inc.
40,79
Technologic Systems
86
Technological Arts
90
Tern Inc.
86
Timeline
86
Triangle Research International Inc.
40
Trilogy Design
93
Vetra Systems Corp.
92
Weeder Technologies
23
Wittig Technologies
91
Xilor Inc.
87
Z-World
93
Zagros Robotics
’d like to think that the public and the airline industry would have come to its senses long before the events of last
September but maybe that’s what it took. Yes, air travel is down, flights have been cut, and airline stocks are in the
tank. It’s easy to correlate it all to security but I think the cause started long before September 11, 2001. Many of us won-
der if long-distance travel is worth the hassle. Security delays are but one more item on the list of reasons against it.
In truth, if the average business traveler was starting to think like me, it spelled big trouble already. The problems in the air travel industry were
brought on by years of neglecting fundamental business logic. Recent events might have provided a catalyst for companies and consumers to bet-
ter analyze travel necessities, but continually decreasing the convenience/cost/benefits of air travel would have demanded a commonsense reck-
oning eventually. Travelers can only take so much abuse in the name of low-cost flights.
For too long, the airline industry has had a “sale” mentality where volume and not service was the only objective. Although it creates intermit-
tent spikes in revenue, this pricing strategy has virtually no chance of success. The first thing a retail business does when it senses trouble is put
everything on sale to boost revenues. If that sale price is too low, the sale will succeed but profitability will suffer. Do you make the sale price more
attractive and sell twice as much the next time? The reasoning is, “We’re only losing a few dollars on each sale, but we’ll make it up in volume.”
Consumers, and I have to presume the airlines too, think that there is no piper to pay for continuing this rat race. When the cost of airline travel
competes with buses and trains, it doesn’t take a genius to predict that we’ve hit a critical price level. Even if services can be further reduced to
compensate, the inter-linked infrastructure of air travel demands a minimum profitability or both safety and convenience are lost. It’s no big deal
when a Greyhound bus gets a flat tire, but when you spring a leak at 30,000 feet you just can’t coast into the breakdown lane.
A lot has changed in the past 10 years and when it comes to handling people, let’s face it, airlines do a lousy job. By the time you board a
plane these days, you aren’t a happy camper and all you can think about is how much happier you’ll be when it’s over. It’s not like going to Disney
World where they understand the science of traffic management.
By design or default, more of us are looking at the convenience/cost/benefits issue when it comes to travel. I, for one, had already hit my limit.
The continued degradation of product service, regardless of how wonderfully inexpensive airline tickets seem, hardly makes up for the masochism
necessary to avail yourself of such services these days. After you sit on the runway for three hours because of equipment problems, land at the
airport and wait two hours to deplane because some idiot went out the wrong security door, try not to faint from hunger because “food service” now
means two cookies and a diet Coke, put in a claim for the luggage that apparently never made it onto the flight, miss the meeting and try to book a
new return flight even though most are now canceled, you then have scurry for a hotel reservation because now you’re stuck. Tomorrow, you get
to start the whole process over again!
The airfare pricing structure undoubtedly contributes to how this is all playing out. As you probably already know, just about everyone on the
same plane pays a different fare. The price you paid depends on whether you bought the ticket online, through an online wholesaler, through an
agent, just before boarding, 14-days ahead, under a full moon when the tide was high, and so on. The thing the airlines had going for them was
that just enough business people were buying the higher fare immediate-purchase tickets.
I can’t speak for the majority, but I’m not willing to just jump on a plane these days. If anything good has come from our sudden travel aware-
ness, it’s that at least this question is being asked by people at both ends of the trip. Everyone is looking for alternatives to business air travel.
Fortunately, today’s technology offers many alternatives. Coupled with a personal telephone call or two to put a face on the communication (or
at least an ear), e-mail has already revolutionized a lot of our business activity. Because of its efficiency, e-mail has become an accepted means of
business development and support. Face-to-face meetings are still important, but their frequency has been mitigated by e-mail.
The future, of course, is virtual face-to-face teleconferencing. Although there is a lot of it already going on, the costs are still relatively high.
When teleconferencing becomes as ubiquitous as e-mail and teleconferencing hardware as simple as a camera on your desk, then we’ll have a
true alternative to today’s air travel rat race. In my opinion, the air travel business has a bigger issue. Air carriers have to figure out a pricing strate-
gy that better balances people’s desire to travel at a reasonable cost and convenience with the rational necessity of doing it at a profit. Experience
has demonstrated that when airlines lose money their service suffers and customers feel neglected. The retail industry has a solution for this
predicament. It’s to raise the price and pamper the customers.
I’ll Stay on the Ground, Thank You!
INTERRUPT
i
steve.ciarcia@circuitcellar.com
96
Issue 138 January 2002
CIRCUIT CELLAR
®
www.circuitcellar.com
PRIORITY
Orders received by 4pm will normally be despatched same day.
• Plugs straight into parallel port of PC or
• Programs and verifies at 2, 2.7, 3.3 & 5V
• True no-adaptor programming up to 48
• Free universal 44 pin PLCC adaptor
• Built-in world standard PSU - for go-
• Package adaptors available for TSOP,
• Programs 8 and 16 bit EPROMs,
EEPROMs, PEROMs, 5 and 12V FLASH,
Boot-Block FLASH, PICs, 8751
microcontrollers and more
• Rechargeable battery power for total
• All-in-one price includes emulation
leads, AC charger, PC software, spare
library ROM, user-friendly manual
• Supplied fully charged and ready to use
• Programs wide range of 20 and 24 pin
logic devices from the major GAL vendors
• Supports JEDEC files from all popular
• 3 year parts and labor warranty
• Windows/DOS software included
• Free technical support for life
• Next day delivery - always in stock
Order via credit card hotline - phone
today, use tomorrow.
If you do not agree that these truly are the
most powerful portable programmers you can