7
9
25274 75349
0 8>
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 3 A U G U S T 2 0 0 1
INTERNET AND CONNECTIVITY
MSP430 Design
Contest Primer
A Two-Wire
RS-485 Network
A Closer Look at the AVR
Embedded Linux
CAN: Premier GPS Inc., (403) 295-8879, Fax: (403) 274-3021, tabsha@premier-gps.com
http://www.wilke-technology.com
An additional boost for your projects!
2 Channel Digital Oscilloscope
Only 9 oz and 6.3” x 3.75” x 1.25”
Small, Lightweight, and Portable
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 133 August 2001
3
Implementing a Two-Wire RS-485 Network
Poolside in April
Building a Solar-Powered Pool Heater
APPLIED PCs
Linux, All Grown Up
Fred Eady
ABOVE THE GROUND PLANE
Mic Check
A Communication System for Cyclists
Ed Nisley
MSP430 News Flash
Recognizing the Flexibility of Reprogramming
Jeff Bachiochi
SILICON UPDATE
Listening Chips
Tom Cantrell
14
22
34
46
52
56
COLUMNS
ISSUE
Rob Walker
Fixing What Isn’t Broken
New Product News
edited by Rick Prescott
Advertiser’s Index
September Preview
Priority Interrupt
Steve Ciarcia
Reset Registers
6
8
13
82
95
96
133
42
62
68
74
FEA
TURES
ChipCenter
ASK
US
THE ENGINEERS
TECH-HELP
RESOURCE
Let us help keep your
project on track or simpli-
fy your design decision.
Put your tough technical
questions to the ASK US
team.
The Ask Us research
staff of engineers has
been assembled to share
expertise with others.
The forum is a place
where engineers can
congregate to get some
tough questions
answered, or just browse
through the archived
Q&As to broaden their
own intelligence base.
★★★★★★★★★★
Test Your EQ
8 Additional Questions
THE FUTURE IS NOW
Wireless Internet-Based Remote Control Using a Pager Interface
by Bob Brown
In this article, Bob describes a simple manner of remote control using some technologies that
are time-tested, stable, inexpensive, and do not require that your house be wired to the
Internet. Motorola's FLEX Stack and CreataLink receiver make it possible for your weekend
retreat to be ready for your arrival with home control through the use of alphanumeric
pagers. What was once thought of as futuristic is right here and now.
July 2001
WHICH EMBEDDED IDE IS RIGHT FOR YOU?
by Geoff Revill
The embedded marketplace is changing rapidly. This growth poses a new challenge for
embedded designers. IDEs help to increase productivity by integrating best-in-class, scalable
tools that fit across the various stages of the development process. This month, Geoff takes
us through four routes to buying by categorizing the different types of decision-makers. In the
end, you'll walk away with the knowledge to determine the best IDE to suit your
needs.
July 2001
FINE-TUNING AN EMBEDDED IDEA
Part 1: The Land of BL2000
by Fred Eady
As article submission deadlines loomed, Fred needed an idea and he needed it fast. When
he began to pluck the strings of his bass guitar, inspiration hit. Z-World's BL2000, a member
of the Wildcat series, would be the next Circuit Cellar Online subject for him to explore. He's
done his time with Rabbits, so cats are the next item in his wild-kingdom adventure.
July 2001
CONNECTING THE DOTS
Working with Board-to-Board Connectors
Lessons from the Trenches
—
by George Martin
Don't be afraid to get creative with your daughterboard connector selections. This month,
George takes us down a number of paths for adding a daughterboard to your design. The
classic solution: chassis with backplane. With several manufacturers, good pricing, and avail-
ability, the moral of the story is to move with no fear in making that connection.
July 2001
YOU SAY TOMATO
Silicon Update Online
—
by Tom Cantrell
What's the difference between a mini-van and an SUV? Is it what's under the hood, or is it in
the marketing? Tom tackles the distinction between DSPs and micros this month and shows
us that the line is blurring between the two. Labels are inevitably misused and there are pure
DSPs and MCUs, but hybrids are now commonplace. If Cadillac can make an SUV,
why can't chip manufacturers follow suit?
July 2001
AN ELECTRIC LITESHOW DISPLAY
Part 2: Controlling the Lights with Software
Technically Speaking
—
by James Antonakos
This month, James moves from the hardware details to software in the second part of his
series. There are still 384 lamps, all individually controlled by only three signals from the
printer port, but now you can start thinking about the applications, like Ping-Pong games, a
mouse maze, simple animated scenes, fireworks, or a holiday tree with blinking
lights. A bit of imagination is the last ingredient in the LiteShow recipe.
July 2001
RETRO HUMOR CIARCIA STYLE
Part 4—
by Steve Ciarcia
Way back at the dawn of the microcomputer age, Steve Ciarcia was blazing a trail (some-
times literally) through the hardware and software issues of the era. At the request of many
of our readers, we've brought back a series of articles, written by Steve, chronicling the
design adventures of those early days in the Circuit Cellar. This month, it's chapter
three from
Take My Computer, Please!
July 2001
RESOURCES
• Internet Phones
Rick Prescott
• DVD-R, DVD-RAM,
and DVD+RW
Brant Schroeder
• Wireless Networks
Brant Schroeder
6
Issue 133 August 2001
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 EDITORS
Jennifer Belmonte
Rachel Hill
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 published
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 con-
sequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of reader-
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 con-
struct 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
CONTROLLER
Howard Geffner
CUSTOMER SERVICE
Elaine Johnston
ART DIRECTOR
KC Prescott
GRAPHIC DESIGNERS
Naomi Hoeger
Cindy Siegmund
Mary Turek
STAFF ENGINEERS
Jeff Bachiochi
John Gorsky
QUIZ COORDINATORS
David Tweed
Michael Smith
EDITORIAL ADVISORY BOARD
Ingo Cyliax
Norman Jackson
David Prutchi
TASK
MANAGER
s the saying goes, “If it ain’t broke, don’t fix it.”
Although that may be sound advice when it
comes to home appliances, it’s not always the right
strategy. For example, the Converse shoe company
was recently “reborn” under new leadership with the hopes of bringing
back the Converse name and the legacy of the Chuck Taylor basketball
shoe. What led to the bankruptcy of the company earlier this year was
more a lack of foresight over the last 10 to 15 years than a lack of good
intentions. After almost 50 years of success, the corporate leadership
felt that the power of tradition would still dominate the new era of scien-
tific and high-tech sneaker design. Management clearly underestimated
the benefits of technology and the influence of superstars such as
Michael Jordan. By the time Converse higher-ups acknowledged that
the market was changing, the company was several years behind the
other major manufacturers with regard to technology. It was too little,
too late.
In defense of Converse, similar stories could be told about compa-
nies in just about every industry. Time after time, narrow-minded individ-
uals have taken a perfectly good product (or company) and driven it into
obscurity simply by failing or refusing to fix something that “isn’t bro-
ken.” At the other end of the spectrum, the “New Formula” Coke fiasco
still serves as a reminder that breaking tradition just for the sake of
being able to have a new product can be equally as narrow-minded.
In sports lingo the argument goes something like, “Is the best
defense a good offense or is the best offense a good defense?” In reali-
ty, the most successful team will be a well-balanced mix of offense and
defense. And the same principles apply in the publishing world—there
has to be a balance between preserving tradition and promoting explo-
ration. That balance is our goal here at
Circuit Cellar.
Steve’s Priority Interrupt on page 96 is all about making sure that we
preserve the
Circuit Cellar tradition of being an effective classroom tool
for the next generation of engineers. And in case you haven’t caught
the gist of this editorial yet, I’m about to tell you that changes are com-
ing. If you’re not a big fan of change, then just keep reading the print
magazine each month and you won’t see anything different. However, if
you visit our web site in November, you’ll see a whole new
circuitcellar.com. We’ve spent almost a year fielding your opinions and
looking at our web traffic statistics to find out how we can improve our
site and we think that even those of you with an aversion to change will
welcome this one.
Don’t expect a mega-engineering portal that tries to be all things to
all people. And, don’t expect to have to pay a membership fee or deal
with annoying pop-up ads. You can expect to find quality content (old
and new) and reader services, but most of all, expect the process of
finding whatever it is you’re looking for to be a whole lot easier.
rob.walker@circuitcellar.com
Cover photograph Ron Meadows—Meadows Marketing
PRINTED IN THE UNITED STATES
a
Fixing What Isn’t Broken
Experience your Dream Computer today!
1 Parallel, 1 Serial, 2 USB ports
ATI Rage Fury Max 64MB AGP Video Card
P4 Mid Tower Chassis & 300W PS
Yamaha Sound Card & 520 WATT Speakers
Windows ME, MS Intellimouse & Keyboard
56K v.90 Lucent PCI Modem w/Fax
Reliable, affordable Dream Computers
help fulfill objectives and goals
1 Parallel, 1 Serial, 2 USB ports
ATI Xpert 2000 32MB AGP Video Adapter
P4 Mid Tower Chassis & 300W PS
Yamaha Sound System & 120WATT Speakers
Windows '98, PS/2 Mouse & Keyboard
56K v.90 Lucent PCI Modem w/Fax
PRODUCE, COMPILE & BURN! A COMPLETE P4
WORKSTATION WITH 17” MONITOR, 40GB HD & CDRW.
1 Parallel, 1 Serial, 2 USB ports
P4 Mid Tower Chassis & 300W PS
Windows 2000, PS/2 Mouse & Keyboard
Netgear 10/100 PCI Ethernet Card
NETWORK-READY WITH WINDOWS 2000
PROFESSIONAL & NETWORK ADAPTER FOR
UNBEATABLE BROADBAND PERFORMANCE.
AMD Athlon 4 Processor, 266MHz Bus
40GB 7200 RPM ATA 100 Hard Drive
ATX Professional Tower Chassis
1 Parallel, 2 Serial, 2 USB ports
ATI Rage Fury Max 64MB AGP Video Adapter
Creative Labs Live Value Sound
Windows '98, PS/2 Mouse & Keyboard
Netgear 10/100 PCI Ethernet Card
ATX Professional Tower Chassis
1 Parallel, 2 Serial, 2 USB ports
ATI Xpert 2000 32MB AGP Video Adapter
Yamaha Sound System & 120 WATT Speakers
Windows '98, PS/2 Mouse & Keyboard
56K v.90 Lucent PCI Modem w/Fax
CREATE AUDIO & DATA CDs WITH EASE!
CREATIVE LABS CDRW & 30GB HD DELIVERS
HIGH PERFORMANCE ON A BUDGET.
1 Parallel, 2 Serial, USB & PS/2 Port
ATI Xpert 2000 32MB AGP Video Adapter
Sound System & 120 WATT Speakers
Windows '98, PS/2 Mouse & Keyboard
56K v.90 Lucent PCI Modem w/Fax
ATX Professional Tower Chassis
RELIABLE, POWERFUL WORKSTATION
AT AN UNBELIEVABLY LOW PRICE.
WITH 40GB HD & 32MB VIDEO CARD!
Up to 1.5GB using 3x168-pin SDRAM
UltraATA/100, 2 IDE channels
2 serial ports & 1 parallel port
8
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
NEWS
Edited by Rick Prescott
CPU MODULE
The Tri-M Systems MZ104 is an x86 single board
computer in PC/104. Its compact size (3.55
″
× 3.775
″)
and off-the-shelf extended temperature rating (–40°C to
85°C) make this board compatible with embedded x86
technology in a wide variety of situations, including
hostile, mobile, industrial, military, medical, and tele-
com environments.
The module is the first single
board computer to use the revolu-
tionary MachZ System-on-a-Chip.
Buried within the MachZ silicon is a
586- to 133-MHz processor with
both the ISA and PCI bus derived
from the north and south bridge core
logic, as well as other I/O support.
For those applications in which
power consumption is critical, the
CPU clock is jumper-selectable to
allow processor speeds to be scaled
down from 133 to 33 MHz. The six-
layer circuit board is unique in that all components are
mounted on the top side of the board to reduce compo-
nent count and increase reliability.
Standard module features include two RS-232 serial
ports, parallel and USB ports, 1
2
C bus, dual watchdog
timers, and dual EIDE and floppy drive support. The
MZ104 module is fully compatible
with all standard PC software. It will
run any standard operating system
capable of running on a fully compat-
ible PC with FPU.
Pricing for the MZ104 (1 MB of
BIOS flash memory) is listed at $249.
OEM volume pricing drops below
$200.
Tri-M Systems Inc.
(604) 527-1100
Fax: (604) 527-1110
www.tri-m.com
64 Bytes of User Accessible EEPROM
NEW PRODUCT
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
9
Depending on your choice of color, prices are
$0.14 each or $1.44 in quantities of 500.
LEDtronics, Inc.
(800) 579-4875
Fax: (310) 534-l424
www.ledtronics.com
ULTRA-MINIATURE SMT LEDS
In response to the rise of surface mount technology (SMT),
the ultra-miniature 0603-Profile SurtLEDs have been devel-
oped. These LEDs are compatible with infrared and convective
reflow soldering and pick-and-place automated equipment.
The devices measure 1.6 mm × 0.8 mm. Their uses include
expanding the options for backlighting personal desktop
accessories, cell phones, keypads, palm pilots, and data com-
munication equipment.
The LEDs radiate a vivid light that is available in two
intensities: high efficiency and super bright. Six colors and
several related hues are available. You can get them on EIA
standard 8-mm tape 7
′
reels. In addition, the LEDs feature
viewing angles of 140
″
.
Solid-state design renders LEDs impervious to electrical
and mechanical shock, vibration, frequent switching, and
environmental extremes. With an average life span of 11
years, LEDs operate 17 times longer than incandescent
lamps. They are also environmentally-friendly because they
use 80% to 90% less operating power than standard incan-
descent bulbs.
NEWS
NEW PRODUCT
555 South 300 East #21, Salt Lake City, Utah, USA 84111
Tel:+1-801-534-1017 Fax:+1-801-534-1019 www.systronix.com
The JRealTime family • JStamp • SaJe • J104 • www.jrealtime.com
now -- so stop dreaming about embedded Java
using it. The JStamp module combines an aJile native execution controller, memory, JTAG debugging
EIGHT-CHANNEL AUDIO DAC
The PCM1608 is an eight-channel audio DAC, which
is ideal for high-performance, multi-channel audio sys-
tems. This device targets audio systems that require or
benefit from an eight-channel DAC solution, such as
7.1-channel playback formats. The general configura-
tion of a DVD audio system is a 5.1-channel (six chan-
nels) plus a two-channel stereo down mix, for a total of
eight channels.
Within these
systems, this
converter
replaces multi-
ple low-cost
stereo DACs by
combining
eight 24-bit
DACs and sup-
port circuitry
on a single inte-
grated circuit.
The converter uses a multi-level, delta sigma archi-
tecture to achieve excellent signal-to-noise (SNR) per-
formance. Functions include digital de-emphasis, digital
attenuation, soft mute, and zero flag for each channel.
The device provides single-ended analog outputs, thus
reducing the amount of external components. The
PCM1608 is packaged in an LQFP-48. It costs $4.95 in
1000-piece quantities.
Texas Instruments, Inc.
(800) 336-5236
www.ti.com
NEWS
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
11
2.4-GHZ SPREAD SPECTRUM TRANSCEIVER
Unlike radios designed from chipsets, LX 2.4-GHz fre-
quency-hopping spread spectrum (FHSS) transceivers are
agency-approved, ready-to-use modules designed for
rapid integration into larger volume OEM products. This
spread spectrum transceiver family offers manufacturers
a broad array of wireless capability
accompanied by comprehensive RF
development tools and support.
Five versions of transceivers plus
two repeater models provide varying
ranges and network configurations. All
transceivers have identical dimen-
sions, connectors, and software
requirements, so modules are inter-
changeable to suit your design needs.
Because the transceivers are based on 2.4-GHz FHSS,
they are highly resistant to interference and accepted
virtually worldwide for unlicensed use. They are the
smallest and lowest power in their category, ideal for
portable and hand-held applications.
The cost of the LX is based on power
output. The 3-mW version costs $129,
the 10-mW version costs $139, and the
150-mW version costs $159.
AeroComm, Inc.
(800) 492-2320
Fax: (913) 492-1243
www.aerocomm.com
MINIATURE RETROREFLECTIVE SENSORS
The VS3 series miniature retroreflective mode sensors
are designed to detect shiny objects accurately and elimi-
nate the “blind” response area of conventional photo-
electrics. The VS3 sensors are self-contained and offer
precision performance and exceptional range, making
them ideal replacements for remote and fiber optic sen-
sors in small feeder racks, conveyors, and other similar
space-limited applications.
Bifurcated lens separation creates a blind sensing
response area near the lens of conventional photoelectric
sensors. VS3 miniature retroreflective sensors use coaxial
optics to provide a complete sensing response area with
no blind spots. This feature allows sensing targets to be
placed as close to the sensor lens as needed.
The sensor design includes an advanced circuit board
for precision performance. List prices begin at $80.
Banner Engineering Corp.
(888) 373-6767
Fax: (763) 544-3213
www.bannerengineering.com
Edited by Rick Prescott
NEW PRODUCT
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 . . . . . . . . .
pre-emptive multitasking, easy to
• 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
• Control or program I
• Low volt ICA93LV for 3V ic’s . .
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
13
READER
I/O
CMC’s low cost converters adapt any
use with RS422 or RS485
devices
• Adds multidrop capability to
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
BY ENGINEERS, FOR ENGINEERS...
Your EQ section has been really useful and interesting
to me and you have a very well-balanced set of questions
for all the fields. How about providing even more ques-
tions each month?
Rudolf from France
Just wanted to compliment you guys on providing an
electronic version of Circuit Cellar!
I have been an avid subscriber since your first year and
I have almost all of your back issues, but as you might
imagine, the boxes are getting pretty heavy. I have been
waiting (praying) for one or more of the many magazines
to which I subscribe to be offered in electronic format.
Hats off to you guys for doing this. I'll gladly tolerate
any glitches or growing pains we collectively endure, just
don't give up the journey!
J
ohn Eckl
EDITOR’S NOTE:
The following corrections are from the June 2001 issue.
On page 65, in the first column, the paragraph starting with
"The Amidon..." should say "material 61" rather than
"material 64".
On page 21 there is an error in the upper left-hand corner
of Figure 2. The part labeled as an AD587 should be an
AD586.The part is correctly listed in the text as AD586KN.
The following correction is from the July 2001 issue.
The schematic (Figure 3) on page 52 did not print properly
and may be hard to read so we have made a viewable file
available on the Circuit Cellar web site. Point your browser
to ftp.circuitcellar.com/pub/Circuit_Cellar/2001/ and select
the 132 folder and then choose the pg52 file to view or
print the schematic.
14
Issue 133 August 2001
www.circuitcellar.com
distributed con-
trol system consists
of a network of micro-
controller-based (intelli-
gent) controllers. With the availability
of faster, cheaper, more powerful
microcontrollers, control engineers
are switching to a design based on dis-
tributed control. The geographical
separation of hardware and software
in functionally independent units cre-
ates a highly configurable, flex-
ible, and more reliable system.
Distributed computing inher-
ently supports parallel process-
ing and multi-tasking. These
intelligent distributed con-
trollers need to communicate
with each other or a central
computer. Because the con-
trollers are widely distributed
in the plant, the most cost-
effective networking option is
to use a high-speed serial link.
Many serial communication
standards are available; RS-485
is the most popular because of
its differential transceivers
offering good noise immunity
in the industrial environment.
The RS-485 standard recom-
mends specification for the
transceivers but does not speci-
CIRCUIT CELLAR
®
FEATURE
ARTICLE
Wouldn’t every engi-
neer welcome a high-
ly configurable, flexi-
ble, and reliable sys-
tem? Praveen knew
the answer, so he
wants to talk about
his distributed control
system. With the per-
sistent advances in
microcontroller tech-
nology, he says this is
the way to go.
fy type of cable and termination. The
RS-485 transceivers available today
allow you to design a multi-drop,
four-wire, full-duplex or two-wire,
half-duplex serial communication net-
work. The network would have a
maximum speed of 10 Mbps and max-
imum distance of 4000
′
. Texas
Instruments provides detailed infor-
mation about the design issues for an
RS-485 network. [1]
You can construct a typical two-
wire multi-drop network as shown in
Figure 1. A single RS-485 transceiver
package (e.g., TI’s SN75176) contains
a transmitter and receiver with sepa-
rate enable lines. The differential out-
put and input of the transmitter and
receiver, respectively, are shorted
internally and only two wires are
available for interconnection to other
devices on the bus.
A node (controller) can transmit its
data onto the network by enabling its
transmitter. Similarly, it can receive
the data by enabling its receiver. In a
multi-drop configuration, each node
enables its receiver permanently so
that it can receive all of the network
data, if required.
PROTOCOL IMPLEMENTATION
ISSUES
For a node to communicate within
a network, a set of rules or network
protocol is required so that data can
Praveen P. Deshpande
a
Implementing a Two-
Wire RS-485 Network
Key parameters
Specification limits
Maximum common mode voltage
–7 V to 12 V
Receiver input resistance
12-k
Ω
minimum
Receive
sensitivity
±200
mV
Driver
load
60
Ω
Driver output short circuit limit
250 mA to –7 V to 12 V
T
R
T
R
120
Ω
485
120
Ω
Figure 1—
The multi-drop, two-wire, half-duplex RS-485 network
shows two nodes connections. The cable used to connect these
nodes is terminated at two ends to avoid reflections. Each node
has a transmitter and receiver connected in parallel.
www.circuitcellar.com
Issue 133 August 2001
15
CIRCUIT CELLAR
®
be transferred in an organized man-
ner. In a distributed network, each
microcontroller is called a node. The
transceiver and network protocol
determine the maximum number of
nodes in a network. The RS-485 stan-
dard does not define any protocol.
Thus, each developer is free to devel-
op a protocol to suit a particular
application. However, this creates a
problem for inexperienced developers
because they don’t have guidelines.
Each node transmits a block
of data with predefined start
of block (SOB), end of block
(EOB), possibly a header, and
data bytes grouped together.
The group is typically referred
to as a data packet. When any
two or more nodes attempt to
transmit data packets simulta-
neously, a situation called
packet collision occurs and
the transmitted data is lost.
Designing a protocol that sup-
ports packet collision adds to
the complexity and software
overhead of detecting the col-
lision at each node.
One simplified approach is
to employ one node as a net-
work traffic controller (data
packet router), which ensures
that no two nodes speak at
the same time. As a traffic
controller, it scans each node
and gives it a chance to com-
municate gracefully.
This master/slave architec-
ture dedicates one microcon-
troller (node) as master. All
other network nodes (slaves)
transmit or receive data under
direct control of this master
node, thus avoiding a possible
packet collision. Because all of the
data is routed through the master, it
has the option of transmitting the
network data to a central computer
(see Figure 2). The condition that only
one node speaks at a time results in a
half-duplex communication.
MCS 51 ARCHITECTURE SUPPORT
The Intel MCS 51 microcontroller
architecture has an on-chip UART,
which supports a multiprocessor seri-
al communication. [2] In this mode
(mode 2 or 3), the UART transmits 8
data bits and 1 control bit (TB8). The
processor can be programmed to gen-
erate a serial interrupt if the control
bit is received as one.
This feature can be used to design
an RS-485 master/slave network using
an 8x51 microcontroller. Each net-
work node can be assigned a unique
8-bit address. The MCS 51 architec-
ture has a special-function register
(SCON) for serial port control and
configuration (see Figure 3). The SM0
and SM1 bits specify the serial port
mode. The SM2 bit enables the multi-
processor communication feature in
modes 2 and 3. If the SM2 bit is set to
one, RI will not be activated if the
received ninth data bit (RB8) is zero. If
either the RI (receiver interrupt flag)
or TI (transmitter interrupt flag) bit
generates a serial interrupt, the ISR
has to find out whether RI or TI gen-
erated the interrupt.
The TB8 bit holds the control
bit (ninth bit) and the SBUF
special function register holds
the 8-bit data to be transmitted
or received. The serial port is
full duplex, meaning it can
transmit and receive simultane-
ously. It is also receive-
buffered, meaning it can com-
mence reception of a second
byte before a previously
received byte has been read
from the register.
When the master processor
wants to transmit a block of
data to one of several slaves
(nodes), it first sends out a
(node) address byte with the
control bit set to one, which
identifies the target slave. The
address byte differs from a data
byte in that the control bit is
one in the address byte and
zero in the data byte. When
SM2 is a one, no slave will be
interrupted by the data byte.
An address byte, however, will
interrupt all slaves so that each
slave can examine the received
byte and see if it is being
addressed. The addressed slave
will clear its SM2 bit and pre-
pare to receive the data bytes.
Master
(router)
node
Controller
node one
Remote
central
computer
Controller
node two
Controller
node…N
Two-wire RS-485 serial interface
Figure 2—
The two-wire
RS-485 network is con-
figured in a master/
slave architecture with
an optional master con-
nection to the central
computer. This configu-
ration enables control of
this distributed system
from a control room.
RI
MSB
LSB
where SM0 and SM1 specify the serial port mode as follows:
SM2—Enables the multiprocessor communication feature in mode 2 and 3.
In mode 2 or 3, if SM2 is one, then RI will not be activated if the receiver
ninth data bit (RB8) is zero. In mode 1, if SM2 is one then RI will not be
activated if a valid stop bit was not received. In mode 0, SM2 should be
zero.
REN—Set by software to enable serial reception. Cleaned by software
to disable reception.
TB8—The ninth data bit that will transmitted in modes 2 and 3. Use the
software to set or clean TB8.
RB8—The ninth data bit that was received in mode 2 and 3. In mode 1,
SM2 is zero, RB8 is the stop bit that was received. In mode 0, RB8 is not
used.
TI—Transmits interrupt flag. Set by hardware at the end of the eighth bit
time in mode 0 or at the beginning of the stop bit in the other modes
(in any serial transmission). Must be cleared by the software.
RI—Receives interrupt flag. Set by hardware at the end of the eighth bit time
in mode 0 or halfway through the stop bit in the other modes (in any serial
reception except SM2). Must be cleared by the software.
SM0 SM1 Mode
Description
Data
rate
0
0
0
Shift register
f
OSC/
12
0
1
1
8-bit
UART
Variable
1
0
2
9-bit
UART
f
OSC
/64 or f
OSC
/32
1
1
3
9-bit UART
Variable
SM0 SM1 SM2 REN TB8 RB8 TI
Figure 3—
The serial port control (SCON) register is part of the MCS 51
architecture. Mode 2 or 3 and the SM2 bit enable multiprocessor communi-
cation, which is useful for distributed RS-485 network implementation.
16
Issue 133 August 2001
www.circuitcellar.com
CIRCUIT CELLAR
®
The slaves that weren’t being
addressed leave their SM2 bit set and
go on about their business, ignoring
the coming data bytes. This scheme
puts minimal software overhead of
processing unwanted network data at
each non-addressed slave.
IMPLEMENTATION
My network implementation is
based on the Dallas 80C320 high-
speed microcontroller family. The
80C320 has enhanced MCS 51 archi-
tecture with two hardware serial
ports. One microcontroller board acts
as a master or router node. For the
router, one serial port (with RS-485
interface) is used to communicate
within the network and a second seri-
al port (with RS-232 serial interface)
is used to communicate network data
to a PC (operator console) located
remotely in the control room. Each
node is based on the 80C320.
Because I’ve used SN75176, RS-485
transceiver chips, I can have a maxi-
mum of 32 nodes in the network.
There are transceivers available on
the market, such as MAX1487E, that
support 128 nodes. The router allo-
cates a time slice to each node on a
round-robin basis so that every node
gets a chance to transmit its data onto
the network. Each data packet has a
header containing information about
its source, destination, packet num-
ber, and length of the packet. The
remaining portion of the packet con-
tains actual data bytes.
I defined a data structure for a net-
work packet (see Listing 1) for easy
insertion and extraction of data. With
the use of a union, the incoming
packet data can be read into
u.Buf and
individual packet component infor-
mation (e.g., sender and receiver
address, and packet length) can be
read from the structure members.
This data structure enables me to
modify the packet without modifying
the code to handle it.
While transmitting the packets, the
node and router both compute and
compare the checksum of the data
block to ensure its validity. This is
necessary to detect data corruption
during the data travel along a trans-
mission channel.
In order to address 32 nodes, a 5-bit
address is required. The address byte
has eight bits. I used three spare bits
to embed commands into the address
of the node. This helps me reduce
network traffic and improve the sys-
tem response time. In a distributed
environment, each node may be han-
dling an independent control task and
may not be free to communicate with
the router, especially if it is executing
its critical section of the code.
In order to avoid frequent time-out
at the router because of such node
unavailability, the router algorithm
first checks its availability by sending
Listing 1—
Here’s the data structure for a network packet containing source and destination information.
Defining a union to share the memory for structure and an array simplifies the insertion and extraction of the
packet data. It also provides the flexibility to modify the packet structure without an overhead of code.
// this is packet header
struct _hdr {
unsigned char Msg_Len; // length of one packet
unsigned char BCmd;
// reserved (used for debugging)
unsigned char RCmd;
// reserved (used for debugging)
unsigned char From;
// source address
unsigned char To;
// destination address
unsigned int PNo;
// packet number
};
#ifndef MAX_PACKET_SIZE
// packet size can be defined
//else where
#define MAX_PACKET_SIZE 255
#endif
typedef union {
// simplify the packet handling
//task
struct _packet {
struct _hdr Hdr;
unsigned char Msg[MAX_PACKET_SIZE - sizeof(struct hdr)];
} Packet;
unsigned char Buf[sizeof(struct _packet)];
}U;
Listing 2—
The router (master) is a traffic controller node. It monitors all of the network nodes in a round-robin
fashion giving each one a chance to transmit or receive data to and from the RS-485 network.
// router algorithm pseudo code
#define MAXNODES 3
// assume that we have three nodes
int CurNode =0;
// active node
int NoOfNodes = MAXNODES;
bit MsgFromPC;
// flag informs that Msg from PC is pending
//in the Queue
while(1) {
// pick one message & send it to destination node
if (MsgFromPC) TransmitNetMessage();
// Does node want to communicate its data to PC?
ReadNodePacket(CurNode);
// Any data to deliver to PC?
SendPCPackets();
// Any Msg pending in PC Queue?
RecvPCPackets();
// Proceed to next node
if (++CurNode > NoOfNodes ) CurNode =1;
// nodes are numbered sequentially
}
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
19
a
REPORT_STATUS command embedded
in the address byte prior to sending
any other command. The router con-
tinues with further data communica-
tion only if the node responds with
NODE_FREE status. I’ve used only four
embedded commands, including
REPORT_STATUS, TRANSMIT_DATA,
work data, respectively. The node
reports the status (empty or full) of
these buffers while responding to a
REPORT_STATUS command. The node
status assists the router in asserting
one of the four embedded commands.
This scheme enables communication
with the node at the most appropriate
time—when it’s free and has room to
accept or transmit data.
Listing 2 shows the router algo-
rithm. The router scans each network
node for data. If a node has pending
data, the router issues a
TRANSMIT_DATA
command to the node and waits for it
to initiate the block transfer. During
the block transmission, the length of
the block is transmitted as the first
byte. This byte is loaded in a down
counter at the router and waits until a
complete block is received. Each
received byte is added and a 16-bit
checksum is generated at the router
end. The node similarly generates a
checksum and transmits the check-
sum bytes to the router.
The router compares the received
checksum with its own and validates
the block. When there’s a checksum
mismatch, the router may ask the
node to retransmit the block. Next,
the router analyzes the received pack-
et and determines its destination from
the packet header. After that, the
packet will be delivered to the corre-
sponding destination node when it is
ready to accept it. The router must
have a circular queue data structure
to hold packets pending for transmis-
sion to the network.
At the node end, a serial ISR han-
dles all of the communication with
the router in the background. The
serial interrupt must have the highest
RECEIVE_DATA, and REPORT_ERROR_STA-
TUS. Because there is room for up to
eight embedded commands, you can
add application-specific commands to
reduce the response time.
At each node, there are one input
and one output buffer for storing one
packet of incoming and outgoing net-
Listing 3—
This embedded command parsing code fragment is a part of the serial ISR at the node and initiates
a data transfer (if necessary) on request from the router. This code assumes
AChar
contains a char received
with TB8=1 (address byte).
switch ( (AChar & CMD_MASK) >> 5) {
case TRANSMIT_DATA:
TB8=0;
// clear TB8 bit for data
transmission
SendChrw(Node_Status);
// send status
SendPendingCmd();
//send pending command to
router
break;
case RECIEVE_DATA:
TB8=0;
SendChrw(Node_Status);
// send status
ReadRouteData(uIn.Buf);
// Read data from NET
SendChrw (ACK);
// Confirm data reception
checksum =0;
for (AChar =0; AChar < uIn.Buf[0]; AChar++)
checksum += uIn.Buf[AChar];
SendChrw((checksum & 0xff00) >> 8); //H checksum
SendChrw(checksum & 0xff);// checksum LOW
Packet_Recvd++;
break;
case REPORT_ERROR_STATUS:
TB8=0;
SendChrw(LastError);
// send status byte of node
LastError = NO_ERROR;
break;
case REPORT_STATUS:
TB8=0;
if (fIsOutPending) NODE_OUTBUF_FULL();
else NODE_OUTBUF_EMPTY();
if (fIsInPending) NODE_INBUF_FULL();
else NODE_INBUF_EMPTY();
SendChrw(Node_Status);
//send status byte of node
break;
}
Command
Description
Command data
Asserted by
Process set point
Sets the process temperature
16-bit temperature value
Central computer
Chiller inlet set point
Set point value of chiller inlet temperature
16-bit temperature value
Central computer
Chiller outlet set point
Set point value for chiller outlet temperature
16-bit temperature value
Central computer
Process status
Temperature status of chemical process
16-bit temperature value
Node one
Chiller status
Temperature and flow status of chiller
Three 16-bit values for inlet and outlet
Node two
temperature and flow rate
Flow interrupt alarm
Flow switch indicates low-flow condition
1-byte flow-switch number
Node three
Coolant temperature limit alarm
Coolant temperature exceeds the set limit
1-byte location and 1-byte
Node two
temperature value
Coolant temperature limit set point Coolant temperature limits set point
1-byte temperature value
Central computer
Table 1—
The command set for distributed control of a chemical plant is defined by a detailed description of the bytes.
20
Issue 133 August 2001
www.circuitcellar.com
CIRCUIT CELLAR
®
interrupt priority. The node will be
interrupted only by the address byte.
The serial ISR must find the received
address and compare it with its own
(pre-defined) address. If a match is
found, the serial ISR decodes the
embedded command and decides the
next action. The code uses a
switch()
statement as shown in Listing 3 to
take appropriate action.
After reception of a packet from the
router, the code sets the fIsInPending
flag to indicate pending data in its
input buffer. The node main program
calls the
NetDataProcesser() function
when the fIsInPending flag value is
set to one. This function has applica-
tion-specific code to process the net-
work data. Similarly, when the node
has to transmit a data packet to the
network, it loads the data in its out-
put buffer and sets the fIsOutPending
flag. This flag is reported to the router
by the
REORT_STATUS command. When
the router detects that the node out-
put buffer is full, it issues a
TRANS-
MIT_DATA command to the node.
REAL-WORLD EXAMPLE
In order to illustrate this protocol,
let’s consider an example of a distrib-
uted control system for a chemical
plant. The plant has a chemical
process whose temperature needs to
be precisely controlled using a PID
controller. The plant also has various
subsystems that need water cooling.
A small chiller plant about 100 m
away accomplishes the cooling.
The coolant flow and its tempera-
ture at the inlet and outlet of the
chiller plant need continuous moni-
toring and the temperature difference
must be maintained within 4°C. The
coolant temperature and flow all
along the plant subsystem also needs
to be monitored using about 20 RTD
and flow switches. Information about
the process temperature, coolant tem-
perature, and its flow must be dis-
played at a central computer in the
control room. It should be possible to
change the set point of the process
temperature and coolant flow rate
from the control room.
Because the plant is spread over a
wide area, the obvious choice for the
control system is distributed control.
One controller (node address 1) with a
PID control algorithm controls
process temperature and is conve-
niently located near the process. The
second controller (node address 2) is
located inside the chiller plant to
monitor the coolant flow and coolant
temperature. It also controls the
chiller for maintaining required tem-
perature difference between its inlet
and outlet. The third controller (node
address 3) simply monitors the
coolant temperature and all the flow
switches in the plant.
Each of these three controllers has
an RS-485 serial interface and is con-
nected to the router on a two-wire
serial network (see Figure 2). The
router has one additional RS-232 seri-
al interface for connecting to the cen-
tral computer. The router software
assigns a node address 100 to the cen-
tral computer so that all the data with
a destination address of 100 will flow
to the central computer.
The protocol requires a few com-
mands, as shown in the Table 1, to
provide set point data for the process
temperature and coolant flow rate.
The table also lists status commands
used by each node to report status of
process temperature, coolant flow
rate, and coolant temperature at the
chiller plant inlet and outlet. The
node 3 reports off-state of a flow
switch (to indicate the discontinuity
of required flow at a certain location)
or temperature at a location exceeding
a pre-defined upper limit. In this
application, no node is required to
communicate with each other and the
packet destination is always the cen-
tral computer (address 100).
The sample code is available on
Circuit Cellar
’s web site. For trans-
mitting the process temperature value
from node one, no command is
required from the central computer
but the node automatically requests
the data transfer to the router. At the
node end, the node keeps one copy of
the previous data and compares it to
the new data. The new data is trans-
mitted only if it is different from the
previous data. This is done to reduce
the overall network traffic. You may
write the front-end code at the central
computer using any language.
www.circuitcellar.com
Issue 133 August 2001
21
CIRCUIT CELLAR
®
The router adds two bytes (SOB1
and SOB2) as a start of block and two
bytes (EOB1 and EOB2) as end of
block for any data packet sent to the
central computer. This is done so that
at the central computer it’s easy to
identify the packet boundaries and
simplify their separation. The soft-
ware at the central computer should
test the integrity of the data packet
and discard invalid packets.
I assume that the maximum block
size does not exceed 256 bytes. This
requires one byte for storing the block
length. If a particular application
demands it, the length may occupy
two bytes so that one of the bytes can
transfer a block of 64 KB.
The router uses the packet header
for decoding the packet destination.
The central computer may use it to
determine the source of the packet.
The control system may have a few
commands common for all the nodes
(e.g.,
SELF_TEST). And, the routing pro-
tocol may reserve one node address
(e.g.,
TO_ALL_NODES) for sending com-
mon commands to every one of the
nodes simultaneously.
When a node receives such an
address, it should respond to the com-
mand in addition to its own address.
This saves a great deal of router time.
In addition, it is particularly impor-
tant when the number of nodes in the
network is high.
The central computer gets more
details about the type of information
it’s dealing with by looking at the
source address in the packet header.
The central computer may assign a
packet number to each packet trans-
mitted for debugging.
The idea here is that if the node
immediately sends an echo of each
packet it receives, the sender (in this
case, the central computer) knows
that the node has received the packet
correctly. If during transmission of
this command the node was busy,
which resulted in the time-out at the
router, the central computer wouldn’t
get the echo. The central computer
can wait for a predetermined time for
the echo and then safely assume that
the node did not receive the com-
mand. It may decide to retransmit
such lost packets.
Praveen P. Deshpande earned his
BSEE from Visvesvarayya Regional
College of Engineering (VREC),
Nagpur University, India. Presently,
he is a senior scientific officer in the
field of distributed data acquisition
and control. His interests include
real-time operating systems and dis-
tributed control. You may reach him
at ppd@cat.ernet.in.
SOFTWARE
The source code is available on
Circuit Cellar
REFERENCES
[1] Texas Instruments, “Interface
Circuits for TIA/EIA-485 (RS-
485)—Design Notes,” SLLA036,
November 1998.
[2] Intel Corp., MCS 51 Family
User’s Manual
, Intel Corp.,
Santa Clara, CA, February 1994.
SOURCES
80C320
Dallas Semiconductor, Inc.
(972) 371-4000
Fax: (972) 371-3715
www.dalsemi.com
MCS 51
Intel Corp.
(408) 765-8080
Fax: (408) 765-9904
www.intel.com
SN75176
Texas Instruments, Inc.
(800) 336-5236
www.ti.com
You can easily adapt the code I’ve
described here for your specific appli-
cation. Therefore, it’s easy to build
your own distributed control system
that’s highly configurable, flexible,
and more reliable.
I
22
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
ecently, I went
through my notes
from the quantum
mechanics course I took.
This was a subject that fascinated me,
especially the issues of interpretation.
I loved discussing it in Internet news
groups and read whatever books and
articles I came across. Bell’s Paradox,
the many worlds interpretation,
mathematical formalism...the inter-
esting topics go on and on.
One of the fascinating topics is the
picture of the hydrogen atom, in
which the electron inhabits a hazy
probability cloud around the nucleus.
I wanted another way to view it, so I
used the POV-Ray to render anima-
tion of the hydrogen atom (you can
view them at www.geocities.com/
juanfh/hydrogen.html).
After I was done with the raytrac-
ing, I was toying with a new idea:
What would it be like if I could actu-
ally touch these atoms? What if I
could take the atoms in my hands and
perform experiments with them?
Then, virtual reality came to mind.
I wanted to build my own virtual
reality peripherals for this project. For
my purposes, I wanted the glove and a
position tracker. I once read that such
trackers function by tracing position
by sensing alternating magnetic
fields. This technology originated in
the ’70s in aerial navigation research
and has been improving ever since.
Based on this idea, I began experi-
menting with magnetic field source
arrangements and sensors until I man-
aged to build my own simple tracker.
PRINCIPLES OF OPERATION
If the earth had three pairs of north
and south poles that turned on and off
sequentially, having a compass and
bothering to do triangulation would
allow you to find your way all over
the world. A 3-D position tracker
based on magnetic fields is based on a
similar principle. You can find the
position of a sensor relative to the
magnetic field sources using the
intensity of alternating magnetic
fields generated by coils activated
sequentially as a reference.
The alternating magnetic field gen-
erated by a coil excited by a sinu-
soidal wave has the form:
B(x, y, z, t) = B
0
(x, y, z)sin(2
π
ft)
[1]
Figure 1 shows the spatial field
amplitude B
0
(x, y, z)
for such a field.
When you are closer to the coil, the
amplitude of the field is stronger.
Likewise, when you go farther away,
the field drops. This field can be
sensed by a sensor coil.
To sense position, I wanted to rely
on the scalar amplitude of the mag-
netic field. Because of the vector
FEATURE
ARTICLE
Juan Herrera
Magnetic Position
Tracker
r
Juan takes us into the
realm of virtual reality
as he figures out a
way to hold atoms in
the palm of his hand.
By experimenting with
magnetic field source
arrangements and
sensors, he designed
a simple 3-D position
tracker. Check in with
Juan to get the rest of
the details.
Figure 1—
A planar section for the magnetic field
amplitude for a current-carrying wire shows the familiar
pattern formed by iron filings around a magnet. The full
3-D field is obtained by rotating the pattern around the
coil axis. The field of a square coil is similar to this.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
23
nature of the field, deter-
mining this involves sens-
ing three orthogonal com-
ponents of the field at a
point. So, three orthogonal
sensor coils are required.
You can’t reconstruct
position from the intensity
of a single magnetic field.
In general, the field magni-
tude is constant over cer-
tain surfaces in space, so
sampling a single magnetic
field can give position
within just one such sur-
face. The field of three
coils activated sequentially
can be sensed to remedy
this. The three surfaces
that the field intensities
define will intersect at a
single spatial point.
Fiddling around with the equations,
I figured out that the actual calcula-
tions to reconstruct position this way
can be complicated to carry out in
real time. The best way to adapt this
to real time would be to calculate a
partial table of position as given by
three magnetic field intensities. Then,
numeric interpolation can be applied
to cover all space. I discovered that
this technique gives satisfying results.
This article is a discussion of how
to detect 3-D position. Determining
orientation of the sensor is a separate
process accomplished with linear
algebra. Determining orientation
doesn’t depend solely on the intensity
of the magnetic field, but the infor-
mation of the individual components
of the vector field is required.
A GLANCE AT THE SYSTEM
The wood assembly of the tracker
system corresponds to a cube with six
coils, one in each face (see Photo 1).
These are the generators of the refer-
ence magnetic fields. The tracking is
performed in the space within the
cube. As noted, only three coils are
needed for tracking, but using six
yields the benefit that the three coils
whose field is sensed to be stronger
can be chosen as references, yielding
improved accuracy while keeping the
electronics simple. The magnetic field
sensor is shown in Photo 2.
In this article, I’ll go through the
steps I followed to build the tracking
hardware (see Figure 2). With this
hardware, position and orientation
determination can be accomplished in
conjunction with my C library (I’ll
come back to this library later). A
microcontroller is connected to the
serial port of the computer. It receives
sampling requests, activates the mag-
netic-field-generating coils in
sequence, and takes readings of the
sensor circuit through the microcon-
troller’s A/D converter. The software
will take care of making the neces-
sary operations to reconstruct posi-
tion and orientation of the sensor.
THE SENSOR
The sensor is simple in principle.
Each component of the magnetic field
is picked up by a separate coil, and a
capacitor yields tuning at a given fre-
quency. Three such orthogonal coils
make up the sensor. In the sensor
shown in Photo 2, the three coils are
assembled on the plastic ball of a roll-
on deodorant. Thirty turns of 40-
gauge enameled wire make each coil.
Machined pins are placed at the coil
terminals for connection to a cable
going to the main circuit board where
the signal is amplified. The machined
pins on this cable allow placing tun-
ing capacitors just above the coils. All
of this permits easy attachment of dif-
ferent sensors for testing purposes.
The design seems too
elaborate for this seem-
ingly simple purpose. I
actually assembled sim-
pler sensors in my earlier
experiments. The first
one was assembled on a
balsa wood construction
providing three orthogo-
nal axes on which I
wrapped the coils. But
when testing the sensor,
as I aligned one of the
coils with the magnetic
field vector, the other
two sensor readings
wouldn’t vanish. I didn’t
expect them to be exact-
ly zero because of the
distance offset between
the coils, but the read-
ings were still too sizable. I wondered,
what could be going on?
First, I thought that because the
wires going from the sensor to the
preamplifier were not running togeth-
er, they were effectively forming a
loop that picked up some of the mag-
netic field. I tried moving the tuning
capacitors just above the coils so that
any looping of the cables wouldn’t be
part of the tuned circuit. However,
there was no change. Then, I was
careful to have the cables run closely
together so that they wouldn’t span a
large area. No success either. A
spooky suspect, as spooky as my prob-
lem, was some mutual inductance
between the sensor coils.
With the source of the problems
still unidentified and without a solu-
tion at hand, I couldn’t be sloppy with
Photo 1—
This cube is about 30
″
long (which proved
to be the optimal size after a larger cube wouldn’t fit
through the workshop door!). The tracker will work with
a cube of any size if the circuit gain is properly adjust-
ed, as indicated in Figure 7.
AC/DC
Conversion
Field intensity data
Sensor
addressing
ADC
Signal
saturator
Comparison
Phase
information
I/O pin
Phase signal
conditioning
Oscillator
Output
MUX
Output
transistors
Output coil
addressing
Computer
Serial
Signal
reset
Microcontroller
Cube
Coil 1
Coil 2
Coil 3
Coil 4
Coil 5
Coil 6
Sensor
Amplification
MUX
Figure 2—
The tracker’s functions are responding to signals from a PC, activating the out-
put coils in sequence, addressing the sensors one by one, performing A/D conversion,
and relaying all the information back.
24
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
the sensor construction. So, I strove
to construct a sensor that would be as
ideal as possible. First, I tried assem-
bling the sensors in a Styrofoam ball,
which I assumed would do away with
the mutual inductance and also result
in zero offset distance between the
centers of the coils. I kept the tuning
capacitor right above the coil. I was
careful that the paths for the coils
were orthogonal, but I didn’t attempt
to make them thin.
A few of these sensors worked and
a few didn’t. What could be going on?
My new hypothesis was the sensors
were now coupling to each other
because of the capacitance at the
points where the coil wires cross each
other. Also, the differences in per-
formance among sensors built this
way could be caused by slight differ-
ences in resonance frequency, so the
coupling between sensors would be
more or less effective.
At this point, I tried a brute-force
approach, adding a circuit to sample
one sensor at a time while inhibiting
the rest of the sensors by short-cir-
cuiting them. This way, the sensors
were at least good for position track-
ing. I used this arrangement for a
while, but when I moved onto orien-
tation tracking, the sensor
performance wasn’t good
enough for the increased
accuracy required.
So, I had no other
recourse than further
improving the spherical
sensor. I used thin coils to
minimize capacitance and
make the sensor more
ideal. I used the ball from
a roll-on deodorant for the
support and painstakingly
carved thin paths for the
sensors with a knife. I
used a compass to mark
the orthogonal paths.
Finally, I placed tiny slips
of masking tape between
the coils at the points
where they met to reduce
the capacitance.
The coils I built this
way had an inductance of
~84 µH. With a 47-nF
capacitor, the sensor res-
onated at about 80 kHz. I verified the
resonance frequency for each coil by
putting each in an RCL network.
The component values in the cir-
cuit (more details to follow later on)
are suited for this sensor of 1
″
diame-
ter, 30 turns, and resonance frequency
set at about 80 kHz. The resonance
frequency of the three coils needn’t be
exactly matched; a provision for indi-
vidual calibration in the circuit board
will make up for this.
Depending on the way you build
the sensor coils, you may not get the
exact 80-kHz resonance frequency
with the 47-nF capacitor. Still, I think
the circuit described here will work
fine in the 60- to 90-kHz range.
One final note: In order to properly
detect the orientation of the magnetic
field, the direction the coils are
wound, the choice of axes, and the
way the sensors are connected to the
circuit must be consistent with the
right-hand rule of vector analysis.
However, it’s bothersome to keep
track of these conventions. I preferred
to build the sensor outright and used
a software tool to aid me in adjusting
the connections to the sensor to be
consistent (I’ll come back to this topic
later in the article).
Z
X
Y
Figure 3—
Each sensor coil is labeled with a color for identification with
a coordinate axis, defining an orientation with respect to the cube’s coor-
dinate axes in Figure 4. Also notice the machined pins on each sensor
coil’s terminals, which are convenient to attach to a cable such as the
one in Photo 2. This allows for easy experimentation with different oper-
ation frequencies by using capacitors of different values.
RGB
corner
To ground
To signal
CMY
corner
Z
X
Y
Figure 4—
The faces of the
cube are labeled with colors
for easy identification of the
connections to the circuit.
The opposing red-cyan,
green-magenta, and blue-
yellow coils go along the x-,
y-, and z-axes, respectively,
and their connections are
conveniently grouped in
opposing corners.
The red/black banner is a trademark of Texas Instruments. 43-4128
Break the 1-µA barrier and extend the life of your power-sensitive application. Texas Instruments
MCU to break the 1-µA barrier in standby mode. Its ultra-low power consumption and integrated
high-performance analog peripherals make the F413 ideal for cost-sensitive, battery-powered
measurement applications that require display capabilities such as utility metering, intelligent
sensing and portable measurement. On-chip emulation and in-system programmable ultra-low-
power Flash reduce development time. See for yourself how the MSP430F413 sets the benchmark
for low-power, high-performance mixed-signal microcontrollers. Order your development tool today.
MSP430F413: Industry’s first Flash MCU
to break the 1-µA barrier.
■ Ultra-low-power MCU integrates Flash
memory and LCD driver on one chip
■ Power consumption <1-µA standby
mode at 2.2 V (typ.) extends battery life
■ Integrated analog comparator ideal for
precise mixed-signal measurement
■ On-board SVS combats brownout
■ 16-bit RISC architecture enables
new applications at a fraction
of the code size
■ In-system programmable Flash
permits flexible code changes
and field upgrades
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
27
SENSOR CONSTRUCTION
In order to build a sensor that could
be easily attached and detached to
and from the assembly to be tracked, I
used machined pins for the coil termi-
nals. The coils consisted of 30 turns
of enameled AWG 40 wire. I soldered
the loose end of the enameled wire to
one of the machined pins. I counted
30 turns and soldered the loose end to
the other pin. Then, I put the pins
into two previously drilled holes on
the ball and glued the pins in place.
Before wrapping the other two coils,
I put a small piece of masking tape
above the four points where the first
coil would cross the others. The tiny
piece of tape reduces capacitance
between the coils. Next, I assembled
the green coil and placed the other
two pieces of tape where the paths
cross. The completed sensor should
look like Figure 3. To connect this
sensor to the circuit board, I built a
six-wire segment of ribbon cable with
machined pins as terminals. I
attached the cable to the sensor and
then placed the capacitors above it.
After building the sensor, each axis
was identified with a color—red,
green, or blue—corresponding to the
x-, y-, and z-axes. The sensor can be
conveniently placed in a handle.
MAGNETIC FIELD GENERATOR
I assembled the cube frame out of
balsa wood. The prolongation at the
edge of the cube allows easy wrapping
of the coils. When assembling your
cube, avoid using large metallic parts
because they will distort the magnetic
fields unpredictably.
After the assembly was finished, I
labeled the prolongations with colors
(see Figure 4). This allows for easy
identification of the coils and axes
and easy connection to the circuit.
Next, I wound coils on each side of
the cube using 16-gauge enameled
wire. Earlier design problems proved
that care must be taken so that the
coils don’t touch each other even
though they’re packed closely togeth-
er. This resulted in distortion of the
magnetic fields likely caused by
mutual inductance and/or capaci-
tance. I ran the coils through thin L-
shaped notches of about 0.25
″
depth
to provide the neces-
sary separation, tak-
ing care to carve
them just above the
meeting edges of
adjacent prolonga-
tions (see Figure 5).
A certain order is
necessary for wrap-
ping the coils. One
way to keep track of
this is to find the
corner of the cube
where the prolonga-
tions all are labeled
red, green, and blue.
Fix a loose end of
enameled wire to
the prolongation
labeled red and label
this loose end with a black tag. Then,
wind the coil counterclockwise. This
is important because otherwise sensor
orientation tracking won’t work (see
Figure 4).
After winding 10 turns, cut the
wire and label the loose end red.
Then, repeat this for the green and
blue coils, always labeling the first
loose end black and the second and
third ends green and blue. Remember
that all of these loose ends should be
in the RGB corner.
After you complete this task, repeat
the process with the CMY corner.
When all of the coils are ready, use a
few segments of masking tape to hold
the wires of each single coil closely
together. Do not join adjacent coils.
The coils will be connected to a cir-
cuit board by two cables, one coming
from the RGB corner and the other
from the CMY corner. The ends
tagged black go to ground and the oth-
ers go to the corresponding signal in
the circuit board. The wires going to a
same corner should go in a single
envelope. This is necessary because
signals not running close to the
ground return path will in fact con-
tribute a magnetic field, just as if they
constituted another coil segment.
0.25"
Figure 5—
It’s important that adjacent coils don’t touch each other, so that the
magnetic fields won’t be distorted because of mostly inductive coupling between
the coils. To achieve this, I ran the coils through L-shaped notches about 0.25
″
deep in the prolongations at the corners so that the coils stay separated.
θ
V
θ
V
N
B
N
Oscillator
Sensor
B
Figure 6—
In both of
these situations, the
ADC will record the
same magnitude for
the normal component
of the magnetic field.
But in the second
drawing, the sensor
orientation (given by
the normal vector
established by the coil
wrapping sense) with
respect to the magnet-
ic field is inverted, and
the component must
be taken to have a
sign opposite to the
first drawing.
Comparing the phases
allows you to distin-
guish these situations.
28
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
the magnetic field, its phase will
appear to be shifted ±90° with respect
to it according to the sign of cos(
θ
).
Therefore, a part of the circuit must
be capable of comparing this phase.
With these considerations in mind,
I designed my tracking system around
the diagram shown in Figure 2. Its
purpose is to generate magnetic fields
in sequence and amplify the sensor
signal containing the information of
the three vector components of the
fields. An oscillator generates a wave
that is fed into one of the output
coils, as addressed by a multiplexer.
The signal from the sensors is ampli-
fied and fed into a multiplexer, which
passes the selected sensor signal to an
AC/DC converter. The output of the
THE CIRCUIT
The hardware part of the position
tracker requires only a circuit that
will excite the generator coils in
sequence, sense the magnetic field
components for each generator coil,
and relay this data to a computer. An
important clarification to keep in
mind is that, as discussed earlier,
position tracking relies on sampling
the intensity of the alternating mag-
netic field, determined as:
[2]
For this purpose, amplifying the sig-
nal of each sensor and converting it
from AC to DC prior to A/D conver-
sion suffices. Note that this doesn’t
allow you to determine whether the
component of the vector field ampli-
tude along the coil is positive or nega-
tive, but this information isn’t neces-
sary to get the amplitude.
However, the method for determin-
ing orientation does require that you
know the signs of the components of
the vector field amplitude. You can
discern this by comparison of the
phases of the local oscillator and the
sensed field (see Figure 6). The field
generated by the coils is proportional
to the current passing through them,
which is proportional to the oscillator
signal. Because the signal in the sen-
sor coils responds to the derivative of
Figure 7—
Together with the tracker C library, this circuit will work with a cube of any size, provided that you set the combined gain of IC1–IC3 and IC5 so that when any sen-
sor is placed in parallel at the center of any generator coil, an intensity around 1.8 V results. You should find the optimal settings for your sensor construction, cube size, and
operating frequency with an oscilloscope.
a)
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
29
AC/DC converter yields the field
magnitude data, which is read by the
microcontroller’s AC/DC converter.
Another stage of the circuit com-
pares the phase of the oscillator and
currently addressed sensor, translating
this into a 1/0 level. Finally, there’s
an additional signal from the con-
troller, which is used to reset some of
the sampling circuitry.
Figure 7 illustrates a detailed
schematic of my circuit. The circuit
is powered by a dual ±10-V source.
Note that there is an independent
amplifier for each sensor, each with a
trimmer for individual calibra-
tion to compensate for slight
differences in the resonant fre-
quency of the sensors. The
outputs of the amplifiers are
routed through a multiplexer.
There is a decoupling capacitor
at the multiplexer output to
eliminate any DC offsets from
the preamplifiers.
An AC/DC conversion cir-
cuit follows. This circuit also
provides some gain, which is
useful for calibration of the
tracker. Note that a transistor
discharges the capacitor as the
multiplexer switches to the
next sensor, improving the
response time of the circuit.
This also inhibits transient
peaks while switching coils.
The waveform that excites
the field generator coils is
obtained by filtering a square
wave through an RC network.
R23 tunes the oscillator to a
frequency that is the average of
the sensors’ resonant frequency. R27
sets the gain of the oscillator amplifi-
er so that the waveform spans ~9 V
and its lower part is above 0.6 V, so
that the transistors are properly excit-
ed through the output of a multiplex-
er addressed by the controller.
Finally, there’s the phase discrimi-
nation circuitry, which is used by the
part of the software that determines
orientation. It tells whether the phase
of the sensed signal differs 90° for-
ward or backward with respect to the
oscillator. To make this easier to
detect, an RC network shifts the
waveform 90° with respect to the
oscillator. Thus, the overall phase dif-
ference becomes 0/180°. This phase-
shifted waveform is compared to the
sensor input and conditioned to a
logic 1/0 level.
The whole circuit is interfaced to a
computer through a microcontroller.
After TTL-to-CMOS level conversion,
the circuit addresses the sensors
through the networks labeled PA0 to
PA1 and the output coils through PB0
to PB2. The circuit then performs an
A/D conversion on the INTENSITY
signal, reads the logical level of the
PHASE, and discharges the capacitors
in the AC/DC converter and the
phase discrimination stage through
the DISCHG signal.
When assembling, optimizing, and
troubleshooting, it’s convenient to
control the circuit’s functions manu-
ally. The usual verification procedure
(with the microcontroller disconnect-
ed) would be to power up the circuit
and place jumpers JP1 and JP2 in
place, thus enabling the DIP switches.
Set switch one (corresponding to the
net DISCH_SIGNAL) off. Set the
OUT_MUX switches to 001 so that
the red output coil is powered. Verify
Figure 7b
Figures 7c and d
c)
d)
30
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
that the red, green, and blue sensors
properly detect the magnetic field by
probing the outputs of IC1, IC2, and
IC3. Now, set the SENSE_MUX DIP
switches to 00 and probe the voltage
level at the INTENSITY output.
Repeat the same process for the
green and blue sensors, setting
SENSE_MUX to 01 and 10. You may
repeat the test addressing the rest of
the output coils and setting the
OUT_MUX swiches from 010 to 111.
FITTING EVERYTHING IN PLACE
I wrote a number of programs
(SENSE1, SENSE2, SENSE3, and
3DTEST) to aid in verifying the cir-
cuit operation and calibration. These
programs are available on my web site
(all programs you use should be called
PROGRAM_NAME n, where n is the
COM port number the tracker is con-
nected to). There’s also a data file
called
INVPOINT.DAT, which must be in
the same directory as these programs.
This data file contains a partial field
position translation table. All the
painful number crunching is already
calculated in this data file; all that is
left to do is interpolation of this table
and some linear algebra.
SENSE1 plots red, green, and blue
lines depicting the response of the
three sensors to the red output coil
and a reading showing the sensed field
intensity as:
[3]
As you move the sensor around the
output red coil, the lines will wiggle.
SENSE1 is especially useful to cali-
brate each of the sensor coils. Because
of small differences in construction
and resonant frequency, the response
of the sensor coils won’t be identical.
To compensate for the response differ-
ence, you should adjust trimmers R7,
R8, and R9. I accomplish this by mov-
ing the sensor to the center of the red
output coil and aligning the plane of
the red sensor with the red output
coil. The goal is a high reading for the
red sensor and low readings for the
green and blue sensors.
I write down the red sensor’s read-
out and repeat this procedure for the
green and blue sensors with the red
output coil. Of the three values
obtained, I take the largest and cali-
brate the other two sensors so that
their readings reach that value, adjust-
ing R7, R8, and R9 as necessary.
SENSE2 shows the sensed field
intensity of each of the output coils
rather than the individual sensor read-
ings (like in Equation 3). Moving the
sensor around, I can verify that all six
generator coils are active.
I further calibrate the circuit by
placing the sensor in the center of the
plane of any coil and set R13 so that
the reading is about 90. I also verify
that rotations don’t alter the readout.
If an alteration is observed, I run
SENSE1 again and refine individual
sensor calibration for the sensors.
After all of this is taken care of,
everything’s ready for position track-
ing. Running 3DTEST shows a three-
dimensional cube that moves around
the screen as a sensor is moved. At
this point, you may see a sudden
jump in position as the sensor is
Figure 7e
32
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
moved past the midplanes of
the cube. This is corrected
by adjusting R13 until the
motion is satisfactory. After
this calibration, you may
still find that a slight mis-
calculation is present
between runs when moving
the sensor through the mid-
planes of the cube. This can
be adjusted automatically by
utility programs. To do this
software calibration with
3DTEST, simply press the
plus and minus keys.
After getting position tracking to
work correctly, it’s time to calibrate
orientation tracking with SENSE3.
This program is similar to SENSE1 in
that it shows the sensor readings for
the red generator coil. However, it
also shows the sign of each compo-
nent of the magnetic field. Run
SENSE3 and place the red sensor in
front of the red coil with the plane of
the sensor perpendicular to the plane
of the coil. As you rotate the sensor
around this position in both direc-
tions the sensor reading varies
between negative and positive
smoothly. If the phase detection isn’t
calibrated, there will be no transition
between negative and positive close
to zero, and it will likely appear else-
where as a sudden jump. Adjust R18
until you obtain proper operation.
Now that phase discrimination is
working, all that remains is to run
3DTEST again. Pressing the letter “r”
will then enable rotations. If you’re
lucky, at this point the tracker is
already fully functional and
the cursor will rotate according
to the motion of the sensor.
Otherwise, the orientation of
the sensor coils must be cor-
rected. As I previously
explained, instead of bothering
to follow the connections of
the sensor, 3DTEST allows an
easy way to get this correct.
While running 3DTEST, press
zero successively until you get
the right rotation of the axes.
3DTEST will then tell you that
some of the connections to the
sensor coils must be twisted.
PROGRAMMING
After I finished the tracker, I spent
my time writing VR programs for my
virtual quantum mechanics applica-
tions. My interface to the tracker’s
functionality is a C library (libtrack.a)
for use with the DJGPP C compiler.
This library provides functions that
control the tracker and calculate posi-
tion and orientation from the magnet-
ic field intensity values. The library’s
Photo 2—
The plastic base and the black Velcro strip allow attaching the mag-
netic field sensor to an object to be tracked, such as a virtual reality glove.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
33
associated header file is
tracker.h. Let
me give you an overview of the
library functions.
You should invoke the
void track-
er_init(char *datafile_path,int
comport_number) function first. This
initializes the tracker function, load-
ing the
INVPOINT.DAT data file. Its
argument is the data file path (set this
to null if the data file is in the current
path), and comport_number is the
number of the serial port to be used
by the tracker (one to four).
The
void get_cube_field() func-
tion makes the microcontroller sam-
ple the magnetic fields.
After calling
get_cube_field(), use
interpolate_tracker_position() to
calculate the x, y, z position of the
tracker. These coordinates are stored
in the
float tracker_pos[3] array and
range from –1 to 1.
Call
get_tracker_orientation after
interpolate_tracker_position() to
calculate the sensor orientation. The
results are stored in the matrix
float
orientation_matrix[3][3] and in the
float vectors
x_orientation[3], y_
orientation[3], and z_orientation[3].
The x, y, and z orientation vectors
store the components of the x, y, z
sensor axes as seen in the tracker ref-
erence frame. When the matrix is
applied to a vector it rotates according
to sensor rotation.
The
void apply_smatrix(float
M[][3],float a[],float b[]) function
applies the matrix M to the vector a,
storing the result in b. This isn’t real-
ly a tracker-specialized function, but I
included it for completeness.
The library doesn’t furnish any spe-
cialized 3-D drawing routines. It’s
intended to be used with a suitable
3-D library. I’ve used my tracker
library together with the DJGPP ver-
sion of the Allegro game program-
ming library by Shawn Hergreaves. It
shouldn’t be difficult to make this
library work along any other libraries
and architectures after some porting.
On my web site (www.geocities.
com/juahfh/tracker_cellar/), you’ll
find this library, the inverse point
data file, and the source code for the
programs. In addition, the microcon-
troller program to interface with the
C tracker library is available on
Circuit Cellar
’s web site.
I
SOURCES
Allegro game programming library
www.talula.demon.co.uk/allegro/in
dex.html
DJGPP C/C++ development system
www.delorie.com/djgpp/
POV-Ray
Persistence of Vision Development
Team
www.povray.org
SOFTWARE
The code for the microcontroller
program and library are available on
Circuit Cellar
Juan Herrera recently graduated from
college and is a physicist. After a
short stint in particle physics, he’s
found his calling in experimentation.
You may reach him at jherrera@
naima.udea.edu.co.
success of embedded
designs—and configurability
is key to the right BIOS.
detailed information and a
free sample BIOS binary for
your standard
reference
design.
What do the leading silicon
vendors know about BIOS
© 2000 General Software, Inc. All rights reserved.
Full source code automatically
configured with over 400 para-
meters using BIOStart
Windows 95/98/CE/NT
Embedded, Linux, DOS, and all
x86-based operating systems
www.gensw.com •sales@gensw.com • 800-850-5755 • 425-454-5755
34
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
s I was mulling
over how to intro-
duce this article, it
occurred to me to check
out my shop drawers, both at home
and work, where I squirrel away my
old microcontroller development
boards and programmers. Would you
believe there were a dozen? Granted,
I’ve been working with microcon-
trollers for about 20 years, but for the
majority of those years I was a faith-
ful Motorola fan. In any case, I was
never one to jump on every new chip
that came along.
Most of those dusty development
boards had earned their keep for a
while. The 68HC705C8 board, which
I designed and published an article
about four years ago, brought back
good memories (Circuit Cellar 85).
Some of the rather expensive com-
mercial development boards were not
so fondly remembered.
My point is that it would be great if
I could use up-and-coming microcon-
troller families without the bother
and expense of a development board
and programmer. The inclusion of
flash program memory on many new
micros as well as in-circuit serial pro-
gramming (ISP) capability have cer-
tainly helped in this respect.
However, many of these devices are
still programmed easily using only a
development board.
With a DB25 plug and a few feet of
5-conductor ribbon cable, you have all
you need to program Atmel’s AVR
family of micros, apart from a PC and
some free software. This article is tar-
geted for students and hobbyists or
people who use microcontrollers in
small work environments where
money and resources are tight. Along
with highlighting some of the useful
features of this microcontroller fami-
ly, I’ll be describing a simple but
smart peripheral device that I’ve
designed using AVR devices.
GETTING STARTED
Before I become enamored by the
product brochures of new micros, I’ll
discuss a few basic features, apart
from the programming concerns.
Can I solder this device to a PCB, or
better yet to a 0.1
″
hole pattern proto-
type board? Even if an evaluation
board for the device exists, it is often
hard to integrate that into a design,
even if the cost is not taken into
account. In the case of the AVR fami-
ly, along with the usual PLCC and
SOIC packages, there are 8-, 20-, 28-,
and 40-pin DIP packages available.
I’m not keen on buying an expen-
sive software suite for a chip I’m not
sure I’m going to be comfortable with.
Atmel provides free Windows-based
assembler and simulator packages,
and later I’ll describe a third-party
Basic compiler and device program-
mer that you can download for free.
At this point, I needed to ask
myself if I was comfortable with the
instruction set and whether or not it
is consistent throughout the family.
Although Atmel labels the AVR as a
RISC processor, it has 90–125 instruc-
tions. I’ve found that the instructions
work consistently from the smaller
chips on upward, and the memory
architecture is also similar as you
climb your way up the family tree.
There’s also a nice touch in the fact
that if an AVR peripheral is present
on one of the lower pin count mem-
bers of the family, generally it will
work exactly like its counterpart on
the larger chips.
FEATURE
ARTICLE
Brian Millier
My fAVRorite Family of
Micros
a
This month, Brian
shows us that Atmel’s
AVR family is just the
ticket to complement
his old boards. If
you’re someone who
uses microcontrollers
in a small work envi-
ronment, this should
lend some insight for
designing a simple
but intelligent periph-
eral device.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
35
Speed is relative, of course, and I’m
not talking about DSP applications.
Many members of the AVR family
run at about 8 MIPS using an 8-MHz
crystal, which is pretty fast in my
book. Given this impressive speed,
the possibility of using a compiled
high-level language like C or Basic
becomes feasible.
Among the many AVR family mem-
bers, I’ve chosen four different devices
to use, depending on the demands of
the particular project. They are nei-
ther the simplest nor the most com-
plex. Table 1 shows the features of
my chosen devices.
PROGRAMMING AVR DEVICES
With a few exceptions, almost all of
the AVR family members can be pro-
grammed serially. I have ignored
those that can’t, as they offer no fea-
tures that are not available on the
other family members that do offer
this ISP capability.
Atmel provides programming soft-
ware with its STK200 development
boards. Because the theme of this arti-
cle is to avoid development boards, I
had to look elsewhere.
MCS Electronics sells a Basic com-
piler for the AVR family, which
includes the sample electronics AVR
programmer, a built-in device pro-
grammer. This programmer programs
AVR devices through a simple five-
wire interface using a PC parallel
port. A free demo version is available
on the company web site. The demo
is fully functional apart from a pro-
gram size limitation in the compiler,
and the built-in device programmer
works without limitation. The
Windows-based device programmer is
fairly user-friendly.
Table 2 shows the connections
needed between the PC parallel port
and various AVR devices when using
the sample electronics programmer.
Generally, you mount a small header
connector on the actual AVR board
you’re building and wire up your
cable to match that. A five-position
header is needed, but you might want
to use the 10-pin STK200/Kanda
header scheme (see Table 2) for com-
patibility with some commercial AVR
prototype boards.
It is possible to steal enough power
from the parallel port of the PC to
program AVR chips if the AVR device
is the only thing connected to the
printer port (i.e., getting its power
from it). However, if you are planning
to program an AVR in-circuit on a
board of your own design, chances are
its current draw will greatly exceed
the small amount of current available
to be stolen from the printer port.
Table 2, therefore, does not include
power connections and assumes that
the proper V
CC
is applied to the AVR
device from an external power supply.
In addition to this wiring and the pro-
vision of power, for the programmer
to function, a suitable crystal (with
caps) or ceramic resonator must be
connected to the AVR device.
To use the sample electronics pro-
grammer, you must install the BAS-
COM-AVR compiler. Note that you
can install either the demo version or
the commercial package. Both ver-
sions come as two zip files, each of
which fits on a single 3.5
″
floppy.
Given that most new programs are
bloated, it’s refreshing to see a full-
featured compiler, with a built-in pro-
grammer, terminal emulator, and sim-
ulator all on two floppies!
I’m sure you’ll want to explore the
many features of the compiler for
yourself, but for now let’s just see
how it can be used to program an
AVR device. I assume that you
already have an object code file that
you want to program into an AVR
device; it could be from the Atmel
assembler, BASCOM-AVR compiler,
or object code you have obtained from
a different source.
The sample electronics programmer
is started by running the BASCOM-
AVR compiler, selecting the Program
menu, and choosing Send to Chip.
Assuming that an AVR device is con-
nected via the cable, a window like
the one shown in Photo 1 will appear.
All AVR devices have a signature pat-
tern built-in, which the programming
software reads. If no AVR device is
connected or if it is not wired up or
working properly, an error message
will appear indicating that the chip
cannot be identified. Although the
programmer software will still load, it
won’t work properly until this prob-
lem is corrected.
Referring again to Photo 1, you can
see that I had an Atmel 90S8515
device connected when I ran the pro-
grammer in this example. If you are
using the programmer in conjunction
with the BASCOM-AVR compiler,
programming is simply a matter of
clicking on the green rectangular icon
near the right-hand side of the tool-
bar. A chip erase is performed, the
chip is then programmed, and a verifi-
cation cycle is done, all automatical-
ly. However, if you are programming
by using an object file from another
source, you must first click the File
folder icon and then choose the appro-
Device
Package
I/O
Flash
EEPROM
RAM
UART
SPI
ADC
ATTiny12
DIP8
6
1 KB
64-byte
None
No
No
No
AT90S2313
DIP20
15
2 KB
128-byte
128-byte
Yes
No
No
AT90S8515
DIP40
32
8 KB
512-byte
512-byte
Yes
Yes
No
AT90S8535
DIP40
32
8 KB
512-byte
512-byte
Yes
Yes
8
Parallel port pin
AVR Signal
ATTiny12
’2313
’8515
’8535
Kanda PIN
2
MOSI
5
17
6
6
1
4
*RESET
1
1
9
9
5
5
SCK
7
19
8
8
7
11
MISO
6
18
7
7
9
18–25
GND
4
10
20
11
4, 6, 8, 10
Table 1—
These four AVR devices cover the needs of a wide variety of projects. Although not shown in the table,
all devices have from one to three timer/counter modules. I personally use DIP packages, but other packaging for-
mats are available for all of the devices listed.
Table 2—
This is the ISP cable wiring for the sample electronics parallel port programmer for various AVR devices.
Because some commercial AVR prototype boards contain a Kanda/STK200 ISP connector, the last column shows
the wiring needed for this.
36
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
priate file. Note that there is a dialog
box to select whether you are loading
a binary file, Intel hex file, or EEP-
ROM memory image file.
When the file is loaded, select
Erase, Write Buffer into Chip, and
then Chip-Verify from the Chip
menu. After you get used to the pro-
gram, you’ll likely switch to using the
icons in the toolbar for accessing
these functions.
A large portion of the programmer
window is used up with the hex
memory display. You can use this to
make minor patches to the object
code by clicking on a cell and chang-
ing it. This window is formatted to
show op-codes as they will appear in a
listing file, but one side effect to this
is that text string constants embedded
in the program code will be jumbled
in their display.
As well as programming AVR chips,
this programmer allows you to read in
the code from a pre-programmed AVR
device if you wish to duplicate the
code. AVR devices have lock bits that
can be set to prevent unauthorized
viewing of the firmware, and the
Sample Electronics AVR programmer
also can set them.
It should be noted that the program-
mer erases the EEPROM in the device
at the same time that it erases the
program flash memory. If you are
storing configuration-type informa-
tion in the EEPROM, you’ll have to
reinstate this if you make any
changes to the program code.
Now that you see how simple it is
to program these devices, let’s take a
look at a simple, yet intelligent
peripheral device I’ve designed using
AVR devices.
SMART CONTROLLER
I recently had to design an elapsed-
time display for an exhibit at a sci-
ence center. It had to be readable from
a distance of 75
′
, which called for
large, bright LED displays. I must
admit I haven’t used LED displays for
quite some time now, preferring the
popularity of LCD alphanumeric dis-
plays. I remember graduating from
“Nixie” tube digital displays to LED
displays several years ago. Lest read-
ers get the impression that I’m over
Listing 1—
The firmware for the jumbo LED controller is written in BASCOM-AVR. The code for the ASCII
string version of the firmware is shown here.
‘ AVR Big LED display driver – ASCII string input version
Dim Dig1 As Byte
Dim Digit As Integer
Dim I As Integer
Dim J As Integer
Dim Temp As Integer
Dim Fstring As String * 9
Dim T As String * 1
Dim Dipsw As Byte
$baud = 9600
$crystal = 4000000
Portd = 255
'enable weak pull-ups on port D
Config Portd = &B00000010
'make port D bits 2,3,4,5 inputs
Config Portb = Output
'Get DIGIT to display from the
'DIPSWITCH setting
Dipsw = Pind
Shift Dipsw , Right , 2
Dipsw = Dipsw And 7
Incr Dipsw
'digit selector now in range 1 to 8
Portb = 0
'TEST-turn all segments on
Wait 2
'leave all segments on for 2 secs
Portb = 255
'all segments off
Do
Input Fstring
J = Len(fstring)
Temp = Instr(fstring , ".")
If Temp = 0 Then
'no decimal point
If J < Dipsw Then
T = Chr(58)
'this will blank LED, when run thru
'lookup table
Else
I = J - Dipsw
Incr I
T = Mid(fstring , I , 1)
End If
Else' decimal point present
I = Dipsw + 1
If J < I Then 'string is shorter than digit to display
T = Chr(58) 'this will blank LED, when run thru lookup
'table
Else
'derive position of digit to display
I = J - Dipsw
If I > Temp Then
Incr I
T = Mid(fstring , I , 1)
Else
T = Mid(fstring , I , 1)
End If
End If
End If
Digit = Asc(t) - 48
'subtract ASCII bias
Dig1 = Lookup(digit , Dta) 'convert digit into 7 segment driver
'value
Incr I
If I = Temp Then
Dig1 = Dig1 And 127
'turn on RH decimal point for this
LED
End If
Portb = Dig1
(continued)
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
37
the hill, I was about 13 years old
when I built my first (and last) Nixie
tube project, a digital voltmeter.
For this application, I decided to use
Lumex’s LDS-AD16RI LED display,
which has 2.25
″
-high digits and an
extremely bright red color (three
times brighter than your average
LED). Much less expensive displays
are available if you can settle for less
brightness. The model I used is a
common anode model, but common
cathode models are also available.
The complication of using these
large displays is that they need about
6.8 V per segment to operate com-
pared to the 1.7 V needed by smaller
displays, because they use four LEDs
in series internally. I considered using
Maxim’s slick MAX7912CNG, which
is an eight-digit LED driver. However,
it is designed to drive LEDs that
require 3 V or less and needs a
lot of glue chips and an addi-
tional –5-V supply to operate
the Lumex LED I chose.
I decided to design a “smart”
controller for these LED dis-
plays using the AT90S2313
from Atmel. The ports on this
device can sink 20 mA per pin,
which is sufficient to drive the
LDS-AD16RI LED display to
full brightness. I used a non-
multiplexed design to maxi-
mize brightness, which was
critical for this application.
This decision requires one
Atmel AT90S2313 device per
digit, but the cost is less than
$3 each. The design lends itself
to a simple single-sided PC board lay-
out that mounts directly onto the
back of the display.
WHAT’S THIS ABOUT “SMART?”
Driving a multi-digit LED display is
not rocket science. However, if you’re
using a small microcontroller for your
project, there are a few resources that
are always in short supply. First of all,
you usually don’t have a lot of I/O
pins available. A non-multiplexed,
four-digit display requires 28 I/O
lines, and 11 lines are needed if a
multiplexed scheme is used.
Assuming that the numbers you’re
dealing with in your application pro-
gram are represented as binary num-
bers (a fair assumption), displaying
them on a multi-digit LED display
requires some mathematical routines
to break down the number into deci-
mal digits and then convert these dig-
its into the proper seven-segment
drive values. Sometimes there isn’t
enough program memory space in
small micros to handle these routines
along with everything else.
To solve both of these problems,
my controller design interfaces the
host micro to a controller/LED dis-
play (up to eight digits) using a two-
wire serial port. The numeric data to
be displayed can be sent in either of
the following two formats.
Any integer or floating-point num-
ber (up to eight digits plus decimal
point) can be sent to the LED con-
troller in ASCII string format.
Alternately, any number (up to
eight digits long) can be sent to the
controller as a long integer. In this
case, a fixed decimal place can option-
ally be displayed by setting a DIP
switch on the appropriate controller.
The first option works best if your
host program is written in a high-
level language such as the BASCOM-
AVR compiler. In this case, you mere-
ly use the
print statement to display
the value of a variable to the LED dis-
play. The second option works best if
you’re using assembly language and
storing variables as integers. Although
the LED controller expects a long
integer, if your display has five or less
digits you can just send zeroes for the
two most significant bytes.
I decided to use the asynchronous
serial protocol for the data transfer
because the entire AVR family (apart
Listing 1—
Continued.
Loop
End
'LOOK-UP table to convert a binary number (0-10) into the proper
'number to drive a 7 segment display. The value of 10 blanks the
'display. The table is set up to handle active low drive of the
'Cathodes of a Common Anode LED display. Segment A is bit 0,
'segment G is bit 6. Dec. Point is Bit 7
'Lookup table data must be placed AFTER the END statement.
Data:
Data 192, 249, 164, 176, 153, 146, 130, 248, 128, 152, 255
Figure 1—
Although each controller drives only one jumbo LED, the cost of the controller components is inexpensive.
38
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
was not critical here and there were
many functions in BASCOM-AVR
that proved useful. The program uses
less than 800 of the 2 KB of flash
memory present in the ’2313 micro.
Listing 1 shows the firmware for
the ASCII string version. Setting the
data rate of the ’2313 is accomplished
in BASCOM-AVR by using the
$CRYS-
TAL directive to inform the compiler
of what clock speed you are using and
then issuing the
$BAUD directive to set
the data rate. As a substitute, you can
use the BASCOM-AVR option compil-
er communication menu to select
these values. Although the AVR fami-
ly contains a versatile data rate gener-
ator, not all possible data rates can be
generated for all crystal choices, and
this menu will warn you if your
choice is not possible.
The port configuration is performed
first and then the DIP switches are
read to determine the digit position.
Unlike most microcontrollers, the
AVR family contains two separate
data registers for each I/O port.
Writing to the PORTD register, for
example, will send that value out to
port D (assuming it is configured as
an output port). This procedure is nor-
mal. However, in order to read the
state of the port D pins (assuming it
is defined as an input port), you must
read the PIND register.
I spent at least an hour staring at
assembly language code the first time
I tried, unsuccessfully, to read a port
on an AVR chip. Several months later
I repeated the same mistake trying to
do the same thing using BASCOM-
from the eight-pin ATTiny) supports
this with a hardware UART function.
The SPI and I
2
C protocols can be
implemented in software, but the
code for this uses up your precious
flash memory space, which may be in
short supply. Using software SPI or
I
2
C routines also may affect the capac-
ity of the host micro to handle other
real-time tasks.
THE HARDWARE
Figure 1 is a diagram of the LED
controller. Atmel’s AT90S2313-4PC is
packaged in a 20-pin DIP and can run
at up to 4 MHz. Because there are no
critical timing considerations, I used a
4-MHz ceramic resonator because it is
less expensive than a crystal.
All eight lines of port B are used to
drive the LED display, seven for the
numeric segments and one for the
decimal place. Driving the large LED
display directly from the port of a
microcontroller requires some expla-
nation. As I mentioned earlier, each
display segment consists of four LEDs
in series, for a total segment voltage
requirement of 6.8 V. I’m feeding the
common anode with a regulated 11-V
power supply and using 220-
Ω
resis-
tors in series with each segment.
These resistors act to limit current
and also tend to equalize the bright-
ness among the individual displays.
Note that after passing through an
LED segment and the current limit
resistor, the 11-V regulated LED sup-
ply is reduced to 5 V, which is within
the V
HI
rating on the AT90S2313.
When a port B line goes low, it will
allow an LED current of approximate-
ly 15 mA to flow. This is the opti-
mum drive current for the display. In
addition, the maximum current avail-
able from the port B lines when all
eight of them are active at one time is
approximately 15 mA.
The decimal point is an
exception because it con-
tains only two series-con-
nected LEDs. So, another
5-V zener diode is placed in
series with the decimal
point to make it work like
the other segments.
Most 12-V regulated sup-
plies can be trimmed down
to 11 V. Alternately, a couple of com-
mon 1N4004 diodes can be connected
in series with a 12-V supply to drop
the voltage to 11 V.
Port lines D2 through D5 are con-
nected to either a four-pole DIP
switch or four jumpers that are used
to set the configuration. They are read
at startup and define which specific
digit of the entire number this partic-
ular LED will display. No pull-up
resistors are used because internal
pull-ups within the ’2313 are enabled
by program code. See Tables 3 and 4
for definitions of the switch settings.
The ’2313 contains an internal
hardware UART. It is as versatile as
those found in other microcontrollers,
however it also contains a versatile
data rate generator that can generate
virtually all of the common data rates
with the most commonly available
crystals. I chose to use 9600 bps, but
you can choose whatever you wish.
This is defined in the program and
will be described later.
It is assumed that the serial data
input to this controller will come
directly from another microcontroller,
at TTL levels and without the data
inversion that occurs when RS-232
protocol is used. Because each con-
troller handles a single LED digit and
the controller firmware can handle up
to an eight-digit number, up to eight
individual controllers may be
required. In any case, the serial data
input lines to all LED controllers are
connected together and driven by the
host’s UART output. The TTL fan-out
capability of a microcontroller’s
UART output is sufficient to drive at
least eight ’2313 input pin loads.
THE FIRMWARE
As I mentioned, for this project’s
firmware I decided to use the BAS-
COM-AVR compiler. Execution speed
DIP1
DIP2
DIP3
DIP4
Digit displayed
Closed Closed
Closed
Don’t care Digit 1 (right-hand)
Open
Closed
Closed
Don’t care Digit 2
…
…
…
…
…
Open
Open
Open
Don’t care Digit 8 (left-hand)
Table 3—
In the ASCII version of the firmware, DIP switches 1–3
define which digit will be displayed by this controller/LED. If the ASCII
string contains a decimal point, the controller will display the digit.
DIP1
DIP2
DIP3
Digit displayed
Closed
Closed
Closed
Digit 1 (units)
Open
Closed
Closed
Digit 2
…….
…….
…….
…….
Open
Open
Open
Digit 8 (10 million)
DIP4
R.H. Decimal point displayed
Closed
No
Open
Yes
Table 4—
In the binary version of the firmware, DIP
switches 1–3 define which digit will be displayed by
this controller/LED display. Although data is sent to the
controller as a long integer, provision is made to dis-
play a decimal point using DIP4. By scaling integers
and using an artificial decimal place, you can often
avoid the need for floating point math routines.
40
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
proceeded by a 55-hex byte for syn-
chronization purposes.
Along with the normal complement
of BASIC commands, this compiler
has several routines built into its
library to allow you to connect associ-
ated peripherals, such as I
2
C, SPI, and
one-wire devices. It also contains bit-
shifting and manipulation instruc-
tions that are useful in embedded
devices but not generally found in
BASIC. The compiler supports all of
the various interrupts associated with
external devices and internal timers. I
hope I’ve piqued your interest enough
to give both the AVR devices and the
BASCOM-AVR compiler a try.
I
AVR. This reminds me of an old say-
ing, “Fool me once, shame on you,
fool me twice, shame on me.”
After this initialization, the pro-
gram enters an endless
DO loop, which
waits for a
<CR> terminated ASCII
string from the serial port UART. The
string is first searched for the pres-
ence of a decimal point using the
INSTR function. If no decimal points
are found, the process is simple. First,
you check to see if the number com-
ing in contains as many digits as the
digit to which this controller is
assigned. If not, assign a code that
will clear the LED. If it does, pick out
the appropriate digit from the string
using the
MID function.
If the ASCII string contains a deci-
mal point, you must break up the
string into two parts, before and after
the decimal point, and then proceed
using the steps I’ve described. You
cannot merely use the
MID function to
pick out the proper digit from the
string, because a decimal point char-
acter is mixed in with the number
and would throw off the procedure.
The final operations are to strip out
the bias of 48 (30 hex) from the ASCII
character and use that result with the
LOOKUP function to convert the integer
into the proper segment pattern. If the
ASCII string contains a decimal point
to the right of this particular digit,
then the decimal point segment is
also turned on.
The binary number version of the
firmware is similar and even less
involved. The only two things worth
noting are that the 4-byte long integer
is sent to the controller with the LSB
first and this 4-byte value must be
SOURCES
AVR devices, 90S8515
Atmel Corp.
(714) 282-8080
Fax: (714) 282-0500
www.atmel.com
LDS-AD16RI LED display
Lumex, Inc.
(847) 359-2790
Fax: (847) 359-8904
www.lumex.com
Brian Millier is an instrumentation
engineer in Dalhousie University’s
chemistry department, Halifax, NS,
Canada. He also runs Computer
Interface Consultants. You may reach
him at brian.millier@dal.ca.
Photo 1—
This is how
the screen looks when
using the Sample
Electronics AVR pro-
grammer built into the
BASCOM-AVR compil-
er. Most of the func-
tions are accessible
from the toolbar at the
top.
42
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
just received my
brand spankin’ new
distribution of Linux
and as I’m writing this
month’s offering, I’m installing it.
There are guys and gals out there who
were around when Linux was just a
little bitty penguin. For those Linux
(and probably UNIX) professionals,
using the resources provided by
today’s Linux is second nature.
Well, I may be a dinosaur, but I did-
n’t grow up sliding around on my
belly to delve into freezing cold water
looking for a free fish dinner. I spent
most of my time washing windows
and fixing broken panes of glass. As a
matter of fact, I still do Windows.
Before that, in the pre-Jurassic com-
puter period, I was
writing programs on a
state-of-the-art Tandy
TRS-80 and producing
graphics using lowly
ASCII characters.
Nothing was free then
and it got even worse
when a gentleman we
all know strolled into
an IBM boardroom to
pitch some software
that, rumor had it, did-
n’t really exist. There
APPLIED
PCs
were a lot of user-written programs
that a geek like me took the time to
put on a diskette and attempted to
run. If I was lucky, I could sign on to
someone’s obscure BBS, answer some
Star Trek trivia, and earn the right to
download “free” code. In most cases, I
ended up buying what I needed. I’ve
always developed things for the “elec-
trically inclined” and I needed the
right tools to produce a decent final
product. Even today, I’ll usually pur-
chase a good quality tool (if I don’t
have it already) to put together a com-
mercial Windows, DOS, or small
microprocessor embedded application.
In other cases, there’s Linux. The
Linux name for “free” is open source.
That means that everybody in the free
world can play with the penguin with
little to no cost other than the com-
puting equipment. In addition, every-
body with good programming skills
who uses the Linux code can modify
it and, if they wish, give away their
productive modifications for the bet-
terment of the Linux community.
Any other charges are there only to
cover the cost of distribution.
Although you can buy Linux stuff,
most of it can be obtained for free
from the Internet, which, in the case
of Linux, has replaced the dial-up BBS
system. If you choose to buy commer-
cial Linux packages like Red Hat,
you’ll find the price is considerably
less than any OS Bill is selling.
NEVER ASSUME
I see Linux as a new and refreshing
addition to the world of computing. In
writing about it, Linux is also a wel-
come breath of embedded fresh air in
the Florida room, too.
Fred Eady
Linux, All Grown Up
i
Fred ponders the
growth of Linux and its
ability to run well with
few resources. What
started out as a tool
that seemed unlikely to
dazzle is now “a new
and refreshing addition
to the world of comput-
ing.” Read on to hear
more about how Linux
will measure up in
real-time applications.
Photo 1—
Designed for portable and set top boxes, the SBC-MediaGX
would have little problem doing server duty on the other side of a router.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
43
was to be able to run all of Bill’s bells
and whistles as well as support that
sort of thing for Linux if you decided
later that you needed it.
The board from Arcom has the nec-
essary core hardware, MediaGX
MMX-enhanced processor, and just
about everything you’ll find in a desk-
top PC to support it. As you might
expect from the MMX, the MediaGX
processor is designed to incorporate a
high level of audio and video process-
ing in a relatively small area.
A 5530 I/O companion IC connects
directly to the MediaGX using both a
direct video and graphics CPU link
and a PCI interface that team up to
provide both analog-based CRT and
digital flat panel display capability.
Power management features provided
by the 5530 are also fully supported
by the MediaGX architecture. No fans
needed here. Just in case I have to
make it play something for Mick and
Keith, the 5530 has an LM4548
AC97-compatible CODEC attached to
its audio interface. The official name
for the MediaGX is XpressAUDIO
and, as you might expect, it’s Sound-
blaster 16-compatible.
While the 5530 is doing lead vocals,
a National PC97317 SuperI/O IC is
providing backup vocals in the form
of general-purpose I/O and standard
ISA functionality. All of the standard
ISA peripherals including parallel
ports, serial ports, keyboard, and
mouse interfaces are crammed into
this single monster IC. The PC97317
also pins out 8 bits of general-purpose
I/O that might come in handy later.
The 233-MHz MediaGX MMX-
enhanced processor is complemented
by a complete set of PC peripheral
components. For our purposes, the
important subjects are covered well.
There’s plenty of SDRAM at 64 MB
(maximum of 128 MB), which in turn
is supported by 16 MB of Intel
StrataFlash. The networking end
is taken care of by a RealTek
8139A that can run the bits
across the twisted pairs at 10 or
100 Mbps. Initial system build
complexity is reduced in that a
standard PC keyboard and
mouse can be employed along
with a standard CRT driven by
Windows look and feel so good to the
end user, and then load a version of
Linux there instead.
EMBEDDED LINUX HARDWARE
Linux possesses a strength in its
ability to run well with few
resources. The latest trend in Linux
computing is moving towards hand-
held devices and generic Internet
appliances. With that, the embedded
hardware I choose will be self-con-
tained and not harbor any mechanical
data storage devices. In other words,
the penguin will reside in silicon.
In a tight-budgeted application, the
SBC would have to be fairly Spartan.
I’m testing the waters here, so a hard-
ware-lean SBC would possibly remove
some of the flexibility and fun associ-
ated with putting up an embedded
Linux box. For my SBC, I selected a
baseline platform that can run all of
the Windows and DOS hardware and
software components comfortably.
Because I’m ignoring the existence of
traditional hard disk drives, I needed
to make sure my choice had plenty of
RAM and flash memory.
At this point I knew what I needed
(sort of). So, I was off to my embedded
SBC storage area to see if I had any-
thing that would fit the bill.
Here’s the scenario. There was a
cute little board, but no Ethernet. I
wasn’t going to do this without being
able to network. Next, I spotted a’486
board, which is one of my favorites,
but doesn’t have enough RAM and
flash memory. Next…whoa! I’d for-
gotten all about this puppy. This one
was right on the money.
If you’re thinking that I lucked out
and discovered a big old AMD or
Intel-based SBC, think again. How
about an SBC based on a part called
Geode from good old National
Semiconductor? One of the criteria
The intent of this article is to pro-
vide some hands-on experience (my
hands, your experience) with Linux
running on an embedded SBC. I won’t
insult your intelligence, but I will not
assume that you know Linux in the
biblical sense either.
Ultimately I want to connect my
Linux-based single board computer to
the Lemos International data radio I
described in “Tuning the Data Radio:
Wireless Data Communication”
(Circuit Cellar 132), but there are
miles to go before we sleep. First
things first. Let’s settle on which fla-
vor of Linux to use and what SBC
will host it.
WHEN PENGUINS FLY
Originally, UNIX and DOS weren’t
too exciting to operate. VT100 termi-
nals and green phosphor monochrome
displays with their cryptic line-by-
line account of the host computer’s
interpretation of the operating system
and application results were only
beautiful in the eyes of their geek
beholders (myself included). In the
beginning, I’m sure no one at Bill’s
complex was losing any sleep over
lost sales to Linux. It seemed obvious
to serious computer professionals
that this OS based on a stubby-
winged Penguin would never fly. Bill
and company saw UNIX as a college
operating system and perceived that
the real money was in GUI-based PC
operating systems that everybody
would write Joe Q. Public applica-
tions for. He was right.
However, these days Linux is far
more than a command line-oriented
operating system. Linux has the pos-
sibility of being everything to every-
one. There has been a debate going on
about the way Linux can or will
behave in real-time applications. I
don’t know if everyone is, as Manfred
Mann would say, “blinded by
the light,” but that’s about as
bad as the press gets for Linux
as a software product. What all
this really means is that Linux
can play right alongside DOS
and Windows, pretty pictures
and all. Therefore, I can choose
from a group of SBCs that has
all of the goodies that makes
Photo 2—
Configuring the Ethernet interface via a file entry won’t work on
your personal Linux system until you build some custom scripts or write
specialized programs to put a wrapper on the real Linux commands.
44
Issue 133 August 2001
www.circuitcellar.com
an onboard Chips 69000
video controller. The SBC
I’ve pulled from the Florida-
room embedded storage area
(called the SBC-MediaGX) is
shown in Photo 1.
Embedded hardware is
nice to look at, but if there’s
no software substance, it’s
just another pretty embed-
ded face. Let’s explore put-
ting some Linux brains
behind the beauty.
EMBEDDED LINUX
Penguin in a can, penguin in a
box…. Isn’t Linux that blanket-drag-
ging kid in the Peanuts cartoons? All
jokes aside, as I pulled the SBC-
MediaGX off the shelf, I remembered
seeing something about an embedded
Linux development kit that might
just work with this SBC. Remember
that Linux distribution I was loading
when I started? Well, it’s up. So, after
entering the necessary IP addresses
and default gateway information, I
fired up the Linux-based Netscape
browser and turned my sights to
Arcom’s web site.
Son of a gun! There it was. My
Florida-room-based SBC-MediaGX
was being used as the platform for
Arcom’s embedded Linux. However,
the names have been changed to pro-
tect the innocent. Instead of SBC-
MediaGX, the embedded Linux ver-
sion is called SBC-GXm. All was good
until I realized that I didn’t have the
Linux code. A special version of Linux
comes pre-loaded with the GXm.
Well, maybe Frank at Arcom can help
me out of this hole.
Here’s how the “conversation”
went, “Hi, Frank. Ahh! I need help.”
“The code’s in the mail!”
As Spock says, “Random chance
seems to have operated in our favor.”
After taking a quick look at the CD I
received from Arcom, I discovered
that the version of Arcom embedded
Linux is based on Red Hat Linux 6.2.
Well, I’ve been there, done that. In
fact, the Linux distribution I loaded is
Red Hat 7.1 with the 2.4 kernel. The
Arcom embedded Linux is based on
kernel 2.2.17 and is space-optimized
for the SBC-GXm.
CIRCUIT CELLAR
®
Everything you need to get a Linux
application running plus some cus-
tom scripts are included with the
GXm software package. The 2.1.3 ver-
sion of the GNU C library is there.
Client and server applications for
both FTP and Telnet are included as
well as an HTTP server. There’s even
a text editor, a bash shell, and system
management utilities available. A
minimal X based on XFree86 and a
Busybox binary rounds out the pack-
age. For those of you who are new to
Linux, what I mean is, there’s more
than enough embedded Linux func-
tionality here. Before you can use it,
you have to install it.
READY TO RUN
For all you hardcore Windows
types, please excuse me. I couldn’t
resist that little pun. Installing the
Arcom embedded Linux distribution
was a snap (just like Windows). The
CD is bootable and all I had to do was
temporarily hook up a standard
ATAPI CD-ROM drive to the SBC-
GXm’s IDE interface. The wall wart
included with the original SBC-GXm
and SBC-MediaGX doesn’t have
enough amperage engineering in it to
support anything external to the SBC
itself. So, I just pulled an old AT-com-
patible power supply out to power the
CD-ROM drive.
There are two methods that you
can use to install the Linux image:
headed and headless (shades of
WindowsNT Embedded here). The
former process implies that a standard
CRT is attached to the SBC-MediaGX
that is soon to become an SBC-GXm.
And, headless installation assumes
that a VT100-like asynchronous ter-
minal will be attached to COM1 of
the SBC-MediaGX accept-
ing the new role of a
Linux-based system.
I tried the installation
both ways because I want-
ed to show you what I did
in the load process. At first
I thought the headless
method was the way to go,
but it really didn’t work
out too well for publica-
tion. So, I installed the ker-
nel and tools using the
headed method. I purposely didn’t per-
form any customization so I could
show you via a Tera Term VT100
screen shot what I could have done
and changed while installing from a
CD. I did, however, choose to load the
full package during the installation
process, and the screen shots are cour-
tesy of Windows.
The onboard flash memory is divid-
ed into three partitions,
boot, root,
and
/var. To keep things secure, the
root or / partition is mounted as read-
only. User information such as home
directories and application data are
stored in the read/write
/var parti-
tion. /
var/temp is a mounted point for
a 4-MB RAM disk. Obviously, if you
want to keep certain information
regardless of powerups or reboots, you
should put it in the
/var partition as
the RAM disk is refreshed and cleared
at every reboot.
The first thing I want to do is get
the newly initiated Linux-based SBC-
GXm up on the Florida-room LAN.
I’ve hacked out a segment for this
project at 192.168.254.0 with a subnet
mask of 255.255.255.0, which is stan-
dard for our class C network. Because
the embedded Linux root partition is
mounted as read-only at boot time,
the first order of business is to
remount it as read/write so you can
modify the network parameters.
This is the first step I perform, as
shown in Photo 2. The Ethernet inter-
face,
eth0, is the network interface for
the LAN segment and it must be con-
figured with a compatible IP address
and subnet mask that matches my
Florida-room network definition. I’m
used to using the
vi editor for matters
such as these, but the SBC-GXm load
of Linux includes only the
ae editor.
Photo 3—
This is a simplified
ifconfig
process. Doing things this way makes it
simple to get the Arcom embedded Linux system on the LAN quickly.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
45
ed in the Arcom embedded Linux dis-
tribution. Photo 4 is a screen shot of
how it’s usually done.
WHAT’S ON THE CD?
Most of what I learn is gained
through reading, experimenting, and
then “discussing” what I’ve discov-
ered with you, the Circuit Cellar
reader. Normally when I prepare to
submit an article, I spend much of
my time poring over technical manu-
als, operational manuals, and data-
sheets that pertain to the subject I
am going to present. Lately, my days
are still spent absorbing the material,
but the paper pages have given way
to web browser-ready or PDF-format-
ted manuals. Every now and then, I
find some neat software packed away
amongst the electronic text.
The CD that I got from Frank (not
Sinatra) not only contained the code I
needed to bring up Linux on my SBC-
MediaGX, it included an open source
tool, Source Navigator, that can be
installed on a desktop Linux box to
aid in project development on the
embedded SBC. The abundance of
standard PC peripherals is great, but
my focus this month is on the eight
general-purpose I/O (GPIO) bits hang-
ing off the PC97317.
To ease development pain, boiler-
plate code for the GPIO bits is
stashed on the Arcom distribution
CD. My plan is to use the Arcom
code as a template for constructing
my own RF/SBC-GXm interface code.
Taking a look at the programming
rules of the moving data between the
RF controller and the host I described
last time will give you an idea of
what I have in front of me. It will be
a bit-bang party using modified rou-
tines based on the original demo code
in the
GPIO.c source file.
The example code
has all of the necessary
functions to manipu-
late the GPIO bits.
Using the basic read,
write, input, output,
buffered, and
unbuffered C functions
of the boilerplate, I
will be able to control
the PIC that controls
the RF transceiver on the Lemos data
radio board. The GPIO C code is too
lengthy to print here. I’ll post the final
version so you can retrieve it from
Circuit Cellar
’s web site.
LOGGING OUT
I’ll admit, I did some Windows bash-
ing, but in reality Linux and Windows
exist in a cooperative user environ-
ment. The Arcom Embedded Linux
distribution and the SBC-GXm can be
a learning system or a production
development platform. It all depends
on how deeply you want to delve into
the Linux workings and what your
final application requires. As far as I’m
concerned, Linux isn’t complicated.
It’s embedded.
I
That’s fine because
ae
is not as “fraternal” as
vi. Again, looking at
Photo 2 you can see
that I changed directo-
ries to the one that
contains the interface
definition file for
eth0
and edited the same.
Photo 3 is the resulting
edit of the
eth0 file.
There’s also another file in this
directory named
lo, which is short for
local loop-back. This address is nor-
mally used for testing when there is
no physical network available. On the
SBC-GXm it is set to the standard IP
address of 127.0.0.1 with a subnet
mask of 255.0.0.0. This address is nor-
mally associated with
localhost.
Not happy with just pounding bits
around the Florida-room network, I
pointed the SBC-GXm at a gateway I
have installed that leads to a
name-
server furnished by one of my ISPs.
And, because I’m going “out there”
on the Internet, it would be nice to
not have to specify an IP address for
every domain I want to communicate
with. Therefore, I will invoke the
services of DNS and specify a name
server, as well.
Adding a gateway to Arcom embed-
ded Linux is easy. All you have to do
is create a file called
gateway in the
/etc/config/networks/routes directo-
ry and enter the GATEWAY = IP
address where the IP address is my
gateway on this LAN segment.
You can apply this same simple
method to provide a DNS entry in the
/etc/resolv.conf file (nameserver IP
address). Executing the command
/etc/init.d/network brings the file
values to life. Also note that if you
hit the IP numbers, the SBC-GXm is
on the Internet.
For those of you who are familiar
with Linux, you’re probably scratch-
ing your head about some of the net-
work setup I just performed. Keep in
mind that this is an Arcom embedded
distribution and the intent is to take
anyone, including a Linux novice
through the hoops with little effort.
For instance, the
gateway and eth0 file
creation processes to define a gateway
and an interface are shortcuts provid-
Photo 4—
Here’s a look at how it would have to be done without the Arcom customizations. I
added a look at the routing table so you could see the results of the commands.
Fred Eady has more than 20 years of
experience as a systems engineer. He
has worked with computers and com-
munication systems large and small,
simple and complex. His forte is
embedded-systems design and com-
munications. Fred may be reached at
fred@edtp.com.
SOURCES
Geode, PC97317
National Semiconductor (Cyrix
Corp.)
(408) 721-5000
Fax: (408) 739-9803
www.national.com
Linux 7.1
Red Hat, Inc.
(888) 733-4281
Fax: (919) 547-0024
www.redhat.com
46
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
n the 21st
Century, the prom-
ises of flying cars,
autonomous robots, and
colonization of Mars are dreams yet
to be realized. Although progress has
been made with the International
Space Station, automobile engines are
still based on the old internal com-
bustion system and robots are auto-
mated mechanisms used for quick
mass production on the assembly line
(a far cry from the endearing R2-D2
and chatty C-3P0 from “Star Wars”).
We have yet to see the robot that fol-
lows the three laws postulated by
Isaac Asimov, which will provide us
with more free time. [1] The ideal
robot would be safe, useful, and
affordable to the average family.
Robotic design involves art, elec-
tronics, software, chemistry, mechan-
ics, and physics. But, the good news is
that only rudimentary knowledge of
any of these fields is required to
assemble a simple utility robot.
The PIC18C452 prototype board is
the foundation for most of my robot-
ics projects. It’s easy to assemble and
makes a great test bed for microcon-
troller-based robotics experiments. It
allows you to experiment with
advanced embedded development
tools such as Microchip’s MPLAB and
C compilers (which support the
PIC18Cxxx devices) to make it easier
to develop embedded microcontroller
projects in C (which are usually done
in assembly language).
I used C because it’s readily
portable to other processor platforms
and is more readable and maintain-
able than assembly language. The typ-
ical hobbyist would rather just get an
application working than squeeze
every cycle out of a microcontroller,
as is commonly done with commer-
cial applications. C is also easier for a
novice in the embedded programming
field to develop, debug, and test code.
The following article will detail the
steps required to use C with
PIC18Cxxx devices, including pro-
gramming the PIC18C452 EEPROM
with an inexpensive programmer and
using Microchip tools (MPLAB, C
compiler, C linker, and C libraries).
WHY THE PIC18C452?
The greatest challenge involved in
completing a successful robot is
choosing its “brain”: in this case, a
PIC18C452. A 1- or 2-GHz Pentium
laptop could, in theory, make a great
brain for any robot, but the size,
power requirements, and cost limit its
use to large robot platforms in
research labs. Besides, a laptop hard
drive might not survive the bumps
that most robots experience. Other
processors such as the 68HC12, 8052,
Atmel AVR family, or Basic Stamp
BS2/BSX/BSP could be substituted at
additional expense and complexity.
Currently, I’m working on a robot
sensor controller board, relay con-
troller board, and a gardening robot
(GardenBot) using the PIC18C452 as
the controller. The GardenBot is
based on the ’18C452 and includes
components from other projects. Of
course, these days, to build a simple
robot such as this, a basic micro-
processor controller board is required.
Within the Microchip family, I had
the choice of PIC15Cxx, PIC16Fxx,
PIC17Cxxx, and PIC18Cxxx devices.
When comparing the cost versus per-
formance for these devices, the
PIC15Cxx devices are not powerful
enough to be supported efficiently
FEATURE
ARTICLE
Daniel Ramirez
Optimize Your PIC
i
Robotic designs today
involve everything
from chemistry to art.
As many of you know,
the foundation for
many of these proj-
ects is the ’18C452
board. Daniel’s here
to discuss his robotic
PIC project with help-
ful tips for both hob-
byists and profession-
al developers.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
47
with a high-level language (HLL) com-
piler and would require extensive
assembly language development.
The PIC16Cxx are capable mid-
range devices. These devices are ideal
for small, specialized tasks, such as
controlling servo stepper and motors,
but can be cumbersome when used on
larger projects.
The PIC17C42 is a high-end device
that was adequate for more advanced
projects until the PIC18C452 became
available. Then the choice became
obvious: The PIC18Cxxx is pin-com-
patible with the PIC16Fxxx devices
and similarly priced, but light years
ahead in performance and capability
(linear memory addressing up to
2 MB) with a processing speed of up
to 10 MIPS. [2] I had found the perfect
brain for the GardenBot.
Because so many microcontrollers
can be used in a single robot for
multi-processing, cost per device can
become an issue, particularly for hob-
byists. Other factors affecting cost are
hardware development tools (e.g., pro-
grammers, emulators, UV erasers,
logic analyzers, and PC board fabrica-
tion costs) and software development
tools (e.g., simulators, emulators,
debuggers, assemblers, compilers, and
linkers). All of this hardware and soft-
ware adds up to a cost that can be dis-
couraging for the average hobbyist.
Demo software, shareware, and
freeware become attractive alterna-
tives. Another possibility for the hob-
byist is the use of recycled computer
and electronic hardware. If you rescue
an Epson printer from the recycling
station, you may
find one of the
most powerful step-
per motors around
for its compact
size. Electronic sur-
plus stores are
incredible sources
for inexpensive
electronic compo-
nents, gears, rods,
and scrap metal.
Even antique stores
are a possible gold-
mine for building
materials, because
they frequently sell
Gilbert and Meccano erector sets as
well as used robot toys.
Despite the fact that there are many
good free tools available for these pop-
ular processors, I ruled out the
68HC12 and 8052 microprocessors for
my own use. The requirement of the
68HC12 for a PLCC with very narrow
traces was a deciding factor, because
wire wrap techniques and standard
PC board construction techniques are
not suitable for it. Availability is also
an issue because it’s used extensively
by the automobile industry.
I thought that the Parallax Stamp
BS2/BSX/BSP microcontrollers would
be expensive for my projects, even
though the one-time startup costs for
its programmer and software are less
than $100. The unit prices for Stamp
microcontrollers are $79 for the
BSP24-IC and $99 for the BSP40-IC
(these devices include I
2
C support and
are closest in hardware features to the
PIC18C452). On the other hand, a sin-
gle PIC18C452 costs about $20 at
Digi-Key. The Stamps are great proto-
typing devices, which I used initially
for each of my projects. I have learned
to treat them like fine china since I
accidentally “broke” one of them!
The only two remaining micro-
processor families to consider were
Atmel and Microchip. Each is compa-
rable in cost and features, but I chose
to use the Microchip family because
I’m familiar with it.
The PIC18C452 is one of Micro-
chip’s top-of-the-line 8-bit RISC
microprocessors. Hobbyists will
appreciate the low cost and ease of
integration using the PIC18Cxxx fam-
ily for robotics, embedded systems,
and control applications. The device
out-performs most other 8-bit micro-
processors and is available as a 40-pin
DIP while most new microcontrollers
are 64 PLCCs. This makes it an ideal
candidate for prototyping and a good
choice for a microcontroller that can
be used as the platform for an embed-
ded system or robotic application.
PIC18C452 ARCHITECTURE
The PIC18C452 prototype board
was designed for modularity and
expandability and it’s easy to modify
(see Photos 1 and 2). In its simplest
configuration, the board is used for
carrying out experiments with
Microchip C and MPLAB, which are
helpful in order to fully understand
the tools and techniques required for
advanced projects. Microchip also
sells demo boards that perform a sim-
ilar function, but at a higher cost.
Keep in mind, you can purchase this
board instead of building the one
described in this article and still be
able to perform similar experiments
with the Microchip software tools.
Figure 1 shows the PIC18C452 pro-
totype board. Each I/O pin is brought
out to a pin header. A MAX233 IC
handles the RS-232 communications
between the PIC18C452 and a host
PC runs Microchip’s software tool
suite. The serial EEPROM is a
Microchip 24LC16 that is used to test
the I
2
C communication functions.
DIP switches simulate hardware
interrupts and enable or disable I/O
pins. The LEDs indicate pin status.
An optional hex keypad may be con-
nected to the pin headers on the
board. An optional 5-V regulated
power supply may be included to
power the board from a 9- to 12-V bat-
tery or wall transformer if a regulated
5-V supply isn’t available.
The I
2
C hardware allows various
subsystems of the robot to communi-
cate data and commands efficiently
using only a two-wire bus. This
reduces a lot of the spaghetti wiring
commonly associated with home-
brew robotics and is unavoidable
when using wire wrap methods. It
also allows the microcontroller to
Photo 1—
In this view of the topside of the PIC18C452 board, you can see where
the components should be placed.
Photo 2—
Notice the color
scheme used for wire wrap-
ping. Red is for power wires,
black is for ground wires, and
white is for logic wires.
48
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
access other hardware ICs such as
serial EEPROMS, real-time clocks,
and temperature sensors.
SOFTWARE TOOLS
To keep development costs to a
minimum, I chose either free, demo,
or shareware software tools.
Microchip offers many tools on its
web site and a CD-ROM. These tools
include MPLAB and the MCC18
demo C compiler. You can buy the
full working version of this compiler
from Digi-Key for $495. MPLAB is a
free tool that includes a simulator
assembler and linker. It also provides
control of the programmer.
The MCC18 compiler demo will
work for 30 days before it’s disabled.
This should be enough time to per-
form the experiments described in
this article. Microchip and other C
compiler vendors sell complete work-
ing software tools to support the chip
but at full price. I figured out a
method to work around this limita-
tion using Microchip products. You’ll
have to come up with a procedure to
work around the problem, as well.
For schematic capture, I used a
demo version of Eagle. It’s a working
version that handles a 3
″
× 4
″
PC
board and provides schematic capture
capabilities. For about $50, you can
register this version commercially.
You may download this software from
CadSoft Computer (the professional
version costs $399). To work around
the limitations of the demo, I
designed small modules in a manner
similar to object-oriented program-
ming (OOP) and connected them
using SPI, I
2
C, jumpers, terminals,
and small busses.
HARDWARE TOOLS
In addition to the software, you will
need a handful of hardware tools.
First, there’s the EEPROM program-
mer, which is required to program the
PIC18C452. For this, I selected the
WARP-13 programmer ($99) made by
Newfound Electronics.
You also need a UV lamp with lamp
holder if you’re going to use PC con-
struction methods. M.G. Chemicals
sells one for around $20.
A UV eraser to erase previously
burned-in firmware made by Walling
is available from Digi-Key for $40.
Lastly, make sure you have a PC or
laptop to run the Microchip software,
Hyperterminal serial communication
software, and EEPROM programmer.
Test equipment such as a good
scope and DVM are helpful for debug-
ging this project. A logic analyzer is a
great tool, but is usually too expen-
sive for the average hobbyist. Surplus
stores carry various models.
Wire wrap tools such as an electric
wire wrap gun or a manual wire wrap
tool are all that are needed when
using the wire wrap prototyping
method. With the exception of Radio
Shack’s wire wrap tool cat. no.
276-1570, I usually find the best
prices at surplus stores. Digi-Key and
Jameco seem to have the best prices
for wire wrap sockets and pin headers.
CONSTRUCTION TECHNIQUES
Wire wrapping is becoming a lost
art. This is unfortunate because it’s
more practical for you to wire wrap a
small board than to send it out to be
fabricated. A single midsized PC
board manufactured by a fabrication
store typically costs around $250. I
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
49
chose to wire wrap the board using a
wire wrap gun that I purchased for
$15 at a surplus store.
Another issue that is rapidly
becoming problematic is the trend of
manufacturers to make only surface
mount devices. This includes devices
such as capacitors, resistors, and ICs.
For the hobbyist, these surface mount
devices are problematic to work with
because they require specialized tools.
I try to find devices in DIP IC or stan-
dard packages. If the miniaturization
trend continues, I would consider
making a small tele-operated surgical
device to handle these components at
the smallest level.
For the lighter and more rugged pro-
totype boards required for mobile
robots, I recommend the PC construc-
tion method. This requires either a
positive or negative etching kit. The
disadvantages to this method are the
use of chemicals and the extra steps
required to fabricate a PC board. I rec-
ommend a kit manufactured by M.G.
Chemicals which provides all the
equipment required for the positive
artwork etching method.
I also suggest reading Jan Axelson’s
book about PC fabrication. [3]
BUILDING THE PIC18C452
BOARD
To build the PIC18C452 prototype
board, use the schematic shown in
Figure 1. Parts placement and board
fabrication techniques are not critical.
Note that wire wrap, point-to-point,
and PC board construction all can be
used for this project.
Start by soldering the pin headers
and IC sockets onto the board. Next,
solder the 0.1-µF bypass capacitors as
close to the IC socket power pins as
possible. Do not clip the leads
because they make handy wire wrap
or point-to-point posts. However,
remember to add solder to each joint
on a round component lead, because
these won’t give you the proper gas-
tight joint you get on a square wire
wrap post. Solder other discrete com-
ponents such as resistors, capacitors,
and diodes as designated in Figure 1.
Wire wrap labels can be purchased
from Digi-Key to make the wire wrap-
ping task easier. Next, wrap the
power lines using red wire and wrap
the ground lines using black wire. Tie
all ground wires to a single post if
possible. Finally, wrap each logic sig-
nal using white or blue wire, checking
off each one from the diagram until
all signals have been wired. Screw any
outstanding PC parts to the PC board
and glue or solder the RS-232 connec-
tor directly to the PC board.
At this point, it’s time to check the
circuit for shorts and open lines by
using your DVM to check continuity
on all power, ground, and logic sig-
nals. You should inspect the board
using a magnifying glass. If you have
a video camera with good macro capa-
bilities, circuit boards can be viewed
on a TV screen or monitor using a
video camera with macro zoom as
well. Keep in mind, the monitor is
also handy for soldering tiny surface
mount components.
Before populating the board with
ICs, power the board by connecting a
9-V battery and check to see if the
power LED lights up. If it does, check
for 5 V at the V
DD
pin of each IC and
no voltage at the V
SS
pins. After this
has been accomplished, you can popu-
late the board with the ICs and fire it
up for the first time.
You may need to add minor modifi-
cations to the board when carrying
out the PIC C experiments.
PROGRAMMING THE PIC18C452
On your PC or laptop computer,
install MPLAB by clicking the Setup
icon from the installation file. You
can download this from Microchip’s
web site or CD-ROM. During setup,
select the PIC18C452 as the target
processor. Install the MCC18 C com-
piler in a similar manner. Finally,
install the WARP-13 or Microchip
programmer software. At this point,
all the tools needed to use the
PIC18C452 should be in place. For
convenience, you may want to create
shortcuts for these programs to your
Windows desktop. [4, 5]
The first task is to create an
MPLAB project for the test applica-
tion. It will contain all the files asso-
ciated with the test program, includ-
ing the C source code, listing files,
map files, and hex files that you can
50
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
text. This is done using the
printf
and
dec functions. You may use these
functions to implement a simple
debugger. These functions exemplify
how Stamp designs can be translated
easily from BASIC to PIC C.
The second test involves initializ-
ing, reading, and writing to the PIC
I/O ports using LEDs as indicators
and switches to change the state of
each I/O pin.
The third test is to develop a simple
stopwatch application that demon-
strates the PIC’s timers.
The fourth test uses the I
2
C func-
tions to initialize the I
2
C hardware,
read and write to a 24LC16 serial I
2
C
EEPROM by writing a ramp to the
EEPROM, and then read back again
and compare the results.
The fifth test interfaces a hex key-
pad to the board and reads it using the
change on port B status interrupt. The
sixth test experiments with the PIC
interrupts by using an ISR written in
PIC C instead of assembly. It’s used to
count external events.
burn into the PIC. The source code
listings are available on Circuit
Cellar
’s web site.
MICROCHIP C LIBRARY
Microchip has provided many low-
level C functions that access the
PIC18C452 internal hardware features
directly without requiring you to
delve into the complexities of assem-
bly language. Of course, you can write
assembly language routines using
MPLAB and maybe even link them to
C routines by using the interface-to-
assembly technique shown in the
MPLAB compiler user’s guide. [4] This
hybrid approach may appeal to people
who think that assembly is the most
efficient way to develop embedded
microcontroller software. This can be
accomplished by coding the time-crit-
ical code inside the innermost loops
in assembly language.
EXPERIMENTS WITH PIC C
The following C experiments may
be carried out with the prototype
board as an exercise. I have provided
most of the functionality with the
test1.c test program available on
Circuit Cellar
’s web site. These exper-
iments use functions from the
Microchip C libraries, including those
involved with the USART, timer, I
2
C,
and port I/O functions. Also included
are some of my own utility functions.
The USART will be needed during
these experiments for serial I/O and
debugging, with a print function I
developed as a simpler version of the
ANSI C print function. It prints text
to the serial port exclusively. For
printing numeric data, I developed a
low-level
printf function similar to
C, and a
dec function that is identical
to the Stamp BSX function. The pro-
totype board may need minor modifi-
cations to perform some of the experi-
ments I included.
There are eight PIC C experiments.
The first is using the PIC C USART
library functions to initialize the
USART and read and write to the seri-
al port in order to input and output
Figure 1—
There are optional sections that you can leave out of the PIC18C452 prototype board to save on wire wrapping.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
51
using cost-effective tools. The
PIC18Cxxx architecture lends itself to
a high-level language such as C, and
the PIC18C452 prototype board can
be used as a learning and develop-
ment platform for more advanced
applications in automation, control
systems, robotics, tele-presence, and
embedded systems.
Although the initial startup costs
for the PIC18Cxxx devices are higher
than for the Stamp BSX, a hobbyist
may also develop embedded applica-
tions that would ordinarily be devel-
oped commercially using expensive
software and test hardware. I also
demonstrated how the startup costs
can be tailored to a hobbyist’s budget
range by taking advantage of commer-
cial software demos, shareware, as
well as freeware.
There are ways to work around the
restrictions placed on the various
commercial demo applications. Stamp
BSX/BSP designs can be ported to the
PIC18Cxxx architecture using I
2
C and
C functions that emulate the Stamp
BSX/BSP instruction set. Other Stamp
functions can be emulated to make it
easier to develop prototype code using
a Stamp, and then translate the code
to PIC C for the final product, thus
reducing the unit cost.
I
SOURCES
Eagle
CadSoft Computer, Inc.
www.cadsoftusa.com
Fabrication kit
M.G. Chemicals
(800) 708-9888
(604) 888-7754
www.mgchemicals.com
WARP-13 programmer
Newfound Electronics
+61 3 5224 1833
www.new-elect.com
Stamp
Parallax, Inc.
(888) 512-1024
(916) 624-8333
Fax: (916) 624-8003
www.parallaxinc.com
Datarase II UV eraser
Walling Co.
Jameco Electronics
(800) 831-4242
(650) 592-8097
Fax: (650) 592-2503
www.jameco.com
SOFTWARE
The source code is available on the
Circuit Cellar
REFERENCES
[1] I. Asimov, I Robot, rev. ed., The
Bantam Dell Publishing Group,
1994.
[2] Microchip Technology Inc.,
“PIC18CXX2 Data Sheet: High
Performance Microcontrollers
Author’s Note: Thanks to my wife,
Pamela, for her time and assistance
with this article.
Daniel Ramirez is a senior software
engineer with more than 10 years of
experience working on real-time
embedded systems. His hobbies are
travel, golf, treasure hunting, and
robotics.
The seventh experiment you can do
performs DC motor control using the
PIC PWM hardware.
And, the final experiment reads an
optical encoder by using the PIC cap-
ture hardware.
EMBEDDED HARDWARE
The MPLAB simulator is used to
debug PIC C programs by setting
breakpoints using the
breakpoint
function and displaying the registers
and variables using the
watch func-
tion. The code can be stepped through
using the
step into and step over
functions. Using the MPLAB simula-
tor for debugging allows you to com-
pletely execute the C and assembly
logic without having to burn a PIC
device. The only disadvantage to this
method is that the code is not execut-
ed in real time.
This task is usually accomplished
on commercial applications using an
in-circuit emulator, or ICE, which has
expensive hardware that allows the
embedded developer to debug his
application in real time. However,
using the techniques developed with
the first experiment, these costs can
be trimmed at the expense of conven-
ience to an RS-232 serial cable and a
serial communication program such
as Hyperterminal. The idea is to place
print and dec statements at strategic
locations within the C application
you’re debugging. This is similar to
using the
debug statement on the
Stamp BSX. The contents of variables,
PIC registers, and memory can be dis-
played in this manner.
New technologies, such as in-cir-
cuit debugging (ICD), which are cur-
rently available for the PIC16Fxxx
series, should be available soon for
the PIC18Fxxx devices. The new tech-
nologies will allow companies that
manufacture embedded tools to devel-
op less expensive sets of debugging
tools for the PIC18Fxxx when it
becomes available.
SUM OF ALL PARTS
Throughout this article, I have
attempted to show how embedded
software may be developed in the
Microchip PIC C using a PIC18Cxxx
by hobbyists and software developers
with 10-bit A/D,” DS39026B,
2000.
[3] J. Axelson, Making Printed
Circuit Boards
, McGraw-Hill,
New York, NY, 1993.
[4] Microchip Technology Inc.,
“MPLAB CXX User’s Guide,”
DS51217B, 2000.
[5] ———, “MPLAB-CXX Reference
Guide,” DS51224B, 2000.
52
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
oday’s automo-
tive instrumenta-
tion consists of,
among other things, air
core-driven meters for dashboard indi-
cation of engine revolutions per
minute. In this electronic environ-
ment, this method provides the most
robust, controllable way to indicate
engine speed of a variety of models in
a car manufacturer’s line. A simple
ROM module (code plug) plugged into
the common meter-drive electronics
tailors the output to the model differ-
ences and makes the display fit the
particular car’s characteristics (gearing
to rpm sensor, etc.).
The air core meters can be electron-
ically driven by a Philips IC device
that takes in 10-bit serial data and
outputs properly phased signals to
make the meter move to the correct
value (about 0.35° per LSB).
The input to the meter-drive elec-
tronics is a pulse train from a magnet-
ically derived signal mechanically
coupled to the engine. The higher the
engine rpm, the closer in time are the
rising edges of the pulse train. I need
to translate these timed edges into
10-bit data to drive the rpm meter to
the proper indication (as a function of
one of the ROM modules).
FEATURE
ARTICLE
Car instrumentation
can be electronically
driven with a simple
ROM module plugged
into the common
meter-drive electron-
ics, providing the
most controllable way
to indicate engine
speed. If you feel the
need for speed (and
accuracy), come
along for the ride.
TO BEGIN
I built the electronics first, which
included a PIC flash memory proces-
sor (PIC16F876) attached to the
Philips IC (SA5775A). This helped
determine which values of the 10-bit
data drive the meter to which reading.
Figure 1 shows a simple bit-banged
serial attachment to one (of two) of
the meter-drive chips.
Then, I put a function generator
pulse stream into the factory meter-
drive electronics with a particular
ROM module (CP06) plugged into it
to determine which pulse edge timing
produced which meter reading. This
gave the data listed in Table 1.
The first column in Table 1 is an
arbitrary index. For example, column
three has a 10-bit data value of 0x14F
(index 7), which drives the meter to a
3500-rpm reading when sent to the
SA5775A. The fourth column is a
decimal representation of the 10-bit
hexadecimal meter data. This is the
desired value to produce as a function
of the input timing.
The next column is the measured
timing difference between rising edges
of the input signal (into the factory
meter-drive electronics) that gave the
indicated meter reading. The final col-
umn is an observed 16-bit decimal
value formed by capturing a free-run-
ning timer (clocked at 500 kHz) on
every rising edge of the signal. The
variance between the predicted value
(time × 500) and observed value is
measurement and calibration error.
My next task was to produce the
10-bit data from the 16-bit difference
value detected from the pulse train.
FIRST TRY
I originally used only the high byte
of the detected difference count (in
hex) as an index of a table of 8-bit
data values to translate the timing
into meter data (8 bits shifted left
twice to become 10-bit meter data).
This produced jumps in the meter
reading in the higher rpm range
because a small change in the pulse
train timing gave indexes numerically
close to each other.
The table entries for these indexes
could not be smoothly extrapolated to
produce discreet meter readings for all
Dennis Nagel
Lacoste
PIC Floating Point
t
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
53
meter positions. The table could be
increased to include more entries over
more difference values, but this grows
quickly, and the program memory
available for table data is limited
because I need several tables for sever-
al ROM modules. So, it was obvious
that I needed another method.
ENTER FLOATING POINT
One of the advanced features in an
Excel spreadsheet is the placing of a
trend line on a chart. I used the chart-
ing function to plot the decimal tim-
ing difference counts (see Table 1)
verses the arbitrary index, and added a
trend line that gave a power formula
for production of the count (depend-
ent variable) as a function of the
index (independent variable). This for-
mula looks like (see Figure 2):
count = constant × index
exp
[1]
Because I really want to produce the
index as a function of the count, I had
to use the inverse of the formula:
[2]
When the index is calculated, it is
then a straight line formulation of the
slope formula, y = mx + b, to produce
the final result. x is the index pro-
duced from the calculations, m is the
slope, and b is the y-intercept found
from a straight line trend line on
another spreadsheet chart of the index
verses the 10-bit meter data. If I can
calculate the index, I can smoothly
produce 10-bit meter data for any
count input to the process.
DETECTING THE PULSE TRAIN
Note that the PIC capture module
is the ideal component for turning a
periodic timing event into a numeri-
cal value. A free-running 16-bit count-
er (timer0) is latched into a 16-bit
holding register with every edge (posi-
tive or negative) of the pulse train fed
into the capture module.
The data shown in Table 1 illus-
trates the pulse train timing (between
positive edges) ranging from just less
than 4 ms at a high rpm to greater
than 40 ms as the engine slows to less
than 500 rpm. Because I am running
this chip at 16 MHz, the PIC machine
Meter drive
Rising edge
Captured count differences for
Index
rpm
10b hex
10b decimal
time (ms)
500 kHz into a 16-bit binary register
1
500
03C
60
42.30
21022
2
1000
06E
110
24.36
12106
3
1500
0A3
163
16.80
8349
4
2000
0D1
209
12.83
6376
5
2500
0F7
247
10.76
5347
6
3000
123
291
9.05
4498
7
3500
14F
335
7.86
3906
8
4000
182
386
6.94
3449
9
4500
1B7
439
6.18
3071
10
5000
1E3
483
5.57
2768
11
5500
20D
525
5.08
2525
12
6000
23E
574
4.64
2306
13
6500
26F
623
4.31
2142
14
7000
2A1
673
3.99
1983
15
7500
2D2
722
3.71
1844
Table 1—
This table compares rev-
olutions per minute versus meter
drive values and the timing neces-
sary to drive the meter to that rpm
reading. To figure out which pulse
edge timing produced which meter
reading, I put a function generator
pulse stream into the factory meter
drive electronics with a ROM mod-
ule plugged into it.
Figure 1—
The PIC processor connects to the Philips meter drive chip.
54
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
SOFTWARE
The code is available on Circuit
Cellar
RESOURCES
[1] Microchip Technology Inc.,
“AN575—IEEE 754 Compliant
Floating Point Routines,”
DS00167A, 1996.
[2] ———, “AN617—Fixed Point
Routines,” DS00617B, 1996.
[3] ———, “AN660—Floating Point
Routines,” DS00660A, 1997.
cycle rate is 4 MHz. If this is put
directly into the timer0 16-bit count-
er, it will overflow the capacity in
16.38 ms—too short a time.
Fortunately, the capture module
includes the ability to insert a
prescaler between the clock and timer
input. If a 3-bit prescaler (divide by 8)
is used, the range of 4- to 64-ms tim-
ings results in a decimal count range
of 2000 to 32,000, respectively. This
is nicely scaled for the counter’s
capacity (65536 decimal).
When an edge is detected, the
timer0 value is latched to the holding
register and an interrupt is generated.
The interrupt causes the code to read
the holding register and calculate the
16-bit difference count between this
value and the value captured on the
previous edge event. These counts are
in the right-hand column of Table 1.
For instance, if you take a look at
index number 11, representing an rpm
reading of 5500, a 5.08-ms sample of
the 500,000-Hz input (4.0 MHz divid-
ed by 8) is a decimal count of 2525.
FINDING INFORMATION
Microchip’s web site offers zipped
files of the floating point source code
described in the Microchip Math
Library. These files are contained in
application notes AN575, AN617, and
AN660 primarily. [1–3] I created fold-
ers for these three application notes
and downloaded the three zipped files
into their respective folders. The code
is necessary to do the calculations of
equation 2 plus the slope formula.
Because I’m using a PIC16Fxxx, the
issue of paging is still a consideration
when adding significant amounts of
imported (or included) code. Simply
including the necessary
source files as they were
unzipped generated
machine code beyond a
2k page size, so editing
the files was necessary
to take out the unused
routines and alter labels
to permit routines to
call from page to page
correctly. This is not a
trivial exercise, and it’s
certainly instructive.
PUTTING IT ALL TOGETHER
When I got everything assembled
correctly, I tested the routines to pro-
duce correct results in test instances.
Then, I worked on using the routines
to produce the calculations indicated
by Equation 2. An identity of:
A
B
= e
B × ln(A)
[3]
helps in the order of calculations.
The process is as follows. First, con-
vert the 16-bit integer count to 32-bit
floating point (FLO3232). Second,
divide the formula constant (from the
spreadsheet trend line) by the count
(FPD32). Third, form the ln (log) of
the quotient. Fourth, multiply by the
reciprocal of the exponent (from the
spreadsheet) (FPM32). For the fifth
step, form the inverse natural log of
the product (exp).
The preceding five steps yield a
floating point number in the 0.0 to
16.0 range, which now may be used to
produce a 10-bit meter value using
the slope formula.
Moving on to step six, multiply the
meter value by the slope constant
(FPM32). The straight line slope is
formed with data from Table 1. When
you chart the index verses meter data
with a straight trend line formula, the
result is m = 46.942. AN575 includes
an
FPREP.EXE utility to convert any
number to a PIC 32-bit floating point
representation. Using the
FPREP.EXE
utility with this slope value produces
0x843BC49C. The constant is hard-
coded into the process (for this code
plug, the constant is CP06).
For the seventh step, add the y-
intercept (FPA32). Here, the y-inter-
cept is 14.213 (0x82636873).
Lastly, convert the result to integer
form (INT3232) for step eight.
The final conversion leaves an inte-
ger hex number in AARGB2 and
AARGB3 (Microchip designates math
support variables) in the 0 to 0x3FF
range. An include file,
math16.inc,
declares the support variables. To ver-
ify the code’s operation, compare the
predicted results in the spreadsheet to
simulation values for several test
instances of input data and the actual
performance of operational code in an
electronic test setup. The results for
this application are good.
I
Author's Note: Thanks to Wil Blake
and Dr. David J. Nagel for their assis-
tance on this project.
Dennis has a BSEE from California
State University at Long Beach. He
worked for IBM for eight years and
started his own consulting organiza-
tion in 1979. He is a licensed
Professional Engineer and works on
embedded designs and their
firmware. You may reach him at
dnagelmail@yahoo.com.
SOURCES
PIC16F876
Microchip Technology Inc.
(480) 786-7200
Fax: (480) 899-9210
www.microchip.com
SA5775A
Royal Philips Electronics
(212) 536-0500
Fax: (212) 536-0559
www.philips.com
– 0.9
y = 22374x
0
5000
10000
15000
20000
25000
1
3
5
7
9
11
13
15
103
Figure 2—
The graph shown here plots the index displayed in Table 1 ver-
sus the 16-bit decimal count.
56
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
everal years ago,
I moved into a
house with a backyard
pool. My family soon
became frustrated that although we
had to maintain the pool year-round,
there were only about three months
of warm water for swimming.
A gas-fired heater is impractical to
warm the pool based on energy costs,
so I threw a bunch of PVC pipes on
the roof and began working on a con-
troller to run the pump. The first ver-
sion I created was an analog compara-
tor with a thermo-sensor from a
Dodge van. Several iterations later, I
arrived at an all-digital, PIC-based
controller with I
2
C temperature chips
collecting data, an LCD displaying it,
and an SSR driving the pool pump
(see Photo 1). Now, our swimming
season has been extended to about
seven months of the year.
HOW IT WORKS
The design works on the same prin-
ciple as what I call the garden hose
effect. Fill the pipes with water, let
the sun heat the water, then cycle the
heated water back into the pool. It’s
remarkable how efficiently the sun
heats water. The typical pool pump
needs to run about four hours per day
minimum just to keep the pool clean.
I take advantage of this minimum run
time to heat the pool for free.
In the most basic system, the heater
cycle would coincide with the normal
pump operation, typically an electro-
mechanical timer. This tends to be
inefficient for heat transfer because
the water increases just a few degrees
but cools down on the way back to
the pool. My system cycles the pump
on and off based on the data from two
sensors that check the solar collector
and pool temperatures. Typically a
difference of about 10°F is a good start
value. This allows the water to cool a
bit during the trip back and still have
reasonable net gain in temperature.
To achieve system efficiency, there
needs to be sufficient run time to
allow most of the heated water to
enter the pool, but not so much time
to cycle cold water back to the pool.
This time depends on such things as
the distance of the collector from the
pool, diameter of the supply/return
lines, and characteristics of the pump.
For my system, about 3 min. is a good
run time. A cycle is initiated when a
start condition is met (i.e., the differ-
ence between the two sensors is over
the threshold). At that time, the run
timer is loaded with the run time
start value; the run timer will be con-
tinually reloaded with the start value
as long as the condition that initiated
the start is met.
Provision has been made for a man-
ual enable/disable for cleaning and
maintenance. A single sensor solution
is also included. In this case, the start
condition is based on the temperature
of the heat collector only.
FEATURE
ARTICLE
Loren Hunt
Poolside in April
Building a Solar-Powered Pool Heater
s
Throw in some tem-
perature chips, an
LCD, and an SSR,
and you too could be
poolside most of the
year. Just in time for
fall, Loren has
devised a way to
extend those short
summer months with-
out increasing energy
costs. Don’t put away
that bathing suit yet!
Photo 1—
The electronics are mounted inside an
industrial outdoor electrical box.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
57
THE PLUMBING
PVC pipe is used throughout. Not
only is it easy to work with and inex-
pensive, it’s also compatible with the
chemicals used in a pool. Although
copper would have made a better con-
ductor of heat, it’s more difficult to
work with and more expensive.
Because I’m not rich, I chose PVC.
Tee fittings and shut-off valves sep-
arate the heater from the existing pool
plumbing on both the supply and
return lines (see Photo 2). The return
line from the collector has a one-way
valve before it’s connected back into
the main return line. The one-way
valve prevents water from choosing
the wrong path and the 5 lbs of back-
pressure required to open the valve
prevents thermal siphoning.
I used the same diameter pipe for
the supply and return lines as was
already used in the existing pool
plumbing. The best place to put the
collectors is a sunny location free
from shade. I have a flat roof, so for
me the choice was obvious, but a
patio cover will work well also. On
the roof, the supply and return pipes
are split in two, reduced, and attached
to the collectors (see Photo 3). The
collectors are two runs of 1
″
thin-wall
PVC pipe that are 750
′
long. Painted
with flat black exterior house paint,
the pipes lay on the roof out in the
open. More efficiency could be gained
by putting the pipes in a glass-covered
housing, but I kept it simple. The
1500
′
of pipe provides a large enough
surface area for good heating.
Depending on pool size and avail-
able space, you can use any number of
combinations for the collectors. There
are no custom nor hard-to-find pieces;
all of the piping can be purchased
from home improvement stores.
THE HARDWARE
A pair of National Semiconductor
LM75 sensors collects the tempera-
ture data and sends it over a two-wire
I
2
C interface to the controller. [1] I
used an analog sensor in earlier ver-
sions, but discovered that the LM75
provides a more stable solution than
sending an analog signal halfway
around the house picking up noise
from who knows what. I had used I
2
C
EEPROMS in the past but the LM75
posed a few unique challenges (at
least in this application). The follow-
ing explains some of what I learned.
The interface is robust as long as
you obey the rules. The unit worked
fine on the bench, but when I hooked
it up for real, it was totally unreliable.
It gave false readings about a third of
the time. The problem was that I had
exceeded the 400 pf specified on the
SCL and SDA lines (40
′
of cheap four-
conductor wire sure makes a great
capacitor!). Looking at the signal on a
scope revealed an ugly saw tooth
instead of a clean square wave; I won-
dered how it worked at all. Practical
communication over I
2
C is limited to
only a few meters. Clearly I had
stretched beyond the design limits of
the specification. [2]
After changing the pull-up resistors
from 3.3 to 1 k
Ω
, changing to flat
eight conductor wire, and putting the
signals on the outermost wires, capac-
itance was no longer an issue and reli-
able operation was restored. Keep in
mind, there is an I
2
C buffer chip avail-
able from Philips that can easily
extend the reliable range to over a
1000
′
! If extra long runs are required,
the buffer is the way to go.
Photo 2—
Check out
the modified pump plumbing com-
plete with weeds and gravel.
Figure 1—
With all the built-in features of the PIC, the schematic is simple.
Photo 3—
The collectors are the lungs of this project.
Yes, that’s 1500
′
of PVC pipe.
was the case with my device, and it
did cause interference. Rule no. 1:
Don’t upset the family or they won’t
let you play. To minimize any radiat-
ed EMI effects, I read only the LM75s
once every 3 s. I could have used
shielded cable but that would have
meant another trip to the store and
roof. It was easier to fix the code.
The product ID of an LM75 is
1001xxxx. The next three bits make
up the device address of 000–111 with
the last bit representing the read and
write direction. I wired the swimming
pool and collector for addresses 0x92
and 0x94, respectively.
It took several attempts to make a
watertight package out of the LM75’s
S08 package. In the end, I mounted
the sensor inside a discarded IC tube
and the collector sensor inside a
threaded PVC pipe (see Photo 4). Both
are sealed with RTV on both ends.
The PIC16F873 made a good choice
for mission control. I could have used
other PICs, but the built-in I
2
C hard-
ware was a plus that simplified the
interface greatly, and I had no desire
During powerup, the LM75 expects
an initialization word. If no initializa-
tion is sent, the first read request is
swallowed by the LM75 and the
defaults are used. Because I’m using
the LM75 in its default condition, I
just send two reads during powerup
and it’s happy. Other modes include
Alarm Pin and Shutdown.
The communication speed for the
LM75 is 100 kHz. Constantly reading
the I
2
C port with the wires strung too
close to the TV antenna could cause
interference on weak stations. This
Photo 4—
The roof sensor for the pool heater is
mounted inside a sprinkler pipe.
to bit bang I
2
C. The built-in EEPROM
gives room to store all set points with
room to spare for future expansion.
This PIC also implements a two-
wire debug port that makes program-
ming and debugging a cinch (more on
this later). The device has 192 bytes
of RAM, 4 KB of ROM, and 128 bytes
of EEPROM. If I run short, I can
upgrade with the ’16F876, a part that
doubles the ROM and EEPROM and
nearly doubles the RAM but is other-
wise identical. But, everything fit into
the ’16F873 with resources to spare,
including several analog I/O pins that
I use for general-purpose I/O.
The ’16Fxxx series is more costly
than the nearest ’16Cxxx counterpart,
but the flash memory parts allow me
to change my mind without buying
the part again, so the ’16Fxxx parts
were actually cheaper in my case.
For the display, I picked out a 2 ×
16 LCD with the standard parallel
interface Hitachi 44780. I was going
to use a 4 × 20 LCD but the lower
cost of the former on the surplus mar-
ket was too good to pass up. I used a
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
59
Listing 1—
A 1-ms tick counter is used for task delay decrementing and counting seconds.
clock_isr()
{
static int i = 0;
static long ms = 1000;
if(--msTicker==0)
// have we hit a milisecond?
{
if(--ms==0)
// have we hit a second?
{
ms=1000;
// reload milisecond timer
if( pumpOnTimer != 0 )
// decrement pump timer
{
--pumpOnTimer;
}
if( idleTimer != 0 )
// decrement idle timer
{
--idleTimer;
}
else
{
currentMode = IDLE;
// timeout, return to idle mode
}
}
// task delay decrement
for ( i=0; i<TASK_END; ++i)
{
if(taskDelay[i] != TASK_DISABLE) // is task enabled?
{
if(taskDelay[i] != 0)
// is it ready to run?
{
taskDelay[i]--;// not ready yet, decrement delay count
}
}
}
msTicker = MS_TICK_RELOAD;
}
}
device with built-in backlight for bet-
ter contrast and nighttime visibility.
The tough part about using an LCD
is getting the timing right during ini-
tialization. There are several steps
that must be followed in sequence.
LCDs tend to be slow, so the usual
procedure is to check the busy bit
before sending data. During initializa-
tion, when the devices are particular-
ly slow, the busy bit is not valid so a
hard delay count must be used.
After initialization, an LCD can be
thought of and treated as really slow
SRAM. During initialization, I set the
LCD for Nibble mode, saving I/O
lines at the expense of a few more
lines of code. The Hitachi 44780 pro-
vides 80 bytes of display space regard-
less of the display size. Even on a 2 ×
16 display, all 80 bytes are viewable
(not simultaneously). Because I wrote
the LCD routines for a 4 × 20 display
originally, my
gotoxy function handles
up to 4 × 20 direct addressing and
does fine with smaller displays.
The input side of the user interface
uses momentary contact switches. I
disables the task. All task delay val-
ues that are enabled but not ready to
run are decremented at 1-ms intervals
by the clock ISR.
In main, you find the highest priori-
ty task ready to run and run it. The
priority of tasks is defined by their
position in the enumerated list. A
word of caution: If a higher priority
task has a zero or near-zero delay
time, the lower priority tasks may
rarely, if ever, run. This can be avoid-
ed with careful planning.
The task delay implementations
look more like state machines than
task delays, but they work well and
use little resources. In tasks with
up a few partial solutions. I decided to
make my own and give the world yet
another partial solution. I call it PIC
kernel wanna-be (PKWB).
Because of stack space limitations,
this is a non-preemptive, non-reen-
trant kernel that is short of features.
At the present time, the kernel’s only
features are priority-based task sched-
uling and an odd-looking task delay
that allows other tasks to use other-
wise wasted delay time.
I start with an enumerated task list
and make an array of this type called
task delay (
TASK_END). A task delay
value of 0x00 indicates the task is
ready to run and a value of 0xFFFF
60
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
almost went with a 16-key matrix
keypad but reverted to simplicity. By
using menus I was able to get the key
count down to three. The Mode
switch cycles the display between
several modes, each one using an up
and down pair of keys to modify val-
ues as seen in Table 1. A time-out
reverts the display to Idle mode if a
keystroke hasn’t occurred for more
than 2 min. The switches use the
“change on port B” interrupt, but the
actual debounce is handled outside of
the interrupt routine so as not to hog
processor time (see Figure 1).
DEVELOPMENT TOOLS
The choice of development tools
had a direct effect on the design. I
needed something simple and inex-
pensive yet functional. The MPLAB
assembler was free online and the in-
circuit debugger cost about $150. Both
are available from Microchip and
work on a number of chips in the
family. The MPLAB environment has
a near seamless interface to outside
compilers, making integration simple.
Custom Computer Services makes
several versions of its C compiler for
various PIC processors. The full-
blown compiler from CCS has a GUI
and more, but was unnecessary for
this project. I went with CCS’s PCW
product, a $100 command line com-
piler. I was impressed with the
assembler, compiler, and in-circuit
debugger that play nice together all
for about $250. The tool set available
for the PIC family is one reason why I
chose it rather than the 8051 family.
The CCS compiler does have limita-
tions, for instance pointers to func-
tions aren’t available but I worked
around it using a switch. Overall the
compiler exceeded my expectations.
THE FIRMWARE
I could have done the standard
while loop but I was looking for a
challenge. Having used real-time ker-
nels (RTOSs) in other projects of simi-
lar size, I knew I wanted one for this
application. As anyone who has
worked with the PIC family knows,
stack space is nonexistent. This non-
feature makes an RTOS impractical.
A quick look on the Internet turned
From main
// void readKeypad(void)
// reads and debounces the keypad
// No auto increment here. The key must be released and
repressed to increment again
// This function is driven by the keyHit_isr.
//
void readKeypad(void)
{
static int reentryCode=0;
static byte value = 0;
switch( reentryCode )
{
case 0:
value = portB;//.keypad;
// read the keypad
reentryCode = 1;
taskDelay[TASK_READ_KEYPAD] = 20; // 20ms delay
break;
case 1:
value |= portB;//.keypad;
// read it again
reentryCode = 2;
taskDelay[TASK_READ_KEYPAD] = 20; // 20ms delay
break;
case 2:
value |= portB;//.keypad;
// read it again
value = ~value;
// invert polarity of
switches
value = value >> 5;
// get rid of non-key
pad bits
keypadValue = value;
// update the global
value
idleTimer = 120;
// reset display back
to idle mode in 2 min-
utes
displayChange = TRUE;
reentryCode = 0;
// setup for next time
taskDelay[TASK_READ_KEYPAD] = TASK_DISABLE;
break;
default:
reentryCode = 0;
taskDelay[TASK_READ_KEYPAD] = TASK_DISABLE;
break;
}
}
Listing 2—
This helps me decide what to do next.
there are separate tasks for updating
the display, decoding the switch data,
and deciding when to run the pump.
Memory constraint is the only limita-
tion on how many tasks can be imple-
mented. I use five tasks with little
effect on code space.
With little modification, the hard-
ware and software easily could sup-
port a number of different applica-
tions. If I really want to get creative, I
can turn this thing into an Internet
appliance and monitor my pool tem-
perature from work!
As I conclude writing this article in
April, the pool is a comfortable 82°. I
think I’ll take a swim.
I
delays, all working values must be
static, because the task will exit
before being done and the values will
not be saved on the stack. The entire
task is broken up in a switch with a
reentry (not reentrant) code as the
switch. To delay a task, the code is
set to where the task will continue.
The task delay number is then set and
a break gets you out of the task.
Upon reentry into the function,
execution continues where it left off.
A reentry code of zero is set when the
task is complete. The implementation
is unorthodox but it works and is effi-
cient (see Listings 1–3).
The highest priority task reads the
switches after an interrupt enables
the task. The task is then disabled
until the next interrupt. Additionally,
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
61
SOURCES
C compiler
Custom Computer Services, Inc.
(CCS)
(262) 797-0455
www.ccsinfo.com
PIC16F873
Microchip Technology Inc.
(480) 786-7200
www.microchip.com/14010/helper.
htm
LM75
National Semiconductor Corp.
(408) 721-5000
www.national.com
SOFTWARE
The source code is available on
Circuit Cellar
REFERENCES
[1] National Semiconductor Corp.,
“LM75—Digital Temperature
Sensor and Thermal Watchdog
with Two-Wire Interface,” April
2001.
[2] Philips Semiconductors, “The
I
2
C-bus and how to use it (includ-
ing specifications),” April 1995.
Listing 3—
Check out one of several tasks to be done. Note the resemblance to a state machine.
while(1)
{
/* find the highest priority task ready to run */
for (tasks=0;tasks<TASK_END;++tasks)
{
if(taskDelay[tasks] == 0)
{
taskToRunNext = tasks; // task will run next
taskDelay[tasks] = TASK_DISABLE; // disable further
calls
break;
}
}
// run the highest task that is ready
// CCS does not allow pointers to
functions so we do it this way
switch(taskToRunNext)
{
case TASK_READ_KEYPAD: readKeypad(); break;
case TASK_PUMP_CONTROL: CheckPumpCondition(); break;
case TASK_READ_TEMP: updateTemperatures(); break;
case TASK_UPDATE_DISPLAY: updateDisplay(); break;
case TASK_PROCESS_KEYPAD: updateKeypad(); break;
case TASK_BEGIN_MULTITASKING: StartMultiTasking();break;
default: break;
}
taskToRunNext = NO_TASK; // clear so task won't rerun
};
RESOURCE
J. Labrosse, Micro C/OS-II: The Real
Time Kernel
, R&D Books, Gilroy,
CA, October 1998.
Loren Hunt is a firmware engineer at
Torrey Pines Research. He has more
Mode
Up
Down
Description
Idle
NA
NA
Display temperature and run time
Start
Start ++
Start – –
The collectors must be hotter than this setting to run
Difference
Difference ++
Difference – –
The collectors must be hotter than the pool plus this setting to run
Motor Run Time
Run time += 10 s
Run time –= 10 s
How long the motor runs after run condition expires
Hot
Hot ++
Hot – –
The system will shut down when hotter than this
Override
Circular list ++
Circular list – –
Cycles through normal, force on, force off
Memory
Store to EEPROM
Retrieve from EEPROM
Stores or retrieves all values from memory
Table 1—
Here’s your road map for the three buttons.
than 15 years of experience in various
aspects of embedded engineering,
including programming in C and
assembly, mixed-signal circuit
design, and board layout. He enjoys
both analog and digital electronics
and, as an active radio amateur (call
sign KG6FWP), spends spare time tin-
kering with homemade transceivers.
You may reach him at lhunt@tpr.com.
62
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
ne of my test
CDs features a nar-
rator reading a lengthy
text while switching
among 18 high-quality studio micro-
phones. The results tell you clearly
that any possible difference between
zip cord and Monster Cable in your
speakers is lost in the sauce.
Because I’ll be exploring communi-
cations circuitry in future columns, I
thought I should review the most
basic input device in common use:
the microphone. In this day and age,
this means an electret microphone.
Along the way, I’ll look at some
issues in practical applications.
Rest assured, you will not find the
ultimate secret of high-fidelity repro-
duction revealed in this article!
ELECTRET BASICS
The capacitance of an ordinary
capacitor is given by:
[1]
The capacitance, C, is in picofarads,
the plates’ area, A, is in centimeters
squared, their spacing, d, is in cen-
timeters, and n is the number of
plates. K, the dielectric constant,
depends on the insulating material
and equals 1 for vacuum, 1.0006 for
air, and 80 for titanium dioxide.
Because capacitance is inversely
proportional to plate spacing, a capac-
itor also operates as a distance meas-
urement device. The external voltage
varies directly with plate movement,
assuming a constant charge. If you
build one plate from a thin membrane
that moves with air pressure changes,
you have a microphone.
Detecting the resulting minuscule
capacitance changes against a high
DC bias voltage, however, poses a for-
midable challenge. If you want a rea-
sonably flat response across the entire
audio bandwidth, you suddenly find
yourself working with extremely high
impedances and breathtakingly low
noise specifications.
Fortunately, electret mics sidestep
those issues (at least for those of us
who are using them rather than
designing them) by eliminating the
high bias voltage and incorporating a
low-noise preamplifier into the mic
capsule. Photo 1 shows a variety of
bare electret mic elements from my
parts collection. The smallest ones
are about 6 mm in diameter.
A special dielectric in an electret
mic includes a trapped charge that
imposes about 100 V/mm across the
air gap. And, the electret material
supports the rear plate with the mem-
brane grounded to the case as an elec-
trostatic shield.
Some capsules feature a noise can-
celling design to reduce the output
from ambient noise. Small openings
in the rear of the capsule equalize the
pressure on the membrane as a result
of sounds from the side of the mic.
This is relatively effective for low fre-
quencies, but it isn’t a solution for
high-noise environments.
An external DC voltage powers the
preamplifier, usually a FET, which
transforms the capacitor’s extremely
high output impedance down to
something more convenient for the
external world.
WIRING IT UP
Common electret mics have a two-
wire connection that provides power,
signal, and ground. Because both the
It’s all about commu-
nication. Despite their
mode of travel, Ed
designed a way to
remain in contact with
fellow bicyclists while
on the move. This
month, he’ll explain
how he uses an elec-
tret microphone
hooked into his hel-
met to chat with
cycling companions.
Ed Nisley
Mic Check
o
A Communication System for Cyclists
ABOVE THE
GROUND
PLANE
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
63
power input and signal output share a
single wire, you must provide circuit-
ry that separates the two. A resistor
and capacitor often serve this purpose,
but there are complications.
Figure 1 shows the simplest case.
The DC power supply current flows
through R1 to the electret mic while
the signal current produces an AC
voltage at R1’s lower end. Capacitor
C1 blocks the DC power supply and
passes the AC signal to your circuit.
Mic datasheets list the maximum
supply voltage, standard operating
voltage, typical DC supply current,
and a recommended resistor value.
You may vary the resistor to meet the
needs of your design, but you may not
operate the element beyond its rat-
ings. Not for very long, anyway!
The DC current drawn by the mic
causes a familiar IR voltage drop
across R1. The remaining voltage
must be greater than the micro-
phone’s minimum specification.
Ideally, you will choose the power
supply voltage to operate the mic at
its standard voltage, given the typical
current required to run it.
The mics shown in Photo 1 draw
anywhere from 100 to 750 µA across a
supply range of 3 to 9 V. The typical
R1 value is 2.2 k
Ω
, for a drop of about
1 V. The standard voltage depends on
the mic, of course, but newer mics
sport ratings down to 1.5 V. The max-
imum, however, can be as little as
9 V, which means that you cannot run
some mics from a 12-V supply.
The simplest circuit model for an
electret mic includes a DC current
sink plus a small AC current source
in parallel. The DC sink represents
the preamplifier’s operating current of
a few hundred microamps. The AC
source provides the mic’s audio out-
put of a few tens of microamps. For
more detail, a parallel resistor can
account for non-infinite output
impedance or nonzero noise.
Because the mic’s output voltage
appears across a resistor tied to the
DC supply, supply noise looks like an
audio signal. If your application snug-
gles a mic up against digital circuitry,
pay attention to supply isolation and
grounding. You may want to run the
mic and perhaps the rest of the analog
circuitry from a separate DC
supply to filter out the
inevitable digital hash. That
can also solve the problem of
a supply voltage above the
mic’s maximum rating.
For special applications,
you can build more complex
circuitry to provide the prop-
er DC current with a higher
AC signal impedance. Note
that you must accommodate
any supply current variations
with temperature, so driving
the mic from a simple cur-
rent source won’t work.
On the output side, capacitor C1
must be large enough to pass the low-
est signal frequency of interest while
remaining small enough to prevent
audible thumps at turn-on. Equation 2
gives you the required minimum
capacitance, with f as the low-fre-
quency limit:
[2]
Assuming that the amplifier has a
sufficiently high input impedance, R
will be equal to the DC supply resis-
tor R1 shown in Figure 1.
With R equal to about 2 k
Ω
and a
low frequency cutoff of 100 Hz, C1
works out to just under 1 µF. This
may mean an electrolytic capacitor,
but which way does it go? Short
answer: it depends on your circuitry,
which isn’t shown in Figure 1.
Circuits with dual-supply op-amps
bias their inputs at 0 V, which makes
the bottom of R1 more positive than
the op-amp’s input pin. Here, connect
the positive terminal of C1 to R1.
Single-supply op-amp inputs, how-
ever, generally ride at half the supply
voltage, which can be roughly equal
to the mic’s operating voltage. For
low-voltage applications or if you’re
not biasing the op-amp at half the
supply, check the situation carefully.
With the basics in mind, let’s see
what else a real application requires.
CRANK THE GAIN
The circuit in Photo 2 connects an
electret mic to my ICOM Z1A hand-
held amateur radio. It also incorpo-
rates the earbud audio output and
push-to-talk control functions, so the
circuit in Figure 2 has a few more bits
and pieces than you might expect. In
addition, it must work in an RF-rich
environment because the Z1A trans-
mits 5 W in the 2-m or 70-cm band
through a nearby antenna when
you’re talking through the mic!
The specs for the Z1A’s external
mic signal assume a dynamic micro-
phone, which produces a higher audio
output at a lower impedance than an
electret element. Although the mic
jack includes a separate 3.3-VDC sup-
ply, you can’t simply wire up an elec-
tret mic as shown in Figure 1 and
expect to get decent results. An elec-
tret’s audio output is too low and its
impedance is too high. I’ve tried it; it
doesn’t work.
Unfortunately, you can’t simply
wire up an op-amp and get decent
results either, because RF on the mic
input overwhelms the few millivolts
of audio. At best, the audio sounds
distorted and, at worst, you don’t hear
anything at all.
The circuit in Figure 2 uses ferrite
beads on the mic and power leads, as
well as the amplified audio output to
the Z1A. These beads, often referred
to as “black magic,” act as a relative-
ly high resistance at RF frequencies
and form an effective filter when used
outboard of a low RF impedance.
The beads present essentially no
resistance or inductance to audio fre-
quency signals. Different materials or
ferrite mixes have different frequency
characteristics, so random surplus
beads may not work as well as you’d
Photo 1—
Electret mic capsules have a wide variety of sizes, con-
nectors, and specifications. The negative terminal is connected to
the capsule’s case, so the mics do not produce a differential output.
64
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
like. There is no simple way to
measure the response of a given
bead without RF test equipment,
and they bear no markings.
You’ve been warned.
Amidon FB-43-301 beads
(which are made with ferrite
material 43) look like 70-
Ω
resis-
tors at 150 MHz, where 100-pF
capacitors show 10
Ω
. That works
out to about 23 dB of attenuation
at the input and 18 dB at the out-
put of the amplifier.
If you build this circuit for use
with a 440-MHz radio, material
64 beads would provide higher
attenuation. For HF radios, which
operate below 30 MHz, material
73 or 77 beads are more appropriate.
Amateur radios transmit “commu-
nication grade” audio. The frequen-
cies of this audio range from approxi-
mately 300 to 3000 Hz. R4 and C3
form a simple low-pass filter that
rolls off the input above 5 kHz. C4
combines with the input resistor of
the MAX4175 to remove the DC bias
from the electret microphone and
rolls off the response below 300 Hz.
Although it’s certainly not hi-fi audio,
the result sounds about as good as the
Z1A’s internal microphone.
The Maxim MAX4175 op-amp
includes precision-trimmed gain and
bias resistors within its SOT-23 pack-
age, eliminating four external parts
and ensuring excellent matching. The
MAX4175AG I used has an inverting
voltage gain of two, with an
inverting input resistance of
about 150 k
Ω
. Include those
internal parts when designing the
rest of the circuitry; the MAX-
4175 isn’t just an ideal op-amp!
Maxim produces the MAX4175
in 27 different gains from 0.25 to
100, although only 11 are avail-
able in small quantities. If your
radio expects more audio oomph,
try the ’4175BA’s gain of 10. For
less output, the ’4175AD is a
unity-gain inverter.
You can, of course, use a stan-
dard op-amp with external resis-
tors. The venerable LM124A will
work from a 3.3-V supply, but
many other classic op-amps expect a
higher voltage. Also note the output
drive restrictions that apply to most
low-voltage, single-supply op-amps.
An automatic audio gain control
circuit inside the HT compensates for
most signal variations within its
range, so you must adjust the circuit’s
output by 10 dB (voltage gain of 3)
before you notice much difference. If
Photo 2—
The ICOM Z1A radio uses 3.5- and 2.5-mm plugs and I
decided to use a 6-pin mini-DIN plug for the helmet connections.
The 3.5-mm jack connects to the PTT switch through a molded
plug cable. And, a sponge filler immobilizes the ferrite beads and
toroid inside the aluminum case.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
65
you have the gain set too high, the
output received on another radio will
sound mushy and compressed. If it’s
too low, well, you’ll hear some faint
road noise with a tiny voice.
On the output side, R5 isolates the
op-amp from the capacitance of C9
and the shielded cable to the Z1A. It’s
not necessary to match the Z1A’s
input impedance because the maxi-
mum power transfer isn’t a concern.
The Z1A combines the push-to-talk
function with the audio signal, as do
many hand-held radios. Push-to-talk
turns on the radio transmitter when
you push a button. For the Z1A, con-
necting the audio signal to ground
through a 33-k
Ω
resistor does the
trick. The radio’s audio input has a
DC pull-up to 3.3 V, resulting in a
100-µA current through 33 k
Ω
.
I split that resistance between R6
and R7, then inserted C8 as a bypass
to prevent RF from entering the audio
signal through the PTT cable. A sim-
ple push button attached to the han-
dlebar under my left thumb triggers
the transmitter.
The Z1A’s external speaker output
can drive an 8-
Ω
earphone. If you use
a more common 32-
Ω
multimedia
earphone, you may need to install R1
and R2 to attenuate the volume to a
comfortable level. You must experi-
ment with your own radio and ear-
phones to get the right values.
When you’re done, you’ll have con-
venient radio communication while
talking on the local repeater or pro-
viding bicycle-mobile amateur radio
support for public service events.
Build two so you can chat with a
friend without shouting, greatly
improving relations on long rides.
It’ll work with FRS radios, too. But
amateur radio gives you more folks to
chat with and provides more opportu-
nity for analog and RF tinkering.
CONTACT RELEASE
For the electrical design of this cir-
cuit, you may benefit from a few tips
and tricks because this is my third or
fourth generation of mic amps. Roll
up your sleeves, put on that magnifier
headband, and try it out!
You probably already know any
component that can shake loose will
shake loose at the most inopportune
moment, and you have no idea how
much vibration a bike produces. Even
a lightweight box in a padded carrier
gets rattled around enough to crack
solder joints.
I used a similar circuit with a forest
of 0.25-W resistors standing on perf-
board around an LM324A for many
years. This circuit method worked,
but a joint or two came loose every
year. I think the surface-mount design
will survive longer.
+Bias
Com
Electret mic
R1
C1
Figure 1—
R1’s value trades signal amplitude off
against operating voltage, and the capacitor passes
the signal and blocks the DC supply.
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
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
67
Dust and grit create problems, par-
ticularly in connectors. Most amateur
radios use 3.5- and 2.5-mm phone
plugs for external speaker and mic
connections, which provide a direct
path for airborne crud. I used 6-pin
mini-DIN connectors between the
helmet and amp, the same connector
as on the end of a PS/2 keyboard
cable. An inch of heat-shrink tubing
around the joint seals out dust.
I use earphone cable for the helmet
connection by replacing the usual
3.5-mm stereo plug with the mini-
DIN connector, one earbud with the
electret mic, and the other with an
8-
Ω
earbud. The mic mounts easily on
a length of 12-AWG electrical wire
and the package is taped to my helmet.
The cable is fragile and the mini-
DIN connector has a straight-line fric-
tion fit, so the helmet wiring will
break or disconnect easily in an acci-
dent. (Mind you, I haven’t actually
tried that out.)
I know the risks of DWY (driving
while yakking). Because I can’t hear
the earphone audio in traffic, can’t
talk while pedalling uphill, and really
enjoy zipping downhill, most of my
yakking occurs on flat, rural roads.
I should mention that I’m just a
member of the Institute of Electrical
and Electronics Engineers; I neither
work for nor represent them. Their e-
mail forwarding service simply pro-
vides IEEE members with a stable
public address.
I
SOURCES
FB-43-301 Ferrite beads
Amidon, Inc.
(800) 377-3244
Fax: (714) 547-4433
www.amidoncorp.com
MAX4175AG
Maxim Integrated Products
(408) 737-7600
Fax: (408) 737-7194
www.maxim-ic.com
Electret microphones
Panasonic
(770) 338-6000
Fax: (770) 338-6001
www.panasonic.com
LAB-1 enclosure
Sescom, Inc.
(800) 634-3457
Fax: (785) 883-4422
www.sescom.com
Figure 2—
The amplified audio signal must be AC-coupled to the radio through C7, because DC current to common through R6, R7, and the push-to-talk switch turns on the
transmitter. The MAX4175 has internal gain and bias resistors, so you must pick the correct part for your application. I used the AG part with a voltage gain of two.
Ed Nisley is an electrical engineer. In
addition, he is a ham radio hobbyist
(call sign KE4ZNU). You may reach
him at ed.nisley@ieee.org.
SOFTWARE
The board, schematic, and EWB
files are available on Circuit
Cellar
RESOURCES
S. Harris, C. Sanchez, “Personal
Computer Audio Quality Measure-
ments,” www.cirrus.com/design/
products/papers/meas/meas.cfm.
Track 5 test CD, Sterophile,
www.stereophile.com/showarchives.
cgi?176.
Datasheets and circuits, Panasonic,
www.panasonic.com/industrial_
oem/electronic_components/rec_
mic.htm.
Datasheets and samples, Maxim
Integrated Products, www.maxim-
ic.com.
68
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
admire people of
the multi-language
persuasion. Although
I, like most, took classes
in an alternate language, today I speak
only English. The old adage, “If you
don’t use it, you lose it,” seems to be
true, at least with respect to linguis-
tics. In the computer world things
aren’t much different. However, I’d
much rather spend my time learning
a new processor as opposed to, say,
Chinese. No offense intended here.
Attempting to learn the language of
any non-English speaking ethnic
group would be equally tedious to me.
When I think of microprocessors,
Texas Instruments does not come to
mind. When I think of TI, I think of
DSPs and analog. So, when I saw a TI
ad touting “lowest-power flash
MCUs,” I was surprised to say the
least. Although I’ve been saying “big-
ger isn’t always better” for years, I
thought no one was listening.
One of the first things I look at
when I investigate a new processor is
the availability of low-cost develop-
ment tools. I’m more likely to get
serious about a product that has this
level of support. TI’s MSP430 series of
processors are available in some high
pin count OTP packages. Although
these may be fine for larger projects
after you have the basics under your
belt, I generally shy away from proto-
typing with OTP SMT devices. With
flash memory devices, a stupid coding
mistake doesn’t make the device (or a
PCB) a candidate for the trash.
Presently, TI has some of the small-
er (20-pin) MSP430 devices available
using flash memory technology. In
addition, a flash memory emulation
tool (~$50) can be purchased for these
inexpensive devices (~$2). Do these
numbers catch your attention?
MSP430F1121
I don’t want to rehash Tom
Cantrell’s excellent introduction of
TI’s MSP430 devices in “Sweet
Sixteen” (Circuit Cellar 126), so I’ll
refer you to his Silicon Update col-
umn for the specifics. However, let’s
review a few of the high points. With
4 KB of flash memory and 256 bytes
of RAM, this isn’t a minimalist low-
end chunk of silicon. Just take a look
at Figure 1 to see the rest of the
F1121’s internal organs. This 16-bit
CPU was designed for battery use
with a low-voltage requirement of 1.8
to 3.6 V and a nominal current con-
sumption of < 1 mA at 8 MHz. The
use of slower clock speeds and/or low
power modes can reduce that intake
significantly (to microamps).
One of the most significant per-
formance benefits is the ability to
wake up from standby in only 6 µs
when using the internal digitally con-
trolled oscillator (DCO). Although the
DCOCLK is sensitive to both voltage
and temperature, it is great for those
minimum component applications
where the actual operating frequency
doesn’t need to be dead nuts. The
standard external crystal and oscilla-
tor inputs also can be used when an
accurate time base is necessary. In
fact, you can switch between time
bases through software.
COMPARATIVELY SPEAKING
I want to narrow the focus of this
article. Many applications for a micro
require monitoring some kind of sen-
sor. Because most sensors are analog
(more than just a switch closure),
there is an advantage to using a micro
Jeff Bachiochi
MSP430 News Flash
Recognizing the Flexibility of
Reprogramming
i
FROM THE
BENCH
When
you
think of
micro-
proces-
sors,
does TI come to
mind? If you’re open
to learning something
new, you can start
experimenting with
TI’s power flash
MCUs this month.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
69
with an ADC. You may have noticed
in Figure 1 that the ’F1121 doesn’t
have an actual ADC. How can the
comparator peripheral be used for
measuring sensor input?
Figure 2 is a block diagram of the
comparator and supporting circuitry
available on the ’F1121. Two 8-bit reg-
isters are used to configure the com-
parator. CAON (CATL1.3) enables
power to the comparator. This will
add ~30 µA to the current require-
ment of the micro.
The positive and negative inputs to
the comparator can be connected to
either an external pin or internal ref-
erence voltage. P2CA0 (CACTL2.2)
connects or isolates external pin P2.3,
and P2CA1 (CACTL2.3) connects or
isolates external pin P2.4 to and from
intermediate comparator connections.
CARSEL (CACTL1.6) can apply an
internal voltage to either of the inter-
mediate comparator connections.
These intermediate connections are
routed to the comparator inputs by
CAEX (CACTL1.7). This bit connects
the intermediate signals CA0 to the
positive input and CA1 to the nega-
tive input or reverses the connections.
This bit essentially swaps the inputs.
In addition, the comparator’s output
is inverted by CAEX. When CAEX =
0, CAOUT = 1 and the positive input
is greater than the negative input.
When CAEX = 1, CAOUT = 1 and the
negative input is greater than the pos-
itive input. I’ll cover this in greater
detail later in the article. Because the
comparator’s design is that of little
hysteresis, its output may swing wild-
ly as the two inputs approach the
same potential. Bit CAF (CACTL1.1)
can apply a small LP filter (2-µs RC)
to reduce these oscillations.
The internal reference voltage is
selected via bits CAREF0 (CACTL1.4)
and CAREF1 (CACTL1.5). There are
four selections—none, relative
0.5 V
CC
, relative 0.25 V
CC
, and an
absolute (but temperature-sensitive)
voltage source of ~0.55 V.
Typically, to reduce pin count, ana-
log inputs are multiplexed with digi-
tal inputs as alternate functions.
Input circuitry for digital signals is
designed to keep signals at logic levels
and current to a minimum. As a
result, this method doesn’t work well
for analog inputs. The solution is to
allow the CMOS buffer circuitry to be
disabled to reduce current consump-
tion on inputs where the signal is
something other than logic levels.
Register CAPD contains a control bit
for each port input (CAPD.0 through
CAPD.7). Note that any bit position
with a one disables the input buffer
for that input pin.
There are a couple of points worth
mentioning about the comparator
inputs. First, it is possible to config-
ure the comparator with inputs left
unconnected to either an input pin or
reference source. This will surely give
you unpredictable results. Second, it
is also possible to have an internal
reference voltage present at an input.
This can be used as an external refer-
ence with a buffer to prevent loading.
+
–
CAREF
0.5 x V
CC
0V
3 2
1 0
0
1
2
3
1
0
V
CAREF
CCI1B
CAOUT
Set CAIF0
P2.2/
CAOUT/TA0
f=2.0µs
CAF
0
1
Low-pass
filter
1
0V
CARSEL
P2CA0
0
CA0
0
1
0
1
CA1
0V
1
0
1
P2.3/
CAD0/TA1
P2.4/
CA10/TA2
P2CA1
CAEX
0V
0 1
V
CC
CAON
0
1
0V
0.25 x V
CC
CAON
0
Oscillator
system clock
1K + 128
or
4K + 256
flash
128- or
256-byte
RAM
Power on
reset
I/O Port P1
8 I/Os, all with
interrupt
capability
I/O Port P2
6 I/Os, all with
interrupt
capability
Timer_A
3 CC
register
CCR0/1/2
x = 0, 1, 2
Test
JTAG
CPU
including
16
registers
Watchdog
timer
15 or
16 bit
Bus
converter
P2.0/ACLK
P2.1/INCLK
P2.2/TAO
P2.5/R
osc
P2.4/TA2
P2.3/TA1
Outx
CCIxA
TACLK
SMCLK
JTAG
X
IN
X
OUT
MCLK
R
osc
ACLK
SMCLK
TEST
MAB, 16-bit
MDB, 16-bit
TACLK or
INCLK
Outx
CCIxA
CCIxB
ACLK
SMCLK
INCLK
Out0
CCI1B
ACLK
DCOR
MAB, 4-bit
MCB
MDB, 8-bit
*RST/NMI
P1.0-7
V
CC
V
SS
Figure 1—
The 16-bit RISC core of the MSP430F1121 has a cycle time equal to MCLK. It boasts low-voltage oper-
ation, low current consumption, fast wake up from sleep, OTP/flash memory devices, and JTAG interface.
Figure 2—
This block diagram shows the flexibility of the comparator’s configuration.
70
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
BATTERY MONITOR
Because the MSP430 devices are
designed for battery operation, it
makes sense that you want to pay
attention to the battery voltage and
indicate when the battery needs
replacing. This is the simplest opera-
tion for the onboard comparator.
Configure a connection between the
internal voltage reference and the
comparator’s negative input. Connect
the comparator’s positive input to
external pin P2.3. Externally add a
simple resistive voltage divider from
V
CC
to P2.3 to ground. Size the resis-
tors such that a minimum V
CC
will
apply a voltage less than the reference
voltage of 0.550 V. The comparator’s
output will change state as the sys-
tem V
CC
drops to the point where the
analog voltage on P2.3 is lower than
the internal reference voltage (doesn’t
change with V
CC
).
In this example, there are no
unknowns. Operation is predeter-
mined by the choice of external com-
ponents. We are interested only in the
fact that the analog input dropped
below a predetermined point. But
what happens when you want to
measure the exact voltage as opposed
to a relative one?
DYNAMIC INPUTS
I think of an ADC as a device hav-
ing some internal circuitry where a
reference is adjustable so multiple
comparisons can be made to an
unknown input. (The successive
approximation converter is only one
variety of ADC, albeit possibly the
most well-known.) This process of
zeroing in on a value equal to that of
the unknown input takes time. If the
reference is infinitely adjustable, then
the number of comparisons (amount
of time you can spend doing the com-
parisons) is related to how close you
can come to the actual value (bits of
resolution). One comparison can
determine whether the input is above
or below half of a reference. Two com-
parisons can narrow that value again
by half, and so forth.
Another way of thinking about it
might be to imagine the reference as
an incremental potentiometer (the
number of increments, x, resolution,
is usually a power of 2). Crank that
puppy from zero to V
REF
until the
comparator switches state and then
read off the incremental decoder for a
digital value of the unknown input.
This process can be simulated using a
timer/counter and a charging and dis-
charging capacitor, which makes it
closer to another style of ADC, the
dual slope converter.
RC TO THE RESCUE
Use a single analog input and a sin-
gle digital input to set up the circuit
displayed in Figure 3. Choose values
for the RC components such that
their time constant, R*C, is less than
the time it takes for the micro’s timer
to roll over. For instance, the DCO
can be bumped up to ~3 MHz from
the default of ~750 kHz. The 16-bit
timer will roll over after counting
65536 ticks of the 3-MHz clock.
That’s ~20 ms. A 10-k
Ω
resistor and a
1-µF capacitor has a time constant of
~10 ms. This is less than the timer
overflow time so you won’t need to
worry about the timer overflowing.
The digital bit is used to either
apply V
CC
to the resistor (to charge the
capacitor) or ground the resistor (to
discharge the capacitor). This can be
done under program control. Software
is written to set the digital output bit
high for five time constants (tc) to
assure a full charge (>99%). When the
digital output is switched to ground,
the timer is cleared and enabled.
Because the negative input of the
comparator is configured with a rela-
tive internal voltage of 0.25 × V
CC
, the
comparator changes states with the
discharging capacitor. At change of
state, the timer is read. The count is
the reference count and can be equat-
ed to the reference resistor’s value. In
simplest terms, if the timer has
10,000 counts and the reference is a
10-k
Ω
resistor, then one count = 1
Ω
.
If you use a resistive sensor, make
sure your reference resistor’s value is
higher than the sensor’s highest value.
If using a capacitive sensor, make sure
the reference capacitor value is small-
er than the smallest value of your
sensor. To improve result accuracy,
use a close tolerance reference device
(<1%), as all calculations are based on
this known value. This will be more
of a problem when selecting a refer-
ence capacitor, because finding one
with <5% tolerance may be difficult.
Figure 4—
Adding a second resistive element (in this
case, a resistive sensor) allows the micro to compare
how each R interacts with the C. The R not being test-
ed must be removed from the circuit by setting its con-
trol pin as a high-impedance input.
Figure 5—
When adding a capacitive sensor, the R
and C change position. In this case the reference C
value is the close tolerance device, as the R will can-
cel out of each equation.
Figure 3—
Analog input (P2.3) monitors the charging
of RC when P2.0 is set to logic 1 (V
CC
) and the dis-
charging of RC when P2.0 is set to logic 0 (Gnd).
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
71
Now that you have a baseline refer-
ence where a count is equal to so
many ohms of a reference, you need a
way of comparing this to a sensor. See
Figures 4 and 5 for examples of how a
resistive or capacitive sensor may be
connected to the original base design
from Figure 1. This is accomplished
by using an additional digital I/O pin.
Referring back to the reference cir-
cuit (see Figure 3), the digital I/O pin
was used to alternately apply V
CC
or
Gnd to one end of the reference resis-
tor to allow the reference capacitor to
alternately charge and discharge. To
allow multiple resistive (or capacitive)
sensors to the design, each digital I/O
pin must also take on another state.
Multiple sensors connected to V
CC
and Gnd will interfere with one
another by either being in parallel
with one another or forming a divider.
In addition to the two output states,
each pin must be able to be placed
into a high-impedance (input) state.
This action will essentially discon-
nect them from the circuit.
Now each component can be tested.
First, the reference device is connect-
ed and goes through a charge and dis-
charge cycle. The timer count forms a
reference value (counts/ohm). Next,
the sensor is connected and goes
through an identical charge and dis-
charge cycle. This time the discharge
time (timer count) will be somewhat
less (depending on the sensor’s value).
Because the reference discharge time
(R
REF
× C = COUNT
REF
) and sensor dis-
charge time (R
SEN
× C = COUNT
SEN
)
both use the same capacitor, the
capacitor’s value in both equations
cancels out and you have a direct rela-
tionship between R
REF
, R
SEN
, and the
timer counts:
[1]
Using the values from Figure 1, you
get:
[2]
If the COUNT
SEN
value is deter-
mined to be 5000, then
[3]
or
[4]
Actually, the discharge time is from
V
CC
down to 0.25 V
CC
, which is slight-
ly more than one time constant
(63.2%), but everything here is ratio-
metric. As long as V
CC
stays constant
for a complete cycle (reference and
sensor) and as long as the capacitor
used is stable for the same period,
these do not affect the result. Now,
you can see that two things are
important to the result, the actual
value of the known reference and the
maximum number of counts for the
reference discharge time.
Take a look at Photo 1 for a scope
shot of the signal at the RC junction
(comparator input) of the circuit from
Figure 4. The internal RCO was set to
~3 MHz and used as the system clock.
This clock was routed to P1.4 (alter-
nate I/O function of the pin) so I
could physically measure the clock
speed with a scope. This was a sanity
(or confidence) check. The specifica-
tions say 2.7 to 3.65 MHz and I meas-
ured 3.4 MHz. The flash memory
emulator allows breakpoints to be set.
After halting execution after each dis-
charge cycle, I was able to check the
timer counts for the reference and the
sensor. The reference count was
0B65Bh (46683). With a 0.1% refer-
Photo 1—
This scope shot shows the analog input
(P2.3) on the MSP430F1121 running on the flash
memory emulator. The executing program charges and
discharges a capacitor, first through the reference
resistor and then through a resistive sensor.
[10]
where
[11]
In both instances V
IN
can be
reduced with a resistor voltage divider
at the input if necessary to bring the
voltage at the input pin to within the
input specifications (use discharging
for V
CC
> V
IN
> 0.25 V
CC
, use charging
for 0.5 V
CC
> V
IN
> Gnd).
IT’S ONLY THE BEGINNING
With only this small taste of Texas
Instrument’s flash memory-based
mixed signal microprocessor, I hope
you’ll find it intriguing enough to
experiment with it in future battery-
based designs. If you keep this bit of
information handy (which can cer-
tainly be used with any processor
with an internal comparator), you
may be able to figure out how it is
part of a project that will “get up to
temp” after the introduction of one
more critical section.
Next month, I plan to talk about
talking back. If you’re like me, you
need to hear this.
I
72
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
ence of 10,000
Ω
, the counts/ohm is:
[5]
The sensor count was 5DC3
(2,4003). This means that the sensor
resistance is:
[6]
Referring back to Photo 1, notice
that the sensor’s discharge time is
about twice as long as the reference
discharge time (vertical measurement
bars showing ~10-ms discharge time).
E (OR I)
IN
To actually measure a voltage (or
current), the method is similar, how-
ever because you are not dealing with
full-time constants, the terms do not
cancel out. In this instance, I’ll be
comparing the discharge reference
time (V
CC
to 0.25 V
CC
) with the time it
takes the capacitor to discharge to the
unknown voltage (V
CC
to V
IN
). For
0.25 V
CC
< V
IN
< V
CC
, the formula
would be:
[7]
SOURCE
MSP430F1121
Texas Instruments Inc.
(800) 336-5236
Fax: (972) 995-4360
www.ti.com
where
[8]
In this equation, tm is the discharge
time of the unknown voltage (V
CC
to
V
IN
) in counts and tvcc is the dis-
charge time of the reference (V
CC
to
0.25 V
CC
) in counts.
If you used the same counts as in
the previous example (reference 46683
and sensor 24003), you’d have
[9]
V
IN
would discharge from V
CC
to V
IN
(1.42 V) in 24003 counts. Figure 6
shows an R × C discharge curve with
the x-axis in time constants (counts)
and the y-axis in volts.
If V
IN
can fall below 0.25 V
CC
, you’ll
need to use a charging cycle because
the discharge cycle is referenced from
V
CC
down to 0.25 V
CC
. Using the
charging cycle, the reference count is
the charge time from Gnd to 0.5 V
CC
.
The measurement cycle is the charge
time from Gnd to V
IN
. The formula
here is much the same as the dis-
charge cycle:
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@circuitcel-
lar.com.
RESOURCE
Texas Instruments, Inc., “Economic
Measurement Techniques with the
Comparator _A Module,”
SLAA071, October 1999.
Figure 6—
This typical logarithmic RC discharge cycle (five tcs) shows the reference RC discharging to 0.25 V
CC
and its associated timer count. The same reference RC is also shown discharging to V
IN
. Its timer count is used to
determine V
IN
(which is also shown here as ~1.4 V).
74
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
ears back in
May of 1993, I
wrote an article called
“Talking Chips” (Circuit
Cellar
34) describing the then emerg-
ing digital voice recorder ICs. Besides
offering a high-tech replacement for
the bulky, balky mechanical voice
recorders of yore, the innovation
spawned entirely novel applications,
such as greeting cards that speak your
own personally recorded message.
As you might guess, this month I’m
covering a chip that can listen.
There’s definitely the potential for
inspiring a lot of exciting and unique
applications, some of these are more
obvious than others.
I think voice recognition technolo-
gy has gotten a bad
reputation because it’s
stereotyped as a magic
bullet designed to sup-
posedly put that
inspired hack of the
typewriter age, the
crusty but lovable
QWERTY keyboard,
out of its misery.
Through the brute
force application of
MIPS and megahertz,
progress has been
made, but chips and software can’t
yet achieve the accuracy and speed
required for transcribing natural gab.
On reflection, replacing keyboards
may be one of those situations where
if it can be done, it will be done, and
then you’ll see if it should have been
done. As someone who types a lot, I
have a few observations.
First, when writing an article, typ-
ing is the least of my worries. The
real work is studying datasheets, fool-
ing with boards, trying experiments,
and so forth. The hardest of all is giv-
ing creative birth to the words I want
to say, not just typing them.
Even imagining a perfect voice
recognition system for my PC, I’m
not convinced. Try this experiment.
Think of a sentence or phrase and
then type it while saying it aloud. As
someone who can type at a decent
rate, I can key in the words at nearly
a normal speaking cadence. Only by
slurring the words together in a blur
does speaking demonstrate more top-
end throughput. The human brain
demonstrates its formidable skill by
being able to parse such frenetic blab-
ber, but it drives automated recogni-
tion systems nuts.
Besides, have you ever given a long
speech or talked vociferously at a
party for hours on end? It’s tiring. I
presume it wouldn’t be long before
folks would get up in arms over the
other CTS, carpal tonsil syndrome.
Overlooked in the dubious quest to
kill QWERTY is the fact that there
are less glamorous (but imminently
practical) voice recognition applica-
tions that do become feasible with
incremental advances in technology.
Besides such likely candidates as car
SILICON
UPDATE
Tom Cantrell
Listening Chips
y
Delving
into voice
recognition
and chips
that listen,
Tom takes a look at
the current state of
development. With
pioneer Sensory lead-
ing the way, he dis-
covers there’s poten-
tial for designing
unique applications.
Photo 1—
When it comes to voice recognition, the Voice Extreme Toolkit rep-
resents a new high in ease of use and, at only $129, a new low in price.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
75
phones, automated phone systems,
and toys, I can imagine a lot of handy
(make that no hands) products.
For example, when using a scope or
logic analyzer, I invariably end up
needing to punch a switch or twist a
dial even as both hands are frozen
probing the rat’s nest. It would be
great if I could just say, for example,
“External Trigger Channel 2” instead
of the more flowery phrases I find
myself using in that situation.
IN THE REALM OF THE SENSORY
Although it hasn’t reached house-
hold name status, in the relatively
new field of voice recognition,
Sensory can be considered one of the
pioneers. They’ve been around for
years, slowly but surely percolating
their technology into emerging appli-
cations one by one.
I’ve kept in touch with Sensory and
monitored their progress, but held
back on writing an article. The fact is,
with ASIC- and ROM-based custom
silicon underpinning a focus-accounts
marketing strategy, what they had to
offer was only suitable for a few big
outfits like Sony, VTech, and Uniden.
But now, after successfully establish-
ing their place, Sensory is moving to
expand the market with low-cost
standard chips suitable for a broad
range of applications from customers
big and small.
Enter the Voice Extreme Toolkit
(see Photo 1) which, at only $129, is
not only ideal for prototyping and
demos, but is also suitable for moder-
ate volume applications.
The kit is wrapped around a special
version of Sensory’s RSC-364 speech-
recognition chip. The ROM on the
chip is factory-programmed with a C-
like language interpreter and memory
manager designed to work with a
commodity external flash memory
chip. Note that a ROM-less version,
RSC-360, is available (see Table 1).
The external flash memory is used
to store an application’s particular
vocabulary, specifically the templates
and weights that lie at the heart of
Sensory’s recognition technology.
There are two sources for the vocabu-
lary, and the choice is determined by
the specifics of the application.
Listing 1—
This code demonstrates the VE C in action, running a demonstration of speaker-independent
recogni tion. The process boils down to pattern generation (
PatGenW
) and then recognition (
Recog
) with a
level of confidence (
GetRecogLevel1
).
//----------------------------------------------------------------
-
// OPERATION:
// After an initial BEEP the program loops forever, waiting for
// button presses.Press A for a full prompt, B for a short
//prompt.
// Respond to the prompt by saying one of the 6 possible words.
// The program tells you what word you said or announces an
//error.
//
// NOTES:
// The program is linked with both a SPEECH and a WEIGHTS data
//file.
// This program calls the PatGenW and Recog functions and checks
// their returns. It illustrates the use of the confidence level
// stored in the WEIGHTS file and special processing for NOTA (
// None Of The Above ) recognition.
//----------------------------------------------------------------
-
#include <ve.veh>
#include <speech\sidemo.veh>
#include <weights\si6.veh>
#define TalkTable VPsidemo3
main()
{
uint8 prompt;
uint8 code;
uint8 result;
BEEP;
while( 1 )
{
GreenOn; YellowOn;
// Get a key press, then decide which prompt to use
prompt = MSG_BEEP;
do
{
if ( ButtonAPressed )
{
prompt = MSG_LONG;
YellowOff;
}
else if ( ButtonBPressed )
{
prompt = MSG_SHORT;
GreenOff;
}
} while ( prompt == MSG_BEEP) ;
// Say the prompt, wait for a response and try to recognize it
Talk( prompt, &TalkTable );
RedOn;
result = PatGenW(0, &WTSI6);
RedOff;
if ( result )
{
BEEP; BEEP;
DebugH4( result ); // Announce error code, if any
}
else
{
result = Recog( &WTSI6 ); // Try to recognize response
if ( GetRecogLevel1() < CONFSI6 )
(Continued)
76
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
For speaker-independent applica-
tions, Sensory can draw from a library
of common words in the major lan-
guages or provide serv-
ice to generate a cus-
tom (i.e., atypical lan-
guage) vocabulary. By
contrast, speaker-
dependent apps rely on
training (i.e., writing
flash memory) by the
end user in the field.
An interesting tweak
of speaker-dependent
recognition is known
as speaker verification.
The latter is kind of
the inverse of the for-
mer. Instead of recog-
nizing a word from a
predefined vocabulary
spoken by a known
person, verification
recognizes which
speaker from a prede-
fined group is saying a
known word.
A specific applica-
tion might use a com-
bination of recognition
modes. For instance, a security sys-
tem could recognize a particular
user’s voice (speaker verification) and
then, knowing his identity, determine
his specific password (speaker-depend-
ent) before accepting generic com-
mands (speaker-independent).
Other Sensory variations on the
recognition theme include word spot-
ting and continuous listening. Word
spotting finds trigger words in contin-
uous speech, so “Please open the
door” could be recognized as “open
door.” To reduce false triggering com-
plications, use words with more sylla-
bles or include more than one word,
like a brief phrase.
Because there is a slight delay
between recognition of the first word
in a multi-word trigger and listening
for the following word, I recommend
that you try establishing a scheme
that uses trigger words that are natu-
rally separated by other speech or oth-
erwise won’t easily run together. Note
that word spotting only works with
speaker-dependent recognition.
Continuous listening is similar,
except that it waits for a specific iso-
lated phrase (i.e., only “open door”
would be recognized), with pauses
delineating each word. Although not
as powerful as word spotting, continu-
ous listening does have the advantage
of working with both
speaker-dependent and
independent recogni-
tion modes.
LIP READER
How does the chip
work its magic? The
secret advantage for
the RS-364 isn’t so
much what it does, but
the fact that it needs
only a middleweight
micro to do it (see
Figure 1). Of Sensory’s
own design, the 8-bit
core has a familiar yet
minimalist feel. Kind
of like the kid a ’51
and Z8 would have if
they got married.
The instruction set
seems decent, with 54
to choose from and a
clean RAM-based reg-
ister file (448-byte)
architecture. Sensory
AiFE1
AiFE2
AiN0
AiN1
Preamplifier
AOFE1
AOFE2
AOFE3
ADC
DAC
DAC
OUT
BUF
OUT
Analog
control
Pulse
width
modulator
PWM
Speed
processing
unit
Interr
upt logic
OSC1
Timer1
Timer2
OSC2
Po
rt
0
Po
rt
1
External
memory
interface
2K technology
SRAM
Register space
448 bytes
Stack space
8 levels
CPU
32K x 8
High
32K x 8
Low
Timing and
control
Breakpoint
register
P1.0–P1.7
P0.0–P0.7
XI2, XO2
XI1, XO1
–XMH
–XML
–RESET
–TE1/PWM
A[15:0]
D[7:0]
–RDC
–WRC
–RDD
–WRD
Internal ROM (RSC-364)
Figure 1—
Except for the speech processing unit, the ’36x looks exactly like any other mild-man-
nered 8-bit micro. The secret to being a good listener is in the Sensory software.
{
Talk(MSG_WHAT, &TalkTable); // Say "What did you say?"
DelayMilliSeconds(500);
}
else
{
if ( result != 6 ) // If not "None Of The Above"
Talk(2, &TalkTable); // say "you said"
switch (result)
{
case 0: Talk(MSG_CALL, &TalkTable);
break;
case 1: Talk(MSG_ERASE, &TalkTable);
break;
case 2: Talk(MSG_MODIFY, &TalkTable);
break;
case 3: Talk(MSG_PLAY, &TalkTable);
break;
case 4: Talk(MSG_RECORD, &TalkTable);
break;
case 5: Talk(MSG_SKIP, &TalkTable);
break;
case 6: Talk(MSG_WHAT, &TalkTable);
break;
}
}
}
}
}
Listing 1—
Continued.
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
77
claims performance of 4 MIPS at
14.432 MHz, which is probably push-
ing it. Most instructions take at least
five cycles, more if they encounter
wait states accessing external memo-
ry. Branches are fast at only three
cycles but use absolute addresses, so
position-independent code isn’t an
option. (Note that the Sensory linker
can relocate an
.OBJ file.) I was a little
bit surprised to see a limited eight-
level stack, which seems out of place
these days for what’s otherwise a
respectable mid-range micro.
Voice recognition requires all the
MIPS that possibly can be mustered at
14.432 MHz. However, during less
hectic times, the clock rate can be
reduced or even stopped because the
part is fully static.
If power consumption is a consider-
ation, an additional 32.768-kHz oscil-
lator can slow down things, and
there’s a programmable clock divider
and a Sleep mode. The ’364 can be
awoken from Sleep mode by an I/O
event or a timer.
Before you ask, be advised that the
chip doesn’t allow a voice input to
wake it up, so you’ll have to press a
button or rely on a timer interrupt,
which is probably just as well.
Imagine how you’d feel if you had to
snap to attention at every sound.
Make sure you keep in mind that dur-
ing voice processing, power consump-
tion is a prodigious 10 mA versus a
mere 5 µA while sleeping. The chip
does run on anything from 2.85 to
5.25 V, which should keep just about
everybody happy.
Two timer/counter channels, each
with 8-bit count and 8-bit reload reg-
isters, are provided. The clock sources
are fixed, with the first timer running
off the high-speed clock (14.432-MHz)
divided by 16 or 32, and the second
using the low-speed oscillator
(32.768-kHz) divided by 128 or 32,768,
the latter yielding a 1-s timebase.
Sixteen I/O lines are organized as
two 8-bit ports. Each line is individu-
ally programmable as an output or
input, the latter with either strong,
weak, or no pull-up options.
Voice arrives courtesy of a front-end
preamplifier with three stages (up to
500 gain overall) feeding a built-in
ADC. After the ADC comes automat-
ic gain control (AGC) and recognition-
specific support circuits. The manual
says little else about the A/D convert-
er because it’s expected to be dedicat-
ed to speech recognition tasks under
the control of Sensory software.
WALK THE TALK
Actually, perhaps the title of this
month’s article probably should be
“Talking & Listening Chips” because
the RSC-364 is equally adept at han-
dling audio recording and playback
including voice, music, and tone gen-
eration (for example, DTMF).
There are two choices for generat-
ing audio, each with its own trade-
offs. An onboard 10-bit D/A converter
is the logical candidate, but requires
an external audio amplifier. By con-
trast, a PWM option can drive a small
32-
Ω
speaker directly.
Although called PWM, the latter is
actually kind of a push-pull PCM
(pulse count modulation). Two out-
puts are connected to the speaker ter-
minals. When one is held low and the
other is pulsed, the speaker will push.
Reverse the pin functions and the
speaker pulls. More pulses equals
more amplitude (i.e., volume), with
the speaker mechanical inertia acting
as a low-pass filter. The frequency of
reversing the pin functions (push ver-
sus pull) controls the pitch. Clever
scheme, but the datasheet does cau-
tion you to be on the lookout for EMI
generated by all the high-frequency
square wave switching.
Besides recording your own audio
for playback, Sensory makes it easy to
import
.WAV files with the Quick
Synthesis tool as shown in Photo 2.
For convenience, three compression
options (uncompressed, 75% and
50%) are provided to allow you to
choose the trade-off between sound
quality and memory size.
SOFT SOUNDS
The ’364 strategy is to deliver a
credible solution for sub-QWERTY
applications at a practical price. Part
of the equation is the new Voice
Extreme IDE (see Photo 3), the long-
awaited upgrade to the earlier DOS-
based tools. It provides a modern and
friendly environment for developing
speech recognition applications.
Another intriguing aspect of VE is
the proprietary C-like programming
language included in the kit.
The bad news is that the VE version
of C is by no means standard, with
quite a few differences from standard
C. The good news is that, as a practi-
cal matter, you won’t be porting gobs
of existing code over to the ’364.
Remember, the chip needs to
devote a lot of attention to the recog-
nition task in order to deliver the best
possible results. Also, although it
seems like a lot, even the 2-MB exter-
nal flash memory chip can easily get
overrun with templates, weights,
music, and recordings, not to mention
your program.
So, do not try to port an RTOS, run
a web server, or stuff megabytes of
existing application code down the
’364’s throat. Variables are allocated
78
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
Description
RSC-300
RSC-364 (Custom mask)
capabilities
Speaker-independent (SI) recognition
✓
✓
Speaker-dependent (SD) recognition
✓
Limited
Speech synthesis and special sound effects
✓
✓
Speaker verification
✓
✓
Four-voice music generation
✓
Limited support
Voice record and playback
✓
Not supported
SI Recognition capacity
Maximum number of words per recognition set (3)
15
15
Total recognition vocabulary size in words, all sets
Unlimited
40 words
SD Recognition capacity
Maximum number of words per recognition set (3)
64
6/64
Total recognition vocabulary size in words, all sets
Unlimited
6/512
Speaker verification capacity
Number of speakers identified per set (3)
64
1/64
Synthesized speech capacity
Maximum total length of all messages
Unlimited
25 s
Music synthesis capacity
Number of simultaneous independent musical voices
4
4
Number of musical octaves available
2–4
2
Number of musical tunes available
Unlimited
6
Requirement for custom ROM masks
Custom-masked parts (RSC-364) are not stocked
No internal ROM Custom-masked ROM required
by Sensory
Table 1—
The RSC-364, with 64-KB on-chip ROM, is a single-chip voice recognition solution. Taking advantage of
the features that require lots of storage, such as voice recording, requires adding external memory. Accuracy
above 95% must be maintained. The RSC-364 assumes the use of on-chip ROM/RAM only and external serial
EEPROM memory. It depends on the choice of musical instrument and requires external storage for recordings.
CHARGE ORDERS to Visa, Mastercard,
. Shipping and handling for the
C add-ons, recognition programs are
easy to write. However, debugging
them is a bit complicated currently.
Although the ’364 has on-chip debug
hardware (monitor, breakpoints, and
such), the beta version of the software
I received didn’t take advantage of the
hardware. That means reverting to
the old days of inserting print state-
ments. In a whimsical twist on the
recognition coprocessor working
in conjunction with another con-
troller. This is especially true for
those who are retro-fitting voice
recognition features onto an exist-
ing product (i.e., most first-time
Sensory customers). Use the twin
8-bit parallel ports or software RS-
232 to establish an unobtrusive
link with the host and have at it.
When it comes to writing
actual voice recognition
code with VE C, I think the
VE features more than make
up for weaknesses on the C
side. The language has a full
quiver of built-in voice pro-
cessing routines and special
functions that deal with the
’364 on-chip hardware. For
example, in addition to the
usual INTs and CHARs, VE C
knows about data types like
templates, weights, notes,
tunes, and speech.
The ’364 makes hardware
design a snap, as you can see in
Figure 2. And, thanks to the VE
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
79
statically, so feed VE C some recur-
sive code and you’re in for quite a
debugging session. Sure, the ’364 can
handle some simple tasks on the side,
but at the same time I suspect that
it’s all too easy for the chip to bite off
more than it can chew.
If you’re in a hurry (and who isn’t
these days?) and aren’t building a zil-
lion units, it’s probably better to use
the ’364 module (see Photo 4) as a
Photo 2—
The Sensory QuickSynthesis program makes
incorporating
.WAV
recordings in your project a snap, but
watch out because, even with compression, the required
memory adds up quickly.
Photo 3—
Although lacking much in the way of debug capabili-
ty at this time, the Voice Extreme IDE is a big improvement
over the earlier generation DOS tools.
w..cciirrccuuiittcceellllaarr..ccoom
Go to our web
site to get all of
the Circuit Cellar
back issues on
CD-ROM.
I had little trouble installing and fir-
ing up the software. Sensory thought-
fully supplies a number of short demo
programs to both serve as coding
examples and assist hardware check-
out and evaluation.
There were a couple of problems I
filed under beta-site gotchas. When I
tried to experiment with one of the
demo projects, the compiler would
hang up partway through the build
process. The release document did
allude to getting an error message
during builds with older versions of
Windows and offered a fix (increase
the number of environment variables
in
SYSTEM.INI). Even though I wasn’t
getting the error message and my PC
is relatively new, I made the fix and
the build proceeded smoothly.
Next, I tried to download a demo,
but the software insisted it couldn’t
find the VE board. Yes, the serial
cable to the PC was plugged in. After
some head scratching, I discovered
the solution in the documentation,
80
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
scheme, the VE C DEBUG statement
has options that either spell (i.e., RS-
232 output) or speak to you.
YAK ATTACK
Alright already, enough of this book
learning. Now, it’s time to give Voice
Extreme a workout.
Figure 2—
Thanks to the built-in
microphone preamplifier, PWM
speaker driver and direct memo-
ry connection, upgrading your
hardware design with voice
recognition is easy.
although it mistakenly referred to
operation with the older version of
the kit. To get the board to download
a new flash image simply requires
holding down one of the buttons
(aptly named VELOAD) during reset.
Check out the speaker-independent
demo I played with in Listing 1. The
program prompts you to say one of six
words (call, erase, modify, play,
record, or skip) and attempts to recog-
nize it. If successful, the program
announces, “You said (appropriate
word),” otherwise it responds with
“What did you say?”
Although it’s a toy program, it
clearly demonstrates the power of VE
when it comes to writing speech
recognition applications. I’m certainly
not familiar with any other technolo-
gy that could come close to what VE
C does in a mere page and a half of
code (including comments).
It’s easy to write the software, but
how well does it work? There are
times when having kids is actually
Photo 4—
An alternative to starting from scratch, the
Voice Extreme module combines the ’364 chip with
flash memory and analog front-end components.
82
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
speaking, proper microphone place-
ment, and ambient background noise.
To be fair, like the demo program,
you need to stack the deck when
defining your vocabulary. Notice how
the words chosen for the demo don’t
sound alike. I didn’t have time to try
it, but I’m sure the ’364 would have
problems dealing with a vocabulary of
words that sound alike but have dif-
ferent meanings (i.e., one, won, win,
wan, when, warn). Fortunately, just as
the English language is goofy enough
to have words that sound alike but
have completely different meanings,
you can usually come up with a dif-
ferent sounding word that gets the
same meaning across.
HEARING AID
Putting misguided QWERTY-killer
aspirations aside, VE represents an
incremental boost in voice recogni-
tion performance, cost, and ease of
design. Yes, it’s far from the mythical
automatic stenographer, but many
practical voice recognition apps proba-
bly are best served by the VE solution.
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.
SOURCE
Voice Extreme Toolkit, RSC-364
Sensory, Inc.
(408) 327-9000
Fax: (408) 727-4748
www.sensoryinc.com
useful, I reminded myself as I con-
scripted the litter and marched them
into the office. I figured that between
the younger kids’ chirps, the 14-year
old’s adolescent cracks, and my rum-
bling growls, we’d put the speaker-
independent claims to the test.
Seeing everyone huddled around
shouting at a circuit board must have
been a sight, but by golly if it didn’t
work like a champ. In fact, the rela-
tively few errors that did occur
seemed more like a matter of gain
issues (i.e., not speaking directly at or
close enough to the microphone) than
weakness in the recognition itself.
Furthermore, this explains why the
documentation includes a fair amount
of discussion related to proper micro-
phone placement, mounting, housing
materials, and so forth.
It was possible to probe the error
zone by intentional mispronuncia-
tion, speaking unnaturally fast or
slow, or, on occasion, imitating
Homer Simpson. But in reality, the
recognition was uncannily accurate
under nominal conditions of natural
Just remember to keep it simple.
Don’t require or expect users to enjoy
long-winded repartee with some
embedded gadget. I want a chip that
acts like a servant, not a cross
between HAL and a psychiatrist.
Also, just because our brains do a
good job of filtering it out, don’t over-
look the fact that we live in a noisy
world. Think twice before you trigger
a significant real-world event based
on something a chip overhears. Drive-
by voice system? I don’t think so.
I
CIRCUIT CELLAR
Test Y
Your E
EQ
What’s your EQ?
—The answers
and 4 additional questions and
answers are posted at
www.circuitcellar.com
You may contact the quizmasters
at eq@circuitcellar.com
8
more EQ
questions
each month in
Circuit Cellar Online
see pg. 4
Problem 1
—In digital hardware, what are
setup and hold times? What kinds of devices
have them?
Problem 2
—Why did Hewlett-Packard's first
product — a wide-range, low-distortion oscilla-
tor — have a light bulb buried in the circuitry?
Problem 3
—Assuming a fixed inductor, what
range of tuning capacitance do you need to
cover the AM broadcast band, 540 through
1600 kHz?
Problem 4
—In the circuit below, what can you say
about the signal OUT as a function of the value
loaded into the input latch? You can assume that
latch updates are infrequent relative to CLOCK
cycles.
Strobe
Input
(N bits)
Latch
binary
addresser
register
D
Q
OUT
CLOCK
carry out
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
83
....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
PHYTEC America LLC ■ 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!
84
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
85
56&RQWUROOHGRU&DQQHG&\FOHG&RQWUROOHG
6KRUW&LUFXLWDQG2YHU7HPS3URWHFWLRQ
3URJUDPPDEOHELWRSWLFDOO\LVRODWHGLQSXWV
%XLOWLQ$FFHOHUDWLRQ'HFHOHUDWLRQUDPSLQJ
6RIWZDUH&XUUHQW$GMXVWPHQWYLD56
• Design, PCB Fabrication & Assembly
• DS, Multi-Layer, SMT & RF PCBs
• In-house CAM & Photo Plotting and
Superior Quality at Competitive Prices
"...your product was delivered on
schedule and was of the highest quality."
R.R. Bell Atlantic Test Systems
7845-M Airpark Rd., Gaithersburg, MD 20879
Fax: (301) 990-6715 BBS: (301) 990-9628
86
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
Need to quickly get up to speed with the
PICmicro
172 Harvard Road
Waterloo, ON, N2J 3V3
Canada
519.886.4462
519.886.4253(fax)
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
87
88
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
Visit our new site www.jkmicro.com
Call 530-297-6073 Fax 530-297-6074
6 Serial Ports
Ethernet
33Kbaud
Modem-Option
Starts at $369
2 Serial Ports
Ethernet
Enclosure
Starts at $229
PC Based Data Acquisition & Control Products
PCI-9812, 20 MHz Simultaneous
4-Ch Analog Input Card
PCI-7300A, Ultra-High Speed 32-Ch
Digital I/O Card
for EXTENSIVE DETAILS. Much broader selection online!
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
89
Scottsdale, Arizona
Ph: 480.998.3503
Fx: 480.998.3504
Resistance Substitution Device
Order
on-line for
FREE shipping!
• Full duplex
• 422 or 485 4 wire
• Short haul modem
Connecticut microComputer, Inc.
PO BOX 186, Brookfield,CT 06804
(203)740-9890 Fax:(203)775-4595
90
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
91
92
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
Get your IP network remote control
8 Relays, 8 Inputs. Control & Feedback
8 Inputs, 8 Relays. Alarm Monitor
Web, Ping Controlled A/C Reboot Switch
1 Input / 1 Output OEM Control Board.
30+ years satisfying End Users, VARs, and OEMs.
100s of products plus custom modifications & design.
Download or browse online catalog.
For acquisition and control of digital and analog signals.
High speed Serial Port Interface
24 digital I/O (TTL compatible)
11 Analog Channels with 12 bit ADC
4 channels with signal conditioning
Embedded stepper motor controller
Control up to 16 stepper motors simultaneously
Up to 8500 Steps/sec with linear Accel/Decel.
Chopper driver up to 48V/2A for 4,5or 6 wire motors.
Software Winding Current Setup.
Shaft encoder input , external driver capabilities.
Internal FIFO for linear, cubic or spline Interpolation.
24 digital I/O,2 SPI, 11 analog channels on-board.
32 bit DLL with examples in VC++,VBasic and Delphi.
9 Channel Data
Loggers from
US$400. Ask us, or
visit our web site.
Control up to 16 stepper motors simultaneously
Tel: (604) 299-5173 Fax: (604) 299-5174
Web site: www.rmv.com
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
93
Integrated Development Systems:
Compilers, Simulators, Programmers,
Non-intrusive, with trace feature, hardware unconditional & complex
breakpoints, triggers, programmable clock, memory mapping &
banking, full project & source level support for C compilers…
piler to produce DOS EXE. Download EXE to flash disk via serial
port. EXE runs on power up.
Standard Features:
BIOS & DOS-ROM, 128K flash disk,
512K SRAM, 40 MHz AM188ES CPU, 16 digital I/O (opto rack
interface), 2 RS-232, 2 timer/counters, simple bus interface,
real-time clock with timed power-up
Options:
8-ch 12-bit ADC, flash disks up to 288 MB, 1 RS-485
2”x2.6”, 5V @ 200 mA at full speed.
94
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
ADVERTISER’S
www.circuitcellar.com
CIRCUIT CELLAR
®
Issue 133 August 2001
95
INDEX
49
ADAC
85
Abacom Technologies
92
Abia Technology
86
Ability Systems Corp.
86
ActiveWire, Inc.
85
Advanced Embedded Technologies
20,21
Advanced Transdata Corp.
78
All Electronics Corp.
85
Amazon Electronics
9
Amulet Technologies
84
Andromeda Research
91
AP Circuits
65
ATOP Technologies
58
Arcom Control Systems
93
Bagotronix, Inc.
84
Basic Micro
86
Bay Area Circuits
86
CCS-Custom Computer Services
87
CSMicro Systems
85
Capital Electro-Circuits, Inc
90
Cedar Technologies, Inc.
25
Ceibo
94
Cermetek Microelectronics, Inc.
88
Circuit Specialists, Inc.
91
Conitec Data Systems
13,89
Connecticut mircoComputer Inc.
85
Copeland Electronics Inc.
86
Cyberpak Co.
41
Cygnal Integrated Products
C4
Dataman Programmers, Inc.
92
Dataprobe Inc.
86
DataRescue
The Advertiser’s Index with links to their web sites is located at www.circuitceller.com under the current issue.
Page
83
Decade Engineering
55
Design MSP430 Contest
87 Designtech Engineering
92
Device Drivers Int’l, Inc.
93
Digital Products
7
Dreamtech Computers
59
Earth Computer Technologies
40
ECD (Electronic Controls Design)
84
EE Tools
(Electronic Engineering Tools)
64
EMAC, Inc.
84
FDI-Future Designs, Inc.
33
General Software
86
HVW Technologies Inc.
84
Hagstrom Electronics
32
HI-TECH Software,LLC
93
ICE Technology
89
IMAGEcraft
90,92
Intec Automation, Inc.
18
Interactive Image Technologies Ltd.
87
Intronics, Inc.
65,88
JK microsystems
90
J-Works, Inc.
30
JR Kerr Automation & Engineering
39
Jameco
89
LabMetric, Inc.
87 Laipac Technology, Inc.
94
Lemos International
2
Link Instruments
90
Lynxmotion, Inc.
87
MaxStream
90
MCC (Micro Computer Control)
83
MetaLink Corporation
88
MJS Consulting
87
Micro Digital Inc
94
microEngineering Labs, Inc.
33
Microcross, Inc.
48,81
Micromint Inc.
30
Midwest Micro-Tek
66,79
MVS
92
Mylydia Inc.
17
NetBurner
86,89
Netmedia, Inc.
83
Nohau Corp.
89
OKW Electronics Inc.
77
On Time
91
Ontrak Control Systems
93
PCB Express, Inc.
C2
Parallax, Inc.
83
Phytec America LLC
93
Phyton, Inc.
92
Picofab Inc.
92
Prairie Digital Inc.
89
Pulsar Inc.
88
Quadravox
84
R.E.Smith
90
RLC Enterprises, Inc.
92
RMV Electronics Inc.
31
Rabbit Semiconductor
64
Remote Processing
85
SMTH Circuits
12
Saelig Company
5
Scott Edwards Electronics Inc.
88
Sealevel Systems Inc.
92
Senix Corp.
85
Sigg Industries
83
Signum Systems
86
Sirius MicroSystems
88
SmartHome.com
30
Softools
8
Solutions Cubed
91
Spectrum Engineering
83
Square 1 Electronics
91
Street Rod Digital
10
Systronix
32,71
Technologic Systems
94
Technological Arts
91
techBITES INTERactive
C3
Tech Tools
90
Tern Inc.
26
Texas Instruments
13
Trilogy Design
93
Vantec
93
Vetra Systems Corp.
91
Weeder Technologies
1
Wilke Technology GmbH
94
Xilor Inc.
87
Z-World
84
Zanthic Technologies Inc.
Pigeons, Pooches, and PICs
Embedded Internetworking with CANopen
Listen Anywhere: Building a Wireless MP3 Remote Jukebox
One Project Turns into Another:
An Exponential Sweep Frequency Generator
I From the Bench
: Technology That Improves with Age:
Eliminate Senior Moments with SAMI
I Silicon Update
: Bluetruth
I Applied PCs:
The Progress of 8051: iKit2000
Page
Page
Page
Embedded Development
PREVIEW
134
hen you hang around with Ed Nisley for a while you tend to pick up some of his colloquialisms.
Rather than use dull instructions like, “exercise a persistent strategy until the procedure in question func-
tions properly,” Ed simply says something like, “tune for best picture.” One of Ed’s more colorful metaphors is
“reset registers.” You certainly don’t have to be a design guru to realize that reset registers just means it’s time to
reexamine something you’re doing. Like a software program, resetting the registers at
Circuit Cellar meant assessing our current
direction to see if there should be changes. Ultimately, my analysis revealed both no and yes.
Most emphatically “no” concerning our editorial direction and editorial quality. I think if anything has separated us from the pack
over the years, it has been the loyalty and intelligence of
Circuit Cellar readers. Our advertisers have further confirmed this. While
the electronic trade publishing industry is reeling from a 40% drop in monthly advertising, we have yet to experience any significant
slump. If I had to characterize our success, I’d say it’s because of mutual respect among readers, advertisers, and
Circuit Cellar.
Then, there is that one “yes” I have to deal with. As most of you know, I give free issues of the magazine to college engineering
classes that register and qualify. I know that information is easier for students to get these days than when I was in college, but
having mounds of new sources doesn’t ensure its integrity or usefulness. We’re all about doing real applications at this magazine
and I know that is one area of exposure that is sometimes deficient in an engineering education. The savvy educators who read
Circuit Cellar know this, and consequently the demand to be part of our college program has always been high.
Some months ago, I announced the creation of a monthly PDF edition. Back then I justified it as a cost-saving measure. It would
help defer a subscription price increase and allow me to say yes to the avalanche of foreign college program requests. In truth, I
didn’t like discontinuing print issues to colleges, but the shipping cost was killing me. Besides, they could just download it, right?
Well, $20,000 worth of database-management software later, we have a great means of providing both college-program and
paid-subscriber electronic editions each month. I can now enroll an engineering class in Chile just as easily as one in Boston. An
engineer in Croatia can subscribe to the PDF for the same low price as someone in San Jose. More importantly, the availability of a
low-cost PDF edition has significantly increased our foreign circulation. Now colleges that were previously denied print delivery
because of the shipping costs are receiving the magazine. That’s the good news.
The bad news is that the electronic edition is not doing the job for the specific audience that it was intended for. Just like all the
hype about the wireless Internet (long on pitch, short on delivery), the high-bandwidth connected college universe isn’t quite true
either. Whereas Cal Tech, MIT, and many state-supported colleges have Ethernet access for students, it isn’t true for the majority of
the colleges enrolled in our program. According to the reports I received after changing everyone to the PDF, most students are still
limited to dial-up connections. Getting 30 students in a class to each download a 12-MB file became impossible. Consequently, pro-
fessors who typically scheduled class time to pass out a box of issues and discuss specific projects were hindered by the necessity
for everyone to print out the magazine or drag a laptop to class. Basically, it was described to me as a real bummer.
In a classic case of Ed Nisley’s reset registers, I have changed my mind and unilaterally decided to start supplying print issues to
domestic colleges again, beginning with this issue. It may not be as many as I previously provided and it will be strictly limited to
domestic delivery and selected colleges in Canada (the long-time participants), but it will be print magazines. I’ll also be asking pro-
fessors to reregister their classes. In the interim, I’ll use the requests I have on file for the previous program.
Certainly all of this has its benefits and consequences. The benefit is that it revitalizes a valuable
Circuit Cellar program. The
consequence is that I have to admit that I was wrong given the technology and circumstances. It’s costly to go back and do it the
old way, but I still think it’s important. I guess this is one time I’ll just have to eat crow. Deep down, I know it’s really fillet mignon.
Reset Registers
INTERRUPT
w
steve.ciarcia@circuitcellar.com
PRIORITY
96
Issue 133 August 2001
CIRCUIT CELLAR
®
www.circuitcellar.com
In-Circuit Firmware Development with
evelopment tools from TechTools
ER3 will speed up your firmware
development by eliminating the need
to remove-erase-program and re-
devices plug into the EPROM
socket on your target board
We provide software that loads your
firmware code into the emulator in a matter of
seconds! No more waiting for the eraser or
EPROM programmer. No more “debugging” bent
FlexROM emulators provide engineers with a flexible
development tool for any Embedded project that uses an
external FLASH, EPROM or SRAM device.
see the Target’s address fetches with FR3’s Hardware
now supports multiple file projects with “1-Click”
file conversion and downloading.
FR3 is a Flexible, in-circuit memory Emulator with instrumentation.
ER3 is designed for quick, in-circuit firmware test cycles.
TechTools Complete Development System with integrated
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