circuit cellar2004 12

background image

7

9

25274 75349

12>

CIRCUIT

CELLAR

®

www.circuitcellar.com

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)

#173 December 2004

High-Level Software
Analysis Solution

NCO-Built 60-Hz
Generator

Low-Cost FPGA
Alternative

Programmable Timer

EMBEDDED DEVELOPMENT

High-Level Software
Analysis Solution

NCO-Built 60-Hz
Generator

Low-Cost FPGA
Alternative

Programmable Timer

background image
background image
background image

Digital Oscilloscopes

2 Channel Digital Oscilloscope

100 MSa/s

max single shot rate

32K samples per channel
Advanced Triggering
Only 9 oz and 6.3” x 3.75” x 1.25”
Small, Lightweight, and Portable

Parallel Port

interface to PC

Advanced Math options
FFT Spectrum Analyzer options

DSO-2102S

$525

DSO-2102M

$650

Each includes Oscilloscope,
Probes, Interface Cable, Power
Adapter, and software for
Win95/98, WinNT, Win2000
and DOS.

40 to 160 channels
up to 500 MSa/s
Variable Threshold
8 External Clocks
16 Level Triggering
up to 512K samples/ch

Optional Parallel Interface

Optional 100 MSa/s Pattern Generator

LA4240-32K (200MHz, 40CH) $1350
LA4280-32K (200MHz, 80CH) $2000
LA4540-128K (500MHz, 40CH) $1900
LA4580-128K (500MHz, 80CH) $2800
LA45160-128K (500MHz, 160CH) $7000

www.LinkIns4.com

Link Instruments

• 369 Passaic Ave • Suite 100 • Fairfield, NJ 07004 • (973) 808-8990 • Fax (973) 808-8786

Logic Analyzers

• 24 Channel Logic Analyzer
• 100MSa/S max sample rate
• Variable Threshold Voltage
• Large 128k Buffer
• Small, Lightweight and Portable
• Only 4 oz and 4.75” x 2.75” x 1”
• Parallel Port Interface to PC
• Trigger Out
• Windows 95/98 Software

LA2124-128K (100MSa/s, 24CH)
Clips, Wires, Interface Cable, AC
Adapter and Software

$800

All prices include Pods and Software

background image
background image

I

t’s hard to believe it’s December already. Then again, this month seems

longer than usual this year. I noticed the candy corn and scary masks
pushed aside on the sale tables a week before Halloween to make room
for Christmas and Hannakuh stuff. What happened to Thanksgiving?
Don’t get me wrong. I do love the holidays, but there are only so many
times I can listen to “Felice Navidad” and “Auld Lang Syne” before I start
actually looking forward to the bitter cold of February in New England.

As the year comes to a close, I want to take this opportunity to thank

everyone who contributed to the magazine in 2004. We’ve run some fan-
tastic features this past year thanks to the ingenuity of our writers. I hope
you’ll join me in also thanking our hard-working columnists—Jeff
Bachiochi, Fred Eady, Tom Cantrell, and Ed Nisley—for bringing us prac-
tical solutions and keeping us up to date on the latest and greatest com-
ponents and technologies. I also wanted to thank our loyal readers, many
of whom have been subscribers since the first issue back in 1988.

When we conduct reader surveys, one thing always jumps out at me.

It’s remarkable how many readers hold on to their issues. One of our
magazine’s best characteristics is that it works so well as a resource
guide. As some of you may know, we have a college program that pro-
vides free issues to professors for their engineering classes. Recently, I
received an e-mail from someone just starting his professional career.
When he graduated from college a few years ago, he grabbed a stack of
issues his professor had leftover. He told me that, although some of the
projects were tough to follow in college, he is glad he held on to them
because now he’s ready to work on the more advanced applications that
he’s found most interesting and useful.

If you’re missing any issues from your personal library, you can order

the back issues from our web site (www.circuitcellar.com/products/cd.asp).
For those of you who don’t have the space to keep stacks and stacks of
magazines, you’ll be happy to know that we’ll have the 2004 CD-ROM
ready in early 2005. The CD-ROM will feature full-color PDFs of the com-
plete year of issues. You’ll be able to place your order on our web site in
January (www.circuitcellar.com/products/cd.asp).

This has been a great year for design contests as well. The Atmel

AVR 2004 Design Contest, the ZiLOG 2004 Flash Nets Cash Design
Contest, and the Cypress PSoC High Integration Challenge 2004 were
successful thanks to the generosity and support of the sponsors and the
dedicated entrants who designed so many highly optimized applica-
tions. (For more information about past and present contests, go to
www.circuitcellar.com/magazine/contests.htm.) We have more design
contests in store for next year, so stay tuned.

I wish you all happy holidays!

4

Issue 173 December 2004

www.circuitcellar.com

CIRCUIT CELLAR

®

EDITORIAL DIRECTOR/FOUNDER
Steve Ciarcia

MANAGING EDITOR
Jennifer Huber

TECHNICAL EDITOR
C.J. Abate

WEST COAST EDITOR
Tom Cantrell

CONTRIBUTING EDITORS

Ingo Cyliax
Fred Eady
George Martin

George Novacek
Jeff Bachiochi

NEW PRODUCTS EDITOR
John Gorsky

PROJECT EDITORS
Steve Bedford
Ken Davidson
David Tweed

ADVERTISING

PUBLISHER

Dan Rodrigues

E-mail: dan@circuitcellar.com

ASSOCIATE PUBLISHER/DIRECTOR OF SALES

Sean Donnelly

Fax: (860) 871-0411

(860) 872-3064

E-mail: sean@circuitcellar.com

Cell phone: (860) 930-4326

ADVERTISING REPRESENTATIVE

Rachel Humphrey

Fax: (860) 871-0411

(860) 872-3064

E-mail: rachel@circuitcellar.com

ADVERTISING COORDINATOR

Valerie Luster

Fax: (860) 871-0411

(860) 875-2199

E-mail: val.luster@circuitcellar.com

ADVERTISING ASSISTANT

Deborah Lavoie

Fax: (860) 871-0411

(860) 875-2199

E-mail: debbie.lavoie@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) are 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
consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-
er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or
from plans, descriptions, or information published by Circuit Cellar®.

The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to
build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to
construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.
The reader assumes any risk of infringement liability for constructing or operating such devices.

Entire contents copyright © 2004 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

CUSTOMER SERVICE

Elaine Johnston

CONTROLLER

Jeff Yanco

ART DIRECTOR

KC Prescott

GRAPHIC DESIGNER

Mary Turek

STAFF ENGINEER

John Gorsky

QUIZ COORDINATOR

David Tweed

Cover photograph Chris Rakoczy—Rakoczy Photography

PRINTED IN THE UNITED STATES

Looking Back

jennifer.huber@circuitcellar.com

TASK MANAGER

background image
background image

6

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

December 2004: Embedded Development

4

TASK MANAGER
Looking Back
Jennifer Huber

8

NEW PRODUCT NEWS
edited by

John Gorsky

13

TEST YOUR EQ
edited by

David Tweed

FEATURES

COLUMNS

DEPARTMENTS

94

INDEX OF ADVERTISERS
January Preview

96

PRIORITY INTERRUPT
What’s Another Watt or Two?
Steve Ciarcia

14

H8/38024F-Based Programmable Timer
Richard Wotiz
Renesas H8 Design 2003 Contest Winner

32

Atmel AVR 2004 Design Contest Winners Announcement

36

Visualizing History
Record and View High-Level Software Behavior
Scott McOlash

54

Artificial Life Display (Part 1)
Design Basics
Bob Armstrong

62

An FPGA Experimenter’s Board
Philip Nowe

72

Reference Generation
Build a 60-Hz Generator with an NCO
Tom Napier

22

ABOVE THE GROUND PLANE

Building Boxes
Ed Nisley

26

FROM THE BENCH

Light-to-Frequency Conversion (Part 1)
TSL230R-Based Pulse Oximeter
Jeff Bachiochi

44

APPLIED PCs

RabbitWeb HTTP Server
Fred Eady

78

SILICON UPDATE

Position Statement
Tom Cantrell

Programmable

Timer (p. 14)

DIY 60-Hz

Generator (p. 72)

Pulse Oximeter (p. 26)

Cellular Automaton Simulation (p. 54)

Box Building Basics (p. 22)

Box Building Basics (p. 22)

Programmable

Timer (p. 14)

DIY 60-Hz

Generator (p. 72)

background image
background image

8

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

Edited by John Gorsky

TINY FOOTPRINT SMT PACKAGE EMULATION

The SF-MLF32A-A-02 is a small footprint surface-mount

package emulator foot for 5-mm body, 0.5-mm pitch pin
devices, such as members of the Cypress PSoC CY8C2xxxx
family. This device uses patent-pending technology to
achieve a reliable and small SMT MLF adapter.

The SF-MLF32A-A-02 has

pads on the bottom that pre-
cisely match the pin layout for
the MLF/QFN package includ-
ing the E-pad or heatsink pad
in the center of the pattern.
This allows connection to an
MLF land pattern of the target
board to provide a set of inter-
connects available for probing
or connecting to another
assembly. Simply solder the
SF-MLF32A-A-02 using the
same solder reflow and attach-
ment methods used for an

MLF/QFN 32-pin IC.

The SF-MLF32A-A-02 is the same size as the MLF/QFN

32-pin IC in the XY dimension and only 3.3 mm high. The
top of the SF-MLF32A-A-02, after being attached to the
target, consists of female, machined socket pins with all

gold plating for maximum reli-
ability. Compatible gold-plated
male pin adapters are then
plugged in and emulation,
probing, or interconnecting
the MLF is accomplished.
Other sizes of MLF SMT
adapters are available in the
same product line from 28 to
64 pins.

The SF-MLF32A-A-02 costs

$156.

Ironwood Electronics
www.ironwoodelectronics.com

VIDEO GAME SYSTEM DEVELOPMENT KIT

The XGameStation Micro Edition (XGS ME) is the

world’s first video game system development kit designed
for educational purposes. The kit comes with an assem-
bled XGameStation console, a single controller, all of the
necessary cables, a CD containing all of the system soft-
ware and tools necessary to develop the system, and an
extensive eBook that explains how the system was
designed and how it works from the ground up. The
Ubicom SX52 powers the system; it runs at 80 MHz for
80 MIPS of performance with a 12.5-ns instruction cycle.

The SX52 core is responsible for general control of the

raster timing and video signals generated via control of a
special D/A converter that generates a TV-level signal and
mixes luma and chroma to generate composite video. The
SX52 generates the sync pulses as well as the raster data.

Sound on the XGS Micro Edition is generated with a

ROHM BU8763, which is a three-channel FM synthesizer
with full envelope control. For I/O, the XGS has two
Atari 2600-compatible joystick ports, a serial port, and a
30-pin expansion port. Rounding out the hardware is an
external 128K × 8 SRAM for general use (e.g., program
data, decompression buffers, and screen buffers).

The XGS ME comes with XGS Studio, a built-in pro-

grammer and tool
chain. Additionally, the
XGS has a compatibili-
ty port for Parallax’s
SX-KEY, so you can use
its tools as well.

The XGS ME costs

$199.95.

Nurve Networks LLC
www.xgamestation.com

ENCODER/DECODER RF/INFARED LINKS

MS Series encoders and decoders are ideal for remote con-

trol, command, security, keyless entry, status monitoring,
and a host of similar applications. They allow the status of
up to eight buttons or contacts to be securely transferred via
an RF or infrared link.

These encoders and decoders have several unique features

that make it superior to competitive solutions. They can
define unique user groups and relationships, latched or
momentary outputs,
and convenient,
secure address
assignment without
DIP switches. In
addition, you can
define which out-
puts each encoder
has the authority to
activate. This
makes setting
access control as
simple as pushing a
button. The decoder also identifies and outputs the originat-
ing encoder ID so that the transmitter can be easily identi-
fied.

Housed in tiny 20-pin SSOP packages, MS series parts fea-

ture low supply voltage and low current consumption. The
components are complemented by a full evaluation system
to demonstrate their powerful features and ease of applica-
tion.

MS Series components cost $2.11 each in production vol-

ume quantities.

Linx Technologies, Inc.
www.linxtechnologies.com

background image
background image

10

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

LOW-COST, RAIL-TO-RAIL OUTPUT OP-AMPS

The ADA4851-x family of operational amplifiers delivers

many of the performance benefits usually found in more
expensive amplifiers, such as high-speed, rail-to-rail output
and excellent differential
gain and phase. Making
these features more afford-
able, the ADA4851-1 (sin-
gle), ADA4851-2 (dual),
and ADA4851-4 (quad)
voltage-feedback rail-to-
rail output op-amps are
ideal for high-volume con-
sumer applications.

The ADA4851-x family

combines bandwidth of
175 MHz, 250-V/µm slew
rate, and 0.1% settling in
25 ns, with only 3 mA per
amplifier of quiescent
current. These op-amps
provide true single-supply
capability, allowing the
signal levels on the input
to extend 200 mV below

negative rail. The output can swing to within 50 mV of
either rail.

With 0.1-dB flatness out to 15 MHz and differential gain

and phase of 0.05% and
0.05°, respectively, the
ADA4851-x family is ideal
for video applications.

The devices are available

in the following space-sav-
ing packaging options:
SOT23-6 (small outline
transistor), uSOIC-8 (small
outline integrated circuit),
and TSSOP-14 (thin shrink
small outline integrated cir-
cuit).

In 1,000-piece quantities,

the ADA4851-1 costs $0.55
per unit, the ADA4851-2
costs $0.79, and the
ADA4851-4 costs $1.09.

Analog Devices, Inc.
www.analog.com

The Embedded Java Controller (EJC) is a family of

embedded controllers that implement a full-fledged
Java platform for network-enabled and stand-alone
applications. The new EC200 modules provide an
Ethernet-based connection and numerous interfacing
possibilities like a graphic LCD, digital I/O, analog
inputs, high-speed serial ports, a dual I

2

C bus, and

Dallas 1-Wire. The software integrates Tao Group’s

EMBEDDED JAVA CONTROLLER

intent technology featuring an advanced real-time operat-
ing system and a Sun-certified JVM. This allows develop-
ers to adopt an all-in-one approach with which applica-
tions, system components, and even device drivers can be
written entirely in Java, without compromising flexibili-
ty and performance.

The EC200 series further pursues the innovative and

successful concept that was originally introduced by the
first EJC controllers. With a 20-fold performance boost,
more memory, extended functionality and connectivity,
industrial temperature range, and ultralow-power con-
sumption, the second-generation EJC represents a vast
improvement over a well-proven design.

New features include an integrated, fully-programma-

ble slave microcontroller that can be used to extend the
module’s possibilities with new functionality or to
offload the main CPU by taking care of process-intensive
I/O, thus making the new module a perfect fit for hard
real-time applications. The optional on-board NAND
flash memory provides up to 256 MB of solid-state data
storage for application code and data. An integrated LCD
controller can directly interface to most QVGA panels
and supports up to 4,096 colors on the screen.
Connection of a touchscreen controller is also possible.

Pricing starts at $175 in 10,000-piece quantities (stan-

dard configuration). Pricing includes licensing costs and
royalties for the OS, JVM, and run-time libraries.

Snijder Micro Systems
www.snijder.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

11

NEW PRODUCT NEWS

THERMOCOUPLE INPUT MODULE

The WTTCI-M is a member of a new

series of stackable RS-232 data mod-
ules. Four differential input channels
can accept types J, K, T, and E thermo-
couples and read absolute temperature
in degrees Fahrenheit or Celsius using
1° resolution. The module is capable of
measuring temperatures down to
–328°F below ambient and up to
2,502°F above ambient (type K).
Temperature conversions use high-
order polynomial equations that elimi-
nate look-up table interpolation errors.
Calibration is performed in firmware,
so no trim-pot adjustments are neces-
sary. Thermocouple inputs are pro-
tected to

±40 V.

Data acquisition software can be

downloaded free of charge from the
company’s web site and includes sample
applications for each module. All mod-
ules in this series can be plugged end to
end on a common RS-232 cable attached
to the serial port of a PC, laptop, or
another host. An on-board 32-position
DIP switch sets the address of each
module, which is used to identify data
transmitted from it and direct data
transmitted by the host.

SYNTHESIZED LCR/ESR METER

The Model 889A is a synthesized

bench in-circuit LCR/ESR meter.
Using a standard 115-VAC outlet as
the power source, this new high-accu-
racy test instrument with a computer
interface can be used
to test components
at frequencies up to
200 kHz, with a
basic accuracy of
0.1%.

Using the front

panel-mounted BNC
connectors and spe-
cial test leads, you
can easily and accu-
rately test a variety
of components. The
Model 889A not only helps engineers
and students to understand the charac-
teristics of electronic components, it’s
also a useful tool for any workbench.
Built-in functions include DC/AC
voltage and current measurements and
diode/audible continuity checks.

The Model 889A can be used for

measuring inductors, capacitors, and
resistors with a basic accuracy of 0.1%.
The default is automatic ranging; how-
ever, it can be set to manual ranging by
pressing the Range Hold key. When

LCR measurement
mode is selected,
test frequencies of
100 Hz, 120 Hz,
1 kHz, 10 kHz,
100 kHz, or 200 kHz
may be selected on
all applicable ranges.
Test voltages of
50 mV

RMS

, 0.25 VMS,

1 V

RMS

, or 1 VDC

(DCR only) also can
be selected on all

applicable ranges. The dual display
permits simultaneous measurements.

The Model 889A, which comes

with an instruction manual, costs
$1,395.

B&K Precision Corp.
www.bkprecision.com

The data bus supports full anticolli-

sion discipline between connected
modules and will allow up to 32 mod-
ules to share the same communica-
tions line. Power is supplied by an
external 8- to 30-VDC source (not
included) to the first module in the
chain and is carried down the RS-232
cable to successive modules.

The WTTCI-M costs $109.

Weeder Technologies
www.weedtech.com

background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

13

What’s your EQ?

The answers are posted at

www.circuitcellar.com/eq.htm

You may contact the quizmasters at eq@circuitcellar.com

CIRCUIT CELLAR

T e s t Y o u r E Q

Problem 3

What was the first CMOS sin-

gle-chip microprocessor?

Problem 4

Another early CMOS micro-

processor was the IM6100 from Intersil,
introduced in 1976. What was unique about
its architecture?

Contributed by David Tweed

Edited by David Tweed

Problem 1

What is it about the 6502 CPU’s

bus timing that made it particularly
amenable for use in video-based computers
and early game consoles?

Problem 2

Back in the days when video

displays were limited to 24 × 80 text only
and static RAMs were rather expensive,
there was a neat hardware trick that
allowed direct row-column addressing of
the display using just 2 KB of the SRAM.
What was it?

background image

14

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

mainly of a series of poses, or asanas,
and breathing techniques, known as
pranayama

. Some other common yoga

styles also focusing on physical prac-
tices are Ashtanga and Power yoga,
which can be more intense than Hatha.
Dedicated spiritual seekers also may be
familiar with a wide variety of yoga
styles based more on behavior than
physical practices. Karma yoga, for
example, is based on service to others.

For the past couple of years I have

been practicing Kundalini yoga, which
is focused on controlled breathing dur-

I

designed a programmable timer to

address the shortcomings of the existing
timers on the market. My H8/38024F-
based design allows an entire sequence
of time intervals to be preprogrammed
and executed one by one. It beeps
briefly at the end of an interval.

As you’ll see, the timer is the per-

fect tool for monitoring time-sensitive
activities like exercise routines. My
yoga class uses it.

NO PRETZELS ALLOWED

Yoga

is Sanskrit for “yoke,” or

“union.” With origins dating
back more than 5,000 years, yoga
encompasses elements of an
entire lifestyle geared toward
spiritual practice. Intended as a
method to unite the mind, body,
and spirit, it’s currently one of
the most popular ways to stay in
shape and reduce stress. There
are numerous yoga styles—some
ancient, some modern. Each has
a different approach to achieving
the mind-body-spirit union. The
choice of which to pursue is usu-
ally guided by personal preference
because one style is not necessar-
ily better or worse than another.

Most who are unfamiliar with

yoga think of it as the contortion-
ist exercises they’ve heard about
at the local health club. This is
usually the popular style known
as Hatha yoga, which is more
physically oriented. It consists

ing the application of carefully
designed stresses and relaxation to
internal organs. Most of the poses are
stretches done while sitting or lying
down, rather than the complex poses
of Hatha yoga. Each session consists
of one or more kriyas, which are com-
binations of several practices includ-
ing breathing, poses, sounds, medita-
tion, and relaxation. There are hundreds
of predetermined kriyas, each with sev-
eral steps that must be accurately
timed to achieve the desired effect.

The class I’m in has fewer than a

dozen people in it, and has a
peaceful, meditative atmosphere.
Aside from an occasional late
arrival, the only noticeable dis-
ruption is the beeping of the timer
at the end of each step. It actually
bothers our teacher more than us,
and she asked me several times if I
knew of any alternatives. The
timeout beeper is the problem.
Every timer she’s found starts
beeping at the end of the time
interval and won’t stop until she
presses a button. Often, she will
not be in a position to hit the but-
ton immediately, so the class
must listen to the insistent timer
for a while. In addition, most
timers generate audible feedback
after a button is pressed. This
results in a pattern of beeps and
boops every few minutes each
time my teacher restarts it.

At first, I thought there must

FEATURE ARTICLE

by Richard Wotiz

H8/38024F-Based
Programmable Timer

Photo 1

Take a look at the timer. To simplify the user interface, most

of the buttons have only one function assigned to them.

No more fussing around with household timers. Now you can manage time-sensitive activi-
ties like exercise routines with Richard’s H8/38024F-based programmable timer. Want the
alarm to sound every 10 minutes without your having to reset the time? No problem. Simply
key in your requirements beforehand.

CONTEST WINNER

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

15

be something out there that
other yoga teachers use during
their sessions, but neither my
teacher nor I were able to find
anything. It occurred to me that
if there were a way to preset
the entire routine in advance, it
would allow my teacher to
spend more time focusing on the
class, rather than having to
deal with the timer at the start
of each step. I wondered whether
a modified kitchen timer
would be useful or if I needed
to design something from
scratch. Then the Renesas H8
Design 2003 contest came along.
I learned that some Renesas
MCUs included features perfect
for a timer, so I felt it was time
to come up with a real solution.

TIMER SOLUTION

I call my design the Programmable

Yoga Timer (see Photo 1). The hard-
ware is built around a modified
Renesas H8/38024F demo board from
Basic Micro, which contains the MCU,
a four-digit LCD, an RS-232 serial
interface, and a power regulator. All
the board needed was a healthy diet to
remove everything I didn’t need.

I used the demo board because it

already included most of what I need-
ed. This way I didn’t have to hand-sol-
der the MCU’s fine-pitch leads to a
different board. Figure 1 shows the
block diagram of the system.

OPERATING MODES

The timer counts in one of three

modes. If you press the Start/Stop but-
ton after it’s first turned on, the timer
begins counting up. If the Minutes and
Seconds up and down buttons are used
to set a nonzero time before pressing
the Start/Stop button, it counts down
and beeps twice when done. The final
mode involves selecting a stored pro-
gram consisting of a preprogrammed
set of times that are used in sequence.

A stored program (time set) can be as

long as 20 time steps. You can store up
to eight programs. Each step can be
from 1 s to 99 min. and 59 s. To save
programs, flip the Run/Program switch
to Program, and then use the Set up and
down buttons to select the set number

you want programmed. The Step up and
down buttons select which time step to
change. The Minute and Second up and
down buttons select the desired time
interval; they automatically repeat
when held down for more than 0.5 s.
Use the On/Off/Clear button to set the
current time to zero. Intermediate steps
can be set to zero and used as placehold-
ers. These won’t show up in Run mode.
Changes are saved as soon as they are
made, thereby considerably simplify-
ing the user interface.

Each time the Set or Step number

changes while in Program mode, they’re
displayed briefly. Pressing the Start/Stop
button redisplays them, making it easy
to keep track of the current step.

After all of the desired time steps

and sets are entered, you execute
them by flipping the switch back to
Run. Any non-empty sets now can be
selected with the Set up and down
buttons, and the first nonzero time
step will appear. The Step up and
down buttons will sequence through
all nonzero steps of the selected set.
The preprogrammed time for the cur-
rent step also can be adjusted in Run
mode with the Minute and Second up
and down buttons, although the
change won’t be stored permanently.

HARDWARE

Photo 2 shows the modified demo

board. Note the battery holder located

where the power supply com-
ponents used to be and the
piezo speaker just below it.
An array of push buttons is
located in the prototyping area
at the bottom. The schematic
is shown in Figure 2 (page 16).

The H8/38024F is a good fit

for this application. It has a
built-in LCD controller/driver
with just enough segment
pins to drive a four-digit dis-
play in Static mode, which
allows it to work over a wider
voltage range than with mul-
tiplexed drive. The H8 is set
to output the same signal on
all four LCD common out-
puts. Two of these drive the
display, which uses a pair of
pins connected to a single
backplane. The H8’s low-fre-

quency oscillator allows it to keep
time and drive the display while using
a miniscule amount of power. There
are plenty of I/O pins allowing the
push buttons to be connected without
multiplexing them. This saves time
and power during button scanning.

The 10-bit A/D converter is used to

sense battery voltage in an unconven-
tional way. Because its reference voltage
is internally connected to the supply,
and the supply is connected directly to
the battery without any regulation, the

10-MHz

Ceramic

resonator

32768-Hz

Crystal

OSC

XOSC

H8/38024F

Switch

array

Voltage

reference

Voltage

detector

I/O

ADC

*RESET

V

DD

3-V

Battery

GND

SCI

LCD

CTLR

PWM

4 × 7

LCD

Speaker

SP3232

RS-232 Level converter

Optional

RS-232

Connector

MCU

Figure 1

The design is straightforward. A 3-V coin cell provides plenty of

power, because the H8/38024F normally runs off the 32-kHz oscillator when it
isn’t asleep. The optional serial port allows for in-system programming.

Photo 2

The hardware started out as a demo board.

I snipped off everything that wasn’t needed and then
made a few additions. The battery is at the top, with the
piezo speaker just below it. The buttons fit comfortably
in the prototyping area at the bottom.

background image

16

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

ADC’s reference will rise and fall with
the battery voltage. I used a 1.235-V ref-
erence diode to feed one of the analog
inputs, so the converted value will be
the ratio between the diode voltage and
the battery voltage. Thus, as the battery
drops, the converted value will increase.
An output port controls power to the
reference diode. Even though it con-
sumes only 10 µA, I didn’t want this
extra drain to run continuously.

Each of the switches connects to a

port with an internal pull-up resis-
tor—there are just enough of them.
The switches’ common terminals are
controlled by an output port, which I
enable only when they’re being read.
The exception is the On button,
which has to be active when the
MCU is in Standby mode. When the
H8 enters Standby mode, all of its

port drivers are disabled, even though
the pull-up resistors are still active. I
took advantage of the IRQ0 input to
wake up the MCU. The datasheet states
that either it or IRQ1 should work, but I
was unable to get any response from
IRQ1 in Standby mode. It worked fine
in Sub-Sleep mode, so I used it for the
Start/Stop button instead.

One of the PWM outputs drives a

piezo speaker element. By setting the
PWM to a 50% duty cycle, I got a
square wave output at the conversion
rate. This allows the piezo to generate
a single frequency beep, which is all
that’s needed. I originally wanted to
use both PWM outputs to drive the
piezo differentially and effectively
double the drive voltage, but I could-
n’t find a way to synchronize the two
channels. It turned out to be unneces-

sary, because the beep ended up loud
enough even with a single-ended drive.

I wanted the timer to operate on a

single lithium coin cell, which is typi-
cally rated for discharge down to 2 V at
room temperature. The MCU won’t run
that low, but it will work down to 2.7 V,
which takes advantage of about 90% of
the cell’s capacity. The maximum cell
voltage is around 3.3 V, so no voltage
regulator is needed. I used a 2.7-V reset
supervisor (U2) to keep the MCU hon-
est, and set the low battery threshold
to 2.8 V for plenty of warning.

As I selected U2, I discovered the

interesting fact that some parts have
power consumption specs that vary
with the package type. For example,
the Fairchild FM809R uses only 2 µA
in the SOT-23 package, but needs 6 µA
in an SC-70 for an otherwise identical

Figure 2

The H8/38024F contains almost everything needed for the timer. I was able to take advantage of the pull-up resistors on ports 1 and 3. There were just enough pins

for all the switches without having to multiplex them. The optional serial port circuitry doesn’t use any power unless it’s enabled with the Boot switch.

background image
background image

18

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

part. The Microchip TCM809R uses
17 µA in an SOT-23, but the SC-70
needs only 9 µA. I avoided the issue
by using a Seiko S-80927CL, which is
rated at 1.2 µA in any package. It
doesn’t have the built-in time delay
that the others do, but the MCU has
its own 131,072-cycle (approximately
26 ms) reset timer that does the job.

When the timer is awake, it’s almost

always in Sub-Sleep or Sub-Active
modes, measured at 10 and 22 µA,
respectively. When
asleep, it’s in Standby
mode drawing only 5 µA.
Occasional short bursts of
Active mode (each time a
button is pressed or
released) use little enough
power to be ignored. I
chose a CR2032 cell
because it’s commonly
available and has a rated
capacity of 220 mAh.
This allows for more
than a full year of contin-
uous operation. It can
operate for several years
if it’s used infrequently.

The demo board includes

a flash memory MCU,
which allows for instant
reprogramming and easy
debugging using a serial
port. I used what was once
the demo board’s power
switch to control power to
a 3-V RS-232 converter so
it would only draw power
when needed. The switch
also puts the MCU in Boot
mode, thereby allowing
the flash memory pro-
gramming routine to be
downloaded into RAM
and executed. I ended up
using a power supply when
downloading, because the
battery couldn’t run the
serial port for very long.

SOFTWARE DETAILS

The software was writ-

ten in C language using
HEW 2.0. Renesas has
since come out with HEW
3.0, which may have
slight differences from the

menus I’ll describe. The code was so
straightforward that I built it using
Release mode and wrote debug infor-
mation to the LCD rather than take
my chances trying to integrate the rou-
tines needed for the debugger. The code
is posted on the Circuit Cellar ftp site.

The code weighs in at just under

4 KB and uses 512 bytes of RAM. I
adjusted the linker’s segment map to
put the stack at the bottom and the
variables at the top of the RAM to

take advantage of 8-bit absolute
addressing that’s available for loca-
tions 0xFF00 through FFFF. This
allows for faster access to key vari-
ables used in the code that runs in
Sub-Active mode, helping to mini-
mize execution time and power con-
sumption. I did this by first selecting
“Hitachi H8S,H8/300 Standard
Toolchain” from the Options menu.
Next, I went to the C/C++ tab, select-
ed “Category: Optimize,” and then

selected “@aa:8” in the
Data Access box. This
puts all char-sized vari-
ables in a separate seg-
ment named $ABS8D (for
initialized data), $ABS8C
(for constants), or $ABS8B
(if not initialized). Then, I
had to let the linker know
where to put the data by
going to the Link/Library
tab, selecting “Category:
Section,” and then adding
a section named $ABS8B
at the top of the map.
Lastly, I had to modify the
file DBSCT.C (supplied
by the HEW Project
Generator) by uncom-
menting the line contain-
ing $ABS8B, thus allowing
the section to be cleared
to zero at start-up. I did-
n’t need to worry about
$ABS8C or $ABS8D
because the program
doesn’t use any initial-
ized char variables.

Figure 3 shows the main

routine control flow. After
initialization, the main
loop stops in Standby
mode with the On button
interrupt enabled. When
an interrupt occurs, it first
checks that it was from
the On button. Then it ini-
tializes some variables,
turns on the LCD, and
checks the battery level. If
it’s low, “Lb” is displayed
briefly. It then switches to
Sub-Active mode and

scans the buttons until
one is pressed or a 30-min.
idle timer expires.

Start

Enable On button interrupt

Switch to Standby mode and wait for interrupt

Disable On button interrupt

On button
pressed?

Initialize variables

Turn on LCD

Battery

low?

Display “Lb”

Switch to Sub-Active mode

Any button

pressed?

Y

Y

Switch to Active mode

Execute button action

Start

timing?

Initialize time display variables

Beep once

Enable TimerA, Start/Stop button interrupts

Switch to Sub-Active mode

Switch to Sub-Sleep mode and wait for interrupt

TimerA

interrupt?

Start/Stop

button

interrupt?

Switch to Active mode

Disable TimerA, Start/Stop button interrupts

Update time count

Timing all

done?

Switch to Active mode

Disable TimerA, Start/Stop button interrupt

Beep twice

Display “End”

Power-off

timeout?

Switch to Active mode

Turn off LCD

N

N

Y

Y

N

N

Y

N

N

Y

N

N

Y

Y

Figure 3

The main routine waits for you to press a button when the timer is in Sub-Active

mode. It switches to Active mode before handling it. After you press the Start/Stop button, the
timer starts counting down if a nonzero time was set; otherwise, it will count up from zero.

background image
background image

on the LCD each time an interrupt
comes along. Every other TimerA inter-
rupt, the displayed time is updated by
1 s. Because this routine executes in Sub-
Active mode, it needs to be as short
and efficient as possible. Listing 1
shows the time countdown code.

If the Start/Stop button is pressed

again, the timing loop exits and
returns to the main routine to wait for
another button press. When the time
reaches zero (if counting down) or
99:59 (if counting up), an “End” mes-
sage appears and the timer beeps twice
before returning to the main routine.

All of the tasks are done one at a time

20

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

SOURCES

PD422 LCD
Pacific Display Devices
www.pacificdisplay.com

H8/38024F Microcontroller
Renesas Technology Corp.
www.renesas.com

The push button debounce routine

takes approximately 10 ms to run. It
needs to run once every 10 ms to
debounce the buttons reliably without
any perceived delay, so there isn’t any
extra time to switch to Sub-Sleep mode.
After a button has been debounced, a rou-
tine is called to execute the correspon-
ding function. The buttons can be used to
select a particular stored time, set a
desired time, or start/stop the timer.

If the Start/Stop button is pressed,

the timer beeps once, sets up TimerA
to interrupt every 0.5 s, enables the
Start/Stop button interrupt, and switch-
es to Sub-Sleep mode. The colon blinks

in the main loop. As a result, the inter-
rupt routines only have to set flags.

CONSTRUCTION

Modifying the demo board was

straightforward. I removed everything
except the MCU, LCD, and serial port
hardware. I was initially surprised to find
out that the board came with a 5-V

CC

regulator, because the H8 is a 3.3 V-only
part. But, it appeared that no permanent
damage had been done. Even the standby
current was still well within the specifi-
cations. The board was ready to go after I
rerouted some LCD segments and power
traces and added push buttons, a battery
holder, voltage reference, and piezo.

Everything fit comfortably in a stan-

dard plastic box. I made the front
panel legend with an adhesive Mylar
laminating sheet (commonly available
at office supply stores) that I ran
through a laser printer.

STRETCH

The timer is just what my yoga

teacher had been looking for.
Although the prototype isn’t rugged
enough for long-term use, our classes
have been more relaxing.

I

Author’s Note: A special heartfelt
thanks goes to my yoga teacher Linda
Lois Churchill (Kulbir Kaur) for pro-
viding the inspiration for this projec

t.

PROJECT FILES

To download the code, go to ftp.circuit
cellar.com/pub/Circuit_Cellar/2004/173.

Listing 1

The time decrement routine is called every 0.5 s while the timer is counting down. It flashes the

colon and updates the time every other pass. Because it’s called while in Sub-Active mode, it needs to be
short and simple. I used a separate variable for each display digit, so the routine only needs to perform sin-
gle-byte compares and decrements, minimizing the number of instruction cycles.

BYTE timer_decr (void)

{

if (((COLON_addr ^= COLON) & COLON) != 0) { // Flash the colon

if (seconds_1 != 0) {

// If seconds ones digit nonzero,

seconds_1 ––;

// decrement it

if (seconds_1 == 0) {

// and check if we’ve timed out

if ((seconds_10 | minutes_1 | minutes_10) == 0) {

LCD_DIG_4 = dig_to_seg (0);

return (1);

// If so, return non-zero value

}

}

}

else {

// If seconds ones digit is zero,

seconds_1 = 9;

// reset it to 9

if (seconds_10 != 0)

// If seconds tens digit nonzero,

seconds_10 ––;

// decrement it

else {

seconds_10 = 5;

// Or else reset it to 5

if (minutes_1 != 0)

// If minutes ones digit nonzero

minutes_1 ––;

// decrement it

else {

minutes_1 = 9;

// Or else reset it to 9

minutes_10 ––;

// Decrement minutes tens digit

if (minutes_10 != 0)// Check for leading zero suppression

LCD_DIG_1 = dig_to_seg (minutes_10) | Batt_flag;

// Display it

else

LCD_DIG_1 = Batt_flag;// Just display battery status

}

LCD_DIG_2 = dig_to_seg (minutes_1) | COLON;

// Display second digit

}

LCD_DIG_3 = dig_to_seg (seconds_10) | Batt_flag;

// and third digit

}

LCD_DIG_4 = dig_to_seg (seconds_1); // and fourth digit

}

return (0);

}

Richard Wotiz earned a B.S.E. in
Electrical Engineering and Computer
Science from Princeton University. He
has run his own hardware consulting
business for the past 13 years, special-
izing in consumer products and chil-
dren’s toys. You may contact him at
dick601@mystics.org.

background image
background image

C

ircuit Cellar

has always devoted its

attention to the stuff inside the box: the
circuitry and firmware that make things
work. The box wrapped around those
innards gets little attention, generally
only in the context of making it electri-
cally safe and RFI-tight, although I’ve
seen some spectacular examples of
functional and attractive packages.

I routinely get e-mails asking about

how I package some of the gizmos I’ve
described in this column, so a digres-

22

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

sion into box building seems to be in
order. Most of what I build is either a
quick-and-dirty prototype or a gadget
for my own use, so I tend to ignore the
artistic fit-and-finish part of the job.
That’s obviously one end of a time-
and-effort trade-off!

Although I’ll describe how I work

with surplus parts rather than new
ones, the techniques apply equally
well to any construction project. You
should learn some new tricks and
might well produce much better look-
ing stuff than I do!

RECYCLING BIG BOXES

Ideally, a box must have enough

internal volume for the circuit board
and internal parts, sufficient surface
area for the controls and display, and
drop-dead gorgeous styling. Practically, I
tend to pick the least awful looking
box from my collection of surplus
stuff. I simply can’t afford to keep an
inventory of new boxes on hand in a
variety of sizes, so I buy decent look-
ing surplus boxes when they become
available at pennies on the dollar.

Surplus boxes may be new and

unused, prepunched and unused, or
wrapped around some electronics that
simply didn’t sell. I prefer the first two
categories, because they’re easier to
work with. They tend to be more expen-
sive, though, so I never pass up a nice
box surrounding some cheap junk.

Photo 1a shows how to eliminate pre-

punched holes or, perhaps, your very
own oops. The trick is to keep the out-
side surface reasonably flat, so you don’t
have to spend hours filing and sanding.

I cut the rectangular hole on the top

left for an IEC line cord socket and
fuse block. J-B INDUSTRO WELD—
which is a high-strength, steel-filled
epoxy—embeds the aluminum plates
that fill the other holes.

A layer of packing tape or laminat-

ing film on the outside ensures a flat
surface and keeps the epoxy off the
exterior. (The tape is barely visible in
Photo 1a.) Apply the tape smoothly.
Next, place the box tape-side down on
a piece of glass or a machinist’s surface
plate, and then work from the inside.

I put epoxy in the unwanted holes,

squished the aluminum plates in
place, and let the epoxy slump around
the inside seams. The plates needn’t
be works of art, because the epoxy
hides them completely, but they
should be the same thickness as the
surrounding panel. A little care elimi-
nates bubbles under the plates. The
outside is often flat enough for use
without sanding.

You can drill new holes right through

the plates and epoxy. If I need large
holes, though, I add a larger backup

Building Boxes

Ever wonder how Ed packages the gadgets he shares with us? This month he gives box
building its due. From reusing large boxes to building small ones, it’s all inside this column.

Photo 1a

I filled the unwanted holes with aluminum

plates and high-strength epoxy. A layer of packing tape
on the outside ensures a flat surface when it’s laid on a
glass plate to cure.

b—

Sanding the filler flush and

shooting it with almond Krylon paint produced a box
only a techie could love. The three small labels are
laser-printed address label stock.

a)

b)

Photo 2

This custom force-sensor joystick, which was

made from a bolt brazed to a lathe-cut steel sheet, fit
neatly atop a Gameboy cartridge.

ABOVE THE GROUND PLANE

by Ed Nisley

background image

SMALL BOXES

Photo 3 shows an electret mic preamp

similar to the one I described three years
ago (“Mic Check, A Communication
System for Cyclists,” 133, August 2001).
It’s housed in a tiny Sescom LAB-1
box, which consists of six aluminum
sheets and four extruded rails. The
LAB series of boxes excels in projects
that can tolerate their raw geek look.

Four miniature self-tapping screws

secure each end plate to the extruded
rails. Unfortunately, the threads in the
rails don’t withstand repeated disas-
sembly, so one of the screws worked
itself loose somewhere along the road.
After the next screw vanishes, I’ll fill
the threads with J-B WELD, and then
drill and tap machine screw holes.

I discovered that the cables to the

radio and headset must be anchored
securely to prevent them from rotat-
ing and yanking the wires off the cir-
cuit board. The simplest solution was
to wrap a cable tie around each wire and
pot them in a blob of hot-melt glue. A
smaller blob on the exterior provides

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

23

plate inside to ensure a smooth
surface and to reinforce the joints.

I filled the holes in the bottom

panel of Photo 1a with fiberglass
resin and laid glass cloth on the
interior. You see it in Photo 1a
before I glopped resin on the
cloth edges. Alas, the exterior
had too many surface voids and
fiber intrusions that required
another coat of resin on the
exterior, plus some sanding to
cure. It was, as they say, a learn-
ing experience: the aluminum
plate method works better for me.

Photo 1b shows the finished

project—a tool magnetizer-
demagnetizer from the
September/October 2000 issue of
Home Shop Machinist

. I mounted

most of the parts on the exterior of the
box simply because they fit better that
way. It works perfectly on tools and
also shakes the bits right off old flop-
pies, tapes, and ZIP disks.

Sometimes the project’s goals deter-

mine the package, as shown in Photo 2.
This was a force-sensor joystick for a
data-collection program that ran on a
Gameboy console. I designed the
mechanism to fit on an existing gen-
eral-purpose interface Gameboy car-
tridge. I replaced the top of the box
with a 0.25

″ acrylic sheet thick

enough for machined recesses hold-
ing a pair of force transducers and an
elastic anchor that preloaded the
sensors. The shaft is a cutoff bolt
brazed to a steel disk. Unfortunately,
after I sent it to my client, he
demonstrated that you could apply
enough force to the shaft to destroy a
Gameboy’s internal connector. Well,
we live and learn.

strain relief to protect the insula-
tion. This unit has been working
fine on my wife Mary’s bike for
three years of regular commut-
ing, so it’s good enough.

It’s entirely possible to make

boxes similar to the Sescom
products with a milling
machine and slitting saw. In the
March/ April 2004 issue of
Home Shop Machinist

, Robert

Dee explains how to build
beautiful brass and aluminum
boxes from sheet stock. They’re

labor-intensive and look rugged
enough to last forever.

TINY BOXES

Photo 4a shows an adapter between

a Maxon boom mic headset and my
Kenwood TH-F6A radio. The box must
be flush with the radio’s side and not
extend beyond the front and back pan-
els. I wanted the headset jacks on the
top surface, as well as a push-to-talk
button and a jack for a remote PTT
switch, so it must have two minia-
ture phone plugs, three miniature
phone jacks, and a push-button
switch in 1

″ × 1″ × 1.5″. I couldn’t find

a standard box with those dimensions,
so I built one.

Photo 4b shows that the box consists

of two corner pockets: one holds all the
components, and the other is a simple
cover. I cut six pieces of single-sided cir-
cuit board, milled them square, drilled
six holes, and, as you can see in Photo 4c,
used a machinist’s V-block and high-
strength magnets to hold the boards per-
pendicular while the glue cured.

My weapon of choice for small contact

areas is Gorilla Glue, a urethane adhe-
sive that firmly sticks nearly anything
to anything. It foams as it cures, expand-
ing by a factor of four, so use about a
quarter as much glue as usual. Barely
wetting the edges of the boards produced
a solid joint, but I also reinforced each
edge with a fillet of Loctite epoxy putty.
Remember to put waxed paper sheets
under the joints to keep the Gorilla
Glue off the block: it adheres to steel!

Although hand-held amateur radios

use miniature phone plugs for external
mic and speaker connections, the con-
tact wiring and jack-to-jack spacing
isn’t standardized between radios. The

Photo 3

This electret mic preamp for my ICOM Z1A fits neatly in

Sescom’s smallest LAB-1 box. Yes, one screw fell out along the way.

Photo 4a

The headset adapter for my Kenwood TH-F6A consists of six sheets of single-sided circuit board mate-

rial.

b

It’s about as small as it can be, given the required places of five connectors and a push button. The two mini

phone plugs are different sizes: 2.5 and 3.5 mm.

c

A V-block with a square bar perfectly align three boards at right

angles. Magnets hold the sheets in place until the glue cures.

a)

b)

c)

background image

around each plug on the radio side of
the board. Although it sounds cheesy,
it’s actually quite rigid and reliable.

The Maxon boom mic headset also

uses 3.5- and 2.5-mm mini phone
plugs, but with a completely different
electrical arrangement and mechanical
spacing. The wiring inside the box is
trivial, although the TH-F6 seems to
need an amplifier to boost the already
amplified mic’s output a bit more.

MECHANICS

Photo 5a shows a holder I made for a

surplus NiCd laptop battery. It powers
a bicycle lighting system, part of which
you read about in my April 2001 col-
umn. I machined an assortment of
grooves and slots in 0.25

″ Lexan sheet

stock to hold the battery in place,
with a home-brew spring latch to keep
it from sliding out.

24

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

TH-F6A puts circuit ground on the
2.5-mm speaker jack shell and uses
the 3.5-mm mic jack shell for the
push-to-talk switch, so the two jacks
must be electrically isolated from
each other. That’s why I used circuit
boards instead of aluminum sheets.

I couldn’t find panel-mount miniature

phone plugs, so I used ordinary cable-
end mini phone plugs and cut the foil
back around the mic plug hole to isolate
its shell contact. J-B WELD bonds the
plugs to the board while electrically iso-
lating them. There’s no practical way to
do this with nuts and washers, even if
you could find hardware to fit the plugs.

I inserted the plugs in the radio,

aligned the half box on the radio’s
side, and applied epoxy around the
interior of the plugs. When it cured,
the plugs were perfectly aligned with
the jacks. I then ran a bead of epoxy

Photo 5a

This bulletproof Lexan holder for surplus laptop batteries provides high-capacity, low-profile power for a bicycle

lighting system.

b—

I formed brass shim stock into battery contacts. The white silicone rubber acts as a non-corroding, no-

loose-parts spring.

c—

The setscrew adjusts the contact force through “rubberdraulic” pressure.

d—

The small brass pad

distributes force from the setscrew over a larger area. The brass nut brazed to the contact holds the whole affair in place.

a)

b)

c)

d)

Photo 6a

This serviceable and terminally ugly front panel was laser-printed and laminated. The custom meter

scales are printed on glossy photo inkjet paper.

b

A laminated photo of the WA1FFL direct digital synthesizer cir-

cuit board adorns the faceplate of this surplus box. The BNC jack and turning knob are correctly aligned, honest.

a)

b)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

25

All that’s fairly standard practice.

What are of interest are the battery
terminals, which require a sliding con-
tact exerting enough pressure for good
conduction. Commercial battery com-
partments use spring-loaded or cam-
actuated contacts with lots of fiddly
injection-molded parts. I needed some-
thing rugged enough to survive the
occasional rainstorm and easy enough
that even I could build it.

Photo 5b shows that the contacts rest

on a bed of white silicone rubber that
acts as a rustproof, no-loose-parts, short-
travel spring. I adapted the technique
from a note on page 123 of Guy Lautard’s
The Machinist’s Second Bedside Reader

,

which shows you how to use “rubber-
draulic” force to lock a slip ring.

The underside of the holder has a

setscrew to adjust the contact pressure
and a pan-head screw to hold the con-
tact in place (see Photo 5c). Photo 5d
shows the small brass pad that distrib-
utes the setscrew pressure over a large
enough area to keep it from simply
screwing into the rubber. Two turns
lock the battery in place, so the
setscrew can exert plenty of force.

Each contact fits in a small recess in

the base plate, which required some
tedious milling-machine work. The
end result, however, is an absolutely
reliable, easily adjustable contact.

PANELS

The bad old days of hideous Dymo

labels on raw aluminum boxes are
long gone. Any graphics editor, from
Photoshop and The GIMP down to
Windows Paint, can produce front
panels limited only by your artistic
ability. Photo 6a shows my limits: it’s
a functional but certainly not artistic
front panel for the GPS battery power
supply I described in “Battery Power:
Feeding the Z3801A” (155, June 2003).

The dual analog meter was intended

for an FM receiver. I pried it apart,
inkjet-printed custom scales on glossy
photo paper, and slid them under the
needles. John Tonne’s meter program
provided the basic divisions, which I
enhanced with Photoshop (tonnesoft-
ware.com/meter.html).

Just for fun, I put a photo of the cir-

cuitry inside the box on the front panel
of my WA1FFL direct digital synthesis

Ed’s an E.E., P.E., and author in
Poughkeepsie, NY. You may contact

RESOURCES

R. Dee, “High Quality Project Cases”
Home Shop Machinist

, March/April

2004.

Brian Mumford’s creations,
www.bmumford.com.

Sescom Audio Products,
www.sescom.com.

SOURCES

Gorilla Glue
www.gorillaglue.com

Loctite epoxy putty
Henkel Consumer Adhesives
www.loctiteproducts.com

INDUSTRO WELD epoxy
J-B WELD Co.
www.jbweld.net

Boxes
PacTec
www.pactecenclosures.com

signal generator (see Photo 6b). A layer
of laminating film protects the image,
with a cutout for the LCD panel. You
can laminate the printed sheet between
two layers of film to get a completely
smooth surface over the LCD, but you
must be careful to avoid trapping air
bubbles and fuzz, which explains why
I wound up with a raw hole.

CONTACT RELEASE

Although I used my machine shop

tools on some of these projects, you
can achieve similar results with basic
hand tools. Of course, if you’re look-
ing for a reason to get a milling
machine, now you have one.

When you can’t figure out how to

put something together, remember the
new generation of adhesives. They can
simplify box construction, but be sure
the pieces fit correctly. Clamp them
securely before applying the glue:
Once it’s wet, it’s too late. Now, go
forth and build boxes.

I

him at ed.nisley@ieee.org. Write
“Circuit Cellar” in the subject line to
clear the spam filter.

background image

26

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

only a minor incision (or sometimes
none at all) to inspect, diagnose, and
even repair internal problems. The med-
ical professional has progressed from
butcher to miracle worker. Nevertheless,
there’s plenty of room for improvement.

I remember Dr. Kristan coming to

my house and using his stethoscope on
me when I was sick as a child. He’d
place the cold disk on my body and ask
me to breath heavily. Connected to the
disk were black tubes that ran to his
ears. I always asked if I could listen,
and he was never too busy to let me.
Stethoscopes have not changed much
since then; most don’t require a power
source for operation. Other equipment,
however, is more complicated. From
diagnostics to database management,
computers and electronics now play
an integral role in the medical field.

If you’ve been a hospital patient, an

electronic device undoubtedly has
monitored your heartbeat. Devices
like stethoscopes monitor heartbeats

I

grew up reading Spiderman,

Superman, the Fantastic Four, and
other comics. I always seemed to be
able to scrape up the 12 cents or so
needed to stay current with new issues.
Comics were to me as baseball cards
were to most youths at the time.
Instead of dreaming of putting on pin-
stripes or red socks, I wanted colored
spandex and the superpowers that were
associated with them. Please don’t ask
me to reveal my secret identity here.
Obviously, that would give those on
the dark side an edge.

The back pages of most comic books

contain items for sale that feed upon a
child’s fantasies: magic tricks, joke
items, switchblade combs, and unusual
pets—you name it. X-ray glasses have
been a popular item for years. A small
hand-drawn picture is often the selling
point for the product. A curvaceous
female is all that’s necessary to get the
mind reeling. As you can guess, cheap
frames with cardboard lenses won’t
exactly allow you to see some-
one’s bones and anatomical points
of interest. However, the medical
industry has an arsenal of such
machinery at their beckon call.

Seeing into the body brings

with it the advantage of noninva-
sive diagnosis. Luckily for
patients, bloodletting pretty much
has been replaced as a cure-all. In
fact, many of today’s medical pro-
cedures don’t require a patient to
be opened up at all. Various endo-
scopic surgical techniques require

acoustically; other devices measure
pressure. Then there are the devices
that monitor the light modulation
resulting from the pulsing flow of
blood. This has become the prevalent
technology thanks to the photodiode,
which produces a current proportional
to the amount of light hitting its PN
junction. In this two-part series, I’ll
show you how new technology enables
healthcare professionals to monitor the
light absorbed through living tissue.

LIGHT ABSORPTION

My sisters and I rarely got to play with

flashlights as kids. But as dusk fell on
Halloween, we were given a flashlight to
guide our way between tricks and
treats. The light beam often found its
way into our mouths as we tried turning
our heads into jack-o’-lanterns. Glowing,
red cheeks seemed appropriate on All
Hollow’s Eve. When light passes through
your body, your bones, tissues, and fluids
absorb a lot of it. Comparing the intensi-

ty of the light that makes its way
out (X

OUT

) to that which comes in

(X

IN

) gives you the percentage of

light that has passed through your
body. Subtracting this percentage
from 100% gives you the percent-
age of light absorbed by the body.

Arteries and veins carry blood

throughout the body. They expand

and contract with each heartbeat.
During the systolic phase, the
heart contracts, pushing blood into
arteries, capillaries, and veins.
Blood flows back to the heart from

Absor

ption

Variable loss due to blood flow

Loss through veins and arteries

Loss through tissue and bones

Time

Figure 1

Check out how various tissues and bones can absorb light trans-

mitted through the body. As blood flows through the circulatory system, it
changes density because of the heart’s pumping pressure. This change also
changes the absorption rate of light, effectively modulating the light absorp-
tion. The total light absorption is a combination of modulated and constant
absorption, which is similar to a small AC noise riding atop a DC voltage.

Light-to-Frequency Conversion (Part 1)

FROM THE BENCH by Jeff

Bachiochi

TAOS l

i

ght-to-frequency converters are becomi

ng i

ncreasi

ngl

y popul

ar amongst desi

gners

whose appl

i

cati

ons requi

re l

i

ght-sensi

ng capabi

l

i

ti

es. One reason why i

s because desi

gners

want di

gi

tal

output rather than anal

og. In thi

s col

umn, Jef

f expl

ai

ns why a

TAOS

TSL230R i

s

the perfect part for the pul

se oxi

meters used i

n hospi

tal

s.

TSL230R-Based Pulse Oximeter

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

27

the veins during the diastolic (resting)
phase. As the arterial system expands
and contracts, it affects the level of
light absorption. This adds an AC
component to the background absorp-
tion (or DC level), as you can see in
Figure 1. The DC and AC levels might
change drastically depending on where
on the body the measurements are
taken. Earlobes and fingers used most
often because they are relatively thin
and easily accessed.

Using a photodiode to measure intensi-

ty requires fairly high amplification. Care
must be taken to minimize the noise in
the external circuitry necessary to cre-
ate an analog signal large enough to be
read with an A/D converter. A light-to-
frequency converter can replace most of
the sensitive circuitry as the light-mon-
itoring device for the sensor application.

TAOS

In 1999, Texas Advanced

Optoelectronic Solutions (TAOS)
acquired licensing to produce and mar-
ket the optoelectronic family of sensors
from Texas Instruments. Its mission
has been to develop and manufacture
semiconductor devices combining
photodetectors with precision mixed-
signal functionality to give you a light-
sensing solution with improved per-
formance and design simplicity. TAOS
products include light-to-voltage, light-
to-frequency, linear-array, ambient,
color, and color-reflective optosensors.

For this project, I chose the TSL230R

for its sensitivity and wide spectral

response. This programmable light-to-
frequency converter has an array of pho-
todiodes and a current-to-frequency con-
verter in an eight-pin package. All the
I/O is TTL-compatible, so analog isn’t
involved. This removes any concerns
associated with small analog signals.

Although a photodiode array isn’t

mentioned in the TSL230R datasheet,
you can see a 10 × 10 array on the device
(see Figure 2). Two inputs to the
TSL230R are used to select the device’s
sensitivity. Selections include 1×, 10×,
and 100×, which leads me to surmise
that these selections choose the array
size of the photodiodes. Using the 100×
selection, device responsiveness is given
as 770 Hz/µW/cm

2

. The spectral band-

width covers the two areas of interest
pertaining to this project: red (600–
700 nm) and infrared (800–940 nm).
Although the frequency out is directly
proportional to the light intensity,
total darkness is not represented by zero
frequency. The device always produces
output. The minimum might be approx-
imately 1 Hz. At 100 µW, the maximum

Figure 2

This eight-pin sensor is molded in clear

plastic. It has a visible array of photodiodes. Mode
inputs to the device enable an array of one, 10, or 100
photodiodes to select the sensitivity.

background image

28

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

frequency is approximately 100 kHz
(using the 100× mode—the complete
array). As expected, the 10× and 1×
modes produce this frequency at 10× and
100× the light level of the 100× mode.

The eight-pin TSL230R consists of

the photodiode array (with its two sensi-
tivity inputs) with a current-to-frequency
converter. Two other inputs select a divi-
sor for the output frequency. This leaves
connections for power, ground, frequen-
cy output, and an output enable input.

DESIGN PARAMETERS

A heart rate in the vicinity of 70 beats

per minute (bpm) is considered normal
for an adult. A newborn’s heart rate is
typically around 120 bpm. Your heart
rate slows to approximately 50 bpm as
you enter your golden years. When
exercising, your heart rate may dou-
ble. (Sustained exercising need only
elevate the normal heart rate by rough-
ly an additional 50% to be effective.)
Accounting for all of this data, I’d
limit what could be considered good
readings to, say, 50 to 200 bpm.

Figure 3 shows the circuit I used for

experimenting with this project. It may
be overkill for the end product, but I
can have the hardware serial port on
the microcontroller output some data
for analysis. I’ll consider using a small-
er device when I don’t need to log any
data. Although it’s possible to drive an
LED directly from the microcontroller’s
I/O, any change in voltage will have a
different effect on the current through
each LED because the LEDs have differ-
ent drops. I chose to use constant cur-
rent drivers for the two LEDs. This
automatically takes into account the
different drops for the red and IR LEDs.

The TSL230R and LEDs are a sensor

unit connected to the electronics with
a 10-conductor ribbon cable (see Photo 1).

Figure 3 shows how it’s split. This
allows the sensor to connect to vari-
ous prototype circuits.

I found a piece of plastic conduit

that fit over my finger after I slotted
it. By slotting all but a 0.25

″, it acts

like a clothespin and holds on firmly to
my finger without being uncomfortable.
The TSL230R sensor is glued into a
square hole placed on one side of the
conduit. The red and IR LEDs are forced
into two drill holes directly across the
diameter from the sensor. Square pin
headers make all the connections easier.

SMT and flex circuitry would be per-

fect for this application. I did not experi-
ment with mounting the LEDs and sen-
sor on the same side of the conduit.
Although this becomes more of a reflec-
tive illumination, it avoids having wires
span two moving objects, which is a
potential mechanical point of failure.

Because I used a red LED and an IR

LED, the circuit can actually measure
the oxygen content of your blood in
addition to your heart rate. To measure
a heart rate, you must calculate the
time between the maximum (or mini-
mum) excursions of the AC portion of
the light absorption output. Both the
red LED and the IR LED can provide
the light source for the TSL230R.
However, the hemoglobin in red blood
cells picks up oxygen molecules in the
lungs and becomes a brighter shade of
red, which will absorb less red light.

Figure 4 shows the difference in

light absorption between oxygenated
and deoxygenated blood at various
wavelengths. Notice that for infrared
there is little difference in the absorp-
tion. At lower wavelengths (especially
the red region), there is a significant

Figure 3

The lower circuit shows the sensor module in Photo 1. A ribbon cable connects the sensor unit to the

upper circuit located on the bench for easy experimenting. I didn’t include the level-shifting circuitry that makes the
TX sample data available to a PC.

Figure 4—

Study the absorption relationship of oxygen lev-

els in the blood for the red and IR wavelengths. Notice how
the oxygen level affects the absorption rate at the red wave-
length while it remains almost constant at IR wavelengths.

10

(Red)

660 nm

(Infrared)
910 nm

Hbo

2

Hb

0.1

600

700

800

900

1000

Wavelength (nm)

Photo 1

A slot is cut most of the way through a small

section of plastic electrical conduit, which houses both
the TSL230R sensor and the red and IR LEDs. The
TSL230R registers the amount of light passing through
the inside diameter of the conduit, which, in this case,

is

through a victim’s, eh, patient’s, finger.

background image

Schematic and PCB Layout

• Powerful and flexible schematic capture.
• Auto-component placement.
• Rip/entry PCB routing.
• Polygonal gridless ground planes.
• Library of over 8000 schematic and 1000 PCB foot prints.
• Bill of materials, DRC reports and more.

Mixed Mode SPICE Circuit Simulation

• Berkeley SPICE3F5 simulator with custom extensions for

true mixed mode and interactive simulation.

• Six virtual instruments and 14 graph based analysis types.
• 6,000 models including TTL, CMOS and PLD digital parts.
• Fully compatible with manufacturers’ SPICE models.

Proteus VSM - Co-simulation and debugging for

popular Micro-Controllers

• Supports PIC16 & PIC12, AVR, 8051, HC11 and ARM micro-

controllers.

• Co-simulate target firmware with your hardware design.
• Includes interactive peripheral models for LED and LCD

displays, switches, keypads, virtual terminal and much,
much more.

• Provides source level debugging for popular compilers

and assemblers from HiTech PICC, Crownhill, IAR, Keil
and others.

R4

www.labcenter-electronics.com

EASY TO USE CAD TOOLS AT FANTASTIC PRICES

MicroChip PIC 18

• Supported models of the PIC 18 includes PIC18F242,

PIC18F252, PIC18F442, PIC18F452, PIC18F248, PIC18F258,
PIC18F448 and PIC18F458.

Basic Stamp BS1 and BS2

• Proteus VSM for BASIC Stamp contains everything you

need to develop and simulate designs based around the
BASIC Stamp.

• See examples in downloadable Demo at

www.labcenter-electronics.com

“I finished my first design, schematic and PCB in one day.”
“What a great tool! I love it.”

DAN GILL

“For the cost of the software compared to the productivity gains,

I consider Proteus to be pivotal in the commercial viability

of my company and by far represents the best value for money
of anything Tempus possesses.”

ROB YOUNGS, Tempus Consulting

“PROTEUS stands out as the best all-round program in this review.

Other programs reviewed have strengths in the pcb design process,
Proteus maintains a constant high level of capability throughout.
Whether a schematic, user-friendly interactive routing, config-
urable autoplacing, competent autorouteing, or a combination
of the above, PROTEUS handles everything very well.”

Electronic & Wireless World CAD Review Roundup

FREE

DOWNLOADABLE

DEMO

Save Time. Save Money.

Proteus Starter Kit – $199 • Complete Systems from $449

“This is clearly superior in every respect.”

Virtual System Modelling

SYSTEMS
INC

.

Tel: 905•898•0665 info@r4systems.com

background image

30

Issue 173 December 2004

www.circuitcellar.com

CIRCUIT CELLAR

®

difference. You can calculate the level
of oxygen by comparing the absorption
outputs of each light source separately.

AC VERSUS DC

In order to be successful, you must

be able to measure the AC component
of the sensor’s output. What can you
expect as a signal? Photo 2 shows the
TSL230R’s output. The vertical scope
cursors show the minimum and maxi-
mum excursion of the frequency output

(with the sensor on a finger). In /100
mode, a full cycle (DC portion) meas-
ures approximately 3.5 ms, and the AC
portion is approximately 215 µs. In /1
mode, a 35-µs cycle has only 2 µs of AC.

There are two methods for taking

samples. The device’s frequency output is
directly related to light intensity falling
on the sensor, so one cycle is sufficient as
a sample. In the first case, you need only
measure the period of one cycle to obtain
a sample. Keep in mind that the output

in /1 mode is a period and not a symmet-
rical square wave as in /2, /10, and /100
modes. This means that one must meas-
ure a full cycle in /1 mode as opposed to
a minimum half cycle in the other divid-
ed modes. (Or at least be sure you are
measuring the right half.) Although the
percentage of AC to DC is the same with
all output modes, a 1-µs clock is use-
less in this case with a /1 output (in the
aforementioned example). The most
desirable output is one that approaches
the sampling rate but doesn’t create tim-
ing interference with other functions.

Another way to look at data would be

to average the output over the duration
of the sampling period. The TSL230R
does this for you to some extent. For
instance, /100 mode gives an output
equal to the sum of 100 cycles.
However, using this method, you want
this sum to be for the duration of the
sample period and not a certain num-
ber of cycles. In this case, you want
just the opposite of the first method.
You want the fastest output you can
count, so that the DC (and the AC)
portion will have the largest count
possible. Because the AC is roughly
6%, you can expect an AC count of

±3

for every 100 counts of DC. Using the
same numbers as the first method, the
35-µs output would have approximately
880 counts in one sample period. Using
the /100 output of 3.3 ms would have
only eight counts!

DIGITAL CONNECTION

Unlike Analog sensors, the

TSL230R doesn’t require an A/D con-
verter to get values into a microcon-
troller. The TTL-compatible output
makes a direct interface possible to a
microcontroller without the need for
analog signal conditioning. If the sen-
sor is at any distance from the rest of
the electronics, a shielded cable isn’t
necessary because low-level noise sen-
sitive signals aren’t used. Applying the
sensor’s frequency output to a micro-
controller’s external interrupt input
can simplify period or pulse counting.
Although I hope the final circuit won’t
need any active mode control for the
TSL230R, having total control of the
mode input pins makes experimenting
much easier. A PIC running at 4 MHz
has a 1-µs execution cycle, which is a

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

31

SOURCE

TSL230R Light-to-frequency converter
TAOS, Inc.
www.taosinc.com

RESOURCES

Omimeter.org, “Principles of Pulse
Oximetry Technology,” 2002, www.
oximeter.org/pulseox/principles.htm.

TAOS, Inc., “Pulse Oximetry,” www.
taosinc.com/downloads/pdf/pulse.pdf.

———“TSL230R, TSL230AR,
TSL230BR: Programmable Light-to-
Frequency Converters,” TAOS048A,
2004.

nice whole number to work
with for timing. A 16-bit
timer using this 1 µs as the
timebase can count up to
~65 ms before rolling over.

The timer’s count is

directly related to the irra-
diance level. The smaller
the count, the higher the
frequency and the more
light falling on the sensor.
To make sense of this, you
need to grab samples at a
fixed rate (at least two
times faster than the fre-
quency of interest –
Nyquist). For 200 bpm, or
3.3 bps, that would be approximately
7 Hz. I used a sample rate of 32 Hz
(31.25 ms) for this project because it
fits nicely into this timer’s range.

Timer1’s overflow is set to 31.25 ms

by loading the timer’s count with a
constant at each overflow. Because of
interrupt latency and instruction cycles
for the interrupt routine code up to the
point where the timer is loaded and
begins counting, the actual value placed
in the counter will be less than what’s
required for 31,250 counts. The timer
counts up to overflow, so the required
value of counts must be subtracted
from the rollover count (or the value
complemented). A simulator (with a
stopwatch or instruction counter) is
helpful for determining the exact value
necessary to obtain accurate timing.

The frequency of the TSL230R will

increase as more light falls on its

light-sensitive array. Although the
sensor doesn’t produce zero frequency
output for zero irradiance, the output
is linear. Using the most sensitive
mode, the maximum frequency could
be 100 kHz (130 µW/cm

2

at 640 nm)

with a minimum frequency of approxi-
mately 1 Hz. This maximum frequency
equals a Timer1 count of 10 with a
Timer1 overflow at a minimum fre-
quency because the 16-bit timer over-
flows at approximately 31 ms.

The only way to achieve a minimum

frequency is with little or no irradi-
ance. A Timer1 overflow can indicate
an error or too little light. Too much
light is a bit trickier to detect. A count
of 10 would be impossible to detect in
this case because the code execution
for the interrupt lasts longer than the
10 µs for a period. So, counting edges
(periods) would be missed and the

count wouldn’t be accu-
rate.

The instantaneous sam-

pling approach requires
the frequency to be meas-
ured once each sample
period. This is achieved by
enabling the external inter-
rupt each time Timer1
overflows (31.25-ms sam-
pling timer). After the
external interrupt is
enabled, Timer1’s count is
sampled twice on each of
the next two rising edges
of the TSL230R frequency
output. The difference in
the two counts equals the
period of the output in

Jeff Bachiochi (pronounced BAH-key-
AH-key) has been writing for

Circuit

Cellar since 1988. His background
includes product design and manu-
facturing. He may be reached at jeff.
bachiochi@circuitcellar.com.

microseconds for that
sampling period.

The sampling sum

approach uses Timer1’s
overflow (31.25-ms sam-
pling timer) to read the
accumulated period count
and then flush it every
sample period. The external
interrupt is always enabled.
Each rising edge of the
TSL230R’s frequency out-
put adds one to the num-
ber of periods. The accu-

mulated count at each sam-
ple time is the sum of all
the periods output during

that sample time. This is essentially a
period average for that 31.25 ms.

SAMPLING

Next month, I’ll describe the process

of choosing the appropriate mode and
making sense out of the samples. In the
meantime, study Figure 5, which shows
some TSL230R samples. I used the on-
board UART to dump each sample in a
five-digit decimal number (followed by a
CR). I imported these into Excel and
used the graphing function to show you
what’s going on. I’ll use this to deter-
mine how to manipulate the data into
an indication of beats per minute.

I

TSL230R Samples

4,100

4,000

3,900

3,800

3,700

3,600

3,500

3,400

1

33

65

97

129

161

193

225

257

289

321

32 Samples per second

P

e

ri

od (microseconds)

Figure 5

This Excel chart displays imported sample values over time. Samples of the

output frequency (30 samples per second formatted in microseconds) were sent out the
serial port and captured to a file by HyperTerminal.

Photo 2

The TSL230R’s frequency output displayed on my oscilloscope

shows a slow frequency jitter marked by the vertical cursors. The output
frequency shifts with the varying amount of light absorption because of
the blood pulsing within the light’s path.

background image

R

®

DESIGN CONTEST

2004

Flexibility, programmability, affordability, and applicability—

these are the ties that bind the various members of the Atmel
AVR microcontroller family. Last winter, designers learned this
firsthand as they began short-listing parts for use in projects
destined for entry in the Atmel AVR 2004 Design Contest. For
many of the eager entrants, the hardest part of the contest
turned out to be deciding which first-rate AVR part was the best
option for their designs. Just ask Michal Sieluzycki, whose
Color TFT LCD Controller won him the Grand Prize. Like sever-
al other entrants, he was so impressed with the various mem-
bers of the AVR family that he actually put two of them to work
in his prize-winning design.

Scores of other designers also found the right parts to create

solid designs. The result was a stack of entries that kept the
judges busy straight through the summer. The fierce competi-
tion left 12 exemplary projects at the top. Congratulations to all
of the winners!

Grand Prize

Color TFT LCD Controller

Many of the affordable, small, color LCDs on the market are con-
trolled by particular chips that usually aren’t available to the pub-
lic. The Color TFT LCD Controller is a creative solution that uses
two AVR microcontrollers to generate the signals needed to con-
trol a color TFT LCD. A 160 × 240 dot Sony ACX705AKM is used
as the display. This project is inexpensive and flexible—it may be
used as an intelligent LCD controller or a stand-alone device. An
ATmega8515 microcontroller, which was chosen for its efficiency,
collects the color pixel data from static RAM and controls the LCD
by generating digital CRT video signals. An ATmega128 serves as
the second microcontroller. It was selected for its abundance of
interfaces and large flash memory, which is used to store fonts and
bitmaps. The ATmega128 interprets graphic commands received
via RS-232 (or any other interface), and stores the resulting pixels
in the static RAM shared by the ATmega8515.

M ichal Sieluzycki

U.S.

misiek@cox.net

WINNERS ANNOUNCEMENT

background image

First Prize

Fuel-Consumption Gauge for Your GM Car

This low-cost project measures fuel consumption in real time. An
ATmega8515 microcontroller collects vehicle speed and airflow data
from the vehicle’s engine computer using the SAE J1850 VPW bit-
serial bus, which is one of the on-board diagnostic buses required by
the OBD-II standard. A modified off-the-shelf electronic tachometer
is used as an analog display to show the consumption rate in miles
per gallon. Only a few extra components are necessary for this effi-
cient project, including transistors, diodes, resistors, and capacitors.
Special automotive bus interface chips are unnecessary.

Bruce Lightner

U.S.

lightner@lightner.net

®

DESIGN CONTEST

2004

Winners Announcement

Winners Announcement

Complete entries are available at

www.circuitcellar.com/avr2004.

Second Prize

AVRcam

The ATmega8 microcontroller-based AVRcam is a
stand-alone image-processing engine that’s well
suited for robotics applications. The impressive
AVRcam can track eight objects of eight different
user-defined colors at 27 frames per second. The
compact, low-power design provides a high-per-
formance system that enables you to see your
mobile robot’s environment. A user interface dis-
plays the following image information in real time:
the number of currently tracked objects as well as
the color, center point, and bounding box of each
object. A PC-based application provides a platform
to configure the system. In addition, the application
allows you to take photographs with the AVRcam.

John O rlando and Brent Taylor

U.S.

john@jrobot.net

background image

Sing-Along

Sing-Along is a musical tone memory game in the tradition of the popular ’80s game Simon (Hasbro). Designed for one to three players,
the ATtiny12 microcontroller-based device plays a random sequence of notes, and then listens for the player(s) to mimic the sequence
by singing or humming. If the player does not respond within the allotted time or sings an incorrect note, then a “lose” sound will play.
If the player correctly sings the entire 16-note sequence, then a “win” tune will play. After each correct answer, the device plays an even
longer sequence. LEDs indicate which player’s turn it is. They’re also used to follow the notes as they are played or sung. The microcon-
troller’s analog comparator is fed by an analog front end, which processes the input from an electret microphone. An automatic gain con-
trol loop enables the ATtiny12 to detect inputs over a wide range of sound levels.

Richard W otiz

U.S.

dick601@mystics.org

’Net Radio

The ’Net Radio lets you to listen to MP3 streaming radios that are broadcast over the Internet without a PC. MP3 streams are received
through an Ethernet link, decoded by an on-board MP3 decoder, and then output as audio through a 3.5-mm stereo jack. The user-
friendly design includes easy-to-use switch buttons and a color LCD. The ’Net Radio is designed around an ATmega64L RISC microcon-
troller that provides ample memory. The ATmega64L was also chosen for its low power consumption, which enables the ’Net Radio to
be interfaced with low-power commercial devices.

Bertrand A chard

France

ba@cykian.net

FM Receiver

The user-friendly FM Receiver monitors polar orbiting weather satellites operated by the National Oceanographic and Atmospheric
Administration (NOAA). It tunes from 60 to 800 MHz with an IF bandwidth of 50 kHz. The IF bandwidth was chosen because it’s opti-
mal for the NOAA polar orbiting weather satellites; however, the FM Receiver also receives narrowband FM, television audio, and com-
mercial FM stations. An ATmega8-16PI microcontroller is the heart of the high-performance receiver, ensuring good frequency stability.
The MCU also enabled the inclusion of a tuner with a built-in controller, which provides fast tuning. The project features one of each of
the following components: tuner, ceramic filter, second mixer, second oscillator, IF filter, audio integrated circuit, keypad, LCD, and power
supply.

C harles Schee and Karen Lynn Steelm an

U.S.

cschee@lakewebs.net

Honorable Mention

Third Prize

PRO-I/O Breadboard Development System

Whereas in the past breadboarding was used to do little more than
debounce a few push buttons and display a couple hexadecimal
characters, the innovative PRO-I/O Breadboard Development
System simulates various input and output devices typically used
in today’s designs. These devices include switches, push buttons,
LEDs, a 2 × 16 character LCD, a small serial terminal, a frequen-
cy generator, a frequency counter, and two voltmeters. The high-
ly integrated ATmega16 microcontroller is the heart of the project.
The system includes a PC user interface and a USB interface.

Kenneth Lum ia

U.S.

klumia@adelphia.net

Complete entries are available at

www.circuitcellar.com/avr2004.

Winners Announcement

Winners Announcement

background image

®

DESIGN CONTEST

2004

Honorable Mention

A 32-Channel Digital R/C Servo Controller

This forward-thinking project uses a single controller to drive more than 30 radio-controlled (R/C) servos, making it easy to design sophis-
ticated robots. The task of generating a large number of stable PWM control signals to drive the servos has been eliminated. A dedicat-
ed serial servo controller board handles multichannel PWM signal generation while being controlled by simple commands issued on a stan-
dard serial UART. The combined strengths of an FPGA and an ATmega8515L microcontroller make this project a unique and powerful
solution for robotics applications.

Eric G agnon

Canada

egagnon@digitalcreationlabs.com

Stealth Keyless Entry System

The AT90S2313 microcontroller-based Stealth Keyless Entry System is a robust solution to a common security problem. Typical 10-button
keyless entry pads that are controlled by numerical entry codes can be risky over time. Dirt from fingers deposited on the keypad cou-
pled with the natural wearing of the dye on the keypad make it relatively easy to determine which keys are pressed, and therefore eas-
ier to discern the entry code. The Stealth Keyless Entry System uses a modified doorbell to act as a hidden entry system. When pressed
normally, the doorbell rings as expected. But when the entry code (Morse code) is entered, the doorbell does not ring, and the garage
door is unlocked. The MCU deciphers the code, compares it to the master code stored in EEPROM, and then sends the command to open
the garage door.

D avid Brow n

U.S.

k8ax@wowway.com

A Differential Scanning Calorimeter

Commercial differential scanning calorimeters used to measure enthalpy are often too expensive for colleges and universities. Although
this project doesn’t provide the extremely high performance of the commercial devices, it is a remarkably low-cost alternative that is more
than sufficient for classroom use. The goals of the project were to create an instrument that has a wide enough temperature range to
demonstrate measurement, a fairly accurate temperature resolution, and decent accuracy in measuring enthalpy energy. Most important-
ly, it had to be rugged to withstand use in the lab. An ATmega8 microcontroller handles temperature control and measurement functions.
A PC serves as the user interface and display.

Brian M illier

Canada

brian.millier@dal.ca

USB Audio Card

The USB Audio Card project offers a better solution than going through the hassle of adding a new PCI audio device to a PC. A high-
speed USB and a powerful ATmega162L-8PI microcontroller are the keys to an easier upgrade. A USB B-type-to-A-type cable is used to
connect the audio card to the PC. Windows pretty much handles the rest of the work. With earphones connected to the card, you can
listen to MP3 and WAV files.

H avent C hen

China

haventchen@hotmail.com

AVR Electronic Metronome

A metronome is a device musicians use to maintain tempo. It generates a clicking sound at a steady rate that is set by the user. Traditional
mechanical metronomes use a windup spring and a dual-pendulum arm to produce the clicks. Electronic metronomes offer additional func-
tionality, such as programmable beats per measure, measure counting, and distinctive sounds for the first beat of the measure. But the
sound of electronic metronomes can be grating. The ATmega16 microcontroller-based AVR Electronic Metronome improves upon the
commercial competition with a rich set of sophisticated features and tuneful digital sound options.

M ichael Kirkhart

U.S.

mkirkhart@earthlink.net

Complete entries are available at

www.circuitcellar.com/avr2004.

Winners Announcement

Winners Announcement

background image

36

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

information was the arbitrary “I was
here” type of data.

The sheer amount of analysis need-

ed to solve a single problem from this
information was unacceptable. Each
analysis took at least half a day, and
there were usually several to do each
day. This forced me to come up with a
smarter way to approach code analy-
sis. What I needed was a technique to
produce useful information without
requiring constant physical I/O, unop-
timized code, or special runtime envi-
ronments. Moreover, the technique
could not add burden, complexity, or a
learning curve to the already time-
consuming task of simply getting the
job done.

I present such a technique in this arti-

cle. The requirements for the technique
are as follows: the solution must record

No harm’s done to history by making it
something someone would want to read.
—David C. McCullough

N

ot long ago I was placed in charge

of a large amount of distributed legacy
code. I hadn’t written any of it at that
point. The previous team had just dis-
banded, and portions of the code
were a decade old. To make things
more interesting, much of the code
was not performing correctly in terms
of speed and reliability. Many new fea-
tures had to be added quickly to some
poorly understood areas of the code.

Typical initial approaches to investi-

gating such problems would involve
adding instrumentation such as print
statements or using some form of a
debugger or emulator. Unfortunately,
these can cause more problems than
they can identify, especially for time-
critical and embedded applications.
Both approaches require specific
resources such as an output channel
for the print statements and unopti-
mized code and hardware/software
access for the debugger and emulator.
These approaches will cause delays
and timing abnormalities simply by
using them. They generally show too
much low-level or arbitrary detail. In
fact, each section of the code I needed
to look at already logged events that
could be examined after the fact, but
there was no way to effectively collect
them all together. All of the available

the timing and identification of signifi-
cant events; the solution must be able
to remain in place and operate regard-
less of the state or phase of the project;
the solution must not affect overall sys-
tem performance; and the result must
be easily and instantly understandable
without special software or skills.

SOFTWARE SCENARIO

Let’s take a look at an example.

Three software entities (processes,
threads, objects, etc.) will send a mes-
sage in round-robin fashion with an
internal state machine transition occur-
ring after each message. At the comple-
tion of a cycle, a timer is set and waited
for in the first software entity. The
entire cycle repeats on the timeout in
the first entity.

This isn’t a severely complicated

FEATURE ARTICLE

by Scott McOlash

Visualizing History

Software can be challenging to understand, especially when it doesn’t behave as expect-
ed. Traditional debugging tools and techniques provide insight into what your code is doing,
but only at a low level. Fortunately, Scott can teach you a better way to visualize the high-
level behavior of software systems.

Record and View High-Level Software Behavior

Listing 1

—This is an example of a simple text log. The format is arbitrary and can be easy to read, but it

has no indication of time aside from the sequence of the lines and cannot be easily reused by other soft-
ware tools.

A sent message 1 to B

A transitioned from state S1 into state S2

B received message 1 from A

B sent message 2 to C

B transitioned from state S into state S

C received message 2 from B

C sent message 3 to A

C transitioned from state S into state S

A received message 3 from C

A set ‘timer’ for duration of 1s

A transitioned from state S2 into state S1

A received timeout event from ‘timer’

A sent message 1 to B

A transitioned from state S1 into state S2

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

37

example, but it offers some interesting
actions that can be used to drive the
design forward. The events in this sce-
nario could be described in the follow-
ing way: A sends message 1 to B as it
transitions from state S1 into state S2;
B receives message 1 from A and
sends message 2 to C as it self-transi-
tions back into state S; C receives
message 2 from B and sends message 3
to A as it self-transitions back into
state S; A receives message 3 from C
and sets timer to 1 s as it transitions
from state S2 into state S1; and A
receives a timeout message from the
timer and sends message 1 to B as it
transitions into state S2.

TRACE BUFFERS

A trace buffer is generally some form

of in-memory buffer that replaces an
output stream otherwise used with
print statements. The output of the
data held in a trace buffer can be
scheduled for a safe and convenient
time, if ever, in the interest of having
predictable and reliable system per-
formance. Trace buffers can come in
many forms, from simple lines of text
to ring buffers of specialized data
structures. What they all have in com-
mon is that they’re a fast way to log
information. Furthermore, they are
completely internal to a software sys-
tem (no immediate I/O).

Using trace buffers is a good way to

start understanding and debugging the
behavior of a software system. It allows
abstract comments and “I was here”
statements to be placed in a historical
log that can be used later. Unlike a
standard print statement, trace buffers
can generally remain in a finished prod-
uct without affecting the system’s per-
formance or appearance because output
isn’t required (neither physical nor visu-
al). This allows a best practice of log-
ging significant events to remain in
place for future development, analysis,
and debugging.

One simple approach to creating

and saving history data is to create an
array of N fixed length strings, and
then use a sequence number to index
them modulo N. This would provide a
cheap circular buffer solution while
avoiding the memory management
and performance issues of more

Listing 2

—I’ve used this function on several different platforms to provide high-resolution timestamps for log-

ging events and measuring application performance. The basic idea behind the code is to provide a single
code interface to get the system time and return it in a consistent format.

#ifdef WIN32

/* windows headers – must link with ‘winmm.lib’ */

#include <windows.h>

#include <mmsystem.h>

#else

#ifdef VXWORKS

/* vxWorks headers */

#include <time.h>

#include “drv/timer/timerDev.h”

#else

/* unix headers – Linux may need to link with –lrt */

#include <sys/time.h>

#include <time.h>

#endif

#endif

double timestamp (void)

{

double value = 0.0;

#ifdef WIN32

LARGE_INTEGER frequency;

LARGE_INTEGER counter;

QueryPerformanceCounter (&counter);

QueryPerformanceFrequency (&frequency);

if (frequency.QuadPart == 0)

{

timeBeginPeriod (1);

value = timeGetTime ();

timeEndPeriod (1);

}

else

{

value = (double) counter.QuadPart / (double)

frequency.QuadPart;

}

#else

struct timespec ts;

clock_gettime (CLOCK_REALTIME, &ts);

#ifdef VXWORKS

double offset = ((double) sysTimestampLock ()) /

(sysTimestampPeriod () * sysClkRateGet ());

ts.tv_nsec += (long) (1.0E+9 * offset);

#endif

value = (double) ts.tv_sec + ((double) ts.tv_nsec * 1.0E-9);

#endif

/* return the timestamp */

return (value);

}

Listing 3

—This version of the simple text log is improved by the addition of timestamps, but it still has an

arbitrary format and isn’t practical to parse or reuse by other tools.

0.000000 A sent message 1 to B

0.000010 A transitioned from state S1 into state S2

0.000020 B received message 1 from A

0.000030 B sent message 2 to C

0.000040 B transitioned from state S into state S

0.000050 C received message 2 from B

0.000060 C sent message 3 to A

0.000070 C transitioned from state S into state S

0.000080 A received message 3 from C

0.000090 A set ‘timer’ for duration of 1s

0.000000 A transitioned from state S2 into state S1

1.000000 A received timeout event from ‘timer’

1.000010 A sent message 1 to B

1.000020 A transitioned from state S1 into state S2

background image

38

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

dynamic methods. Some mem-
ory efficiency can be addressed
by choosing the length of his-
tory to be saved (N) and the
maximum length of the string
used for a history entry.

At this point, the example

scenario could be encoded as
simple, unstructured text. All
of the message send and
receive events, state machine
transitions, and timer actions
could be shown as individual
entries in the log (see Listing 1).

I was lucky in that the processes I

was investigating already incorporated
a form of internal trace buffer that held
a lot of interesting data. The flaw in the
data was that the only thing that gave
it a historical order was a crude time-
stamp that changed once every 16 ms.
This prevented me from merging log
data from any two logs because there
would be no clear order in the result-
ing list. I was still stuck.

TIMESTAMPS

“Time is what prevents everything

from happening at once,” Dr. John A.
Wheeler, a physicist and father of the
black hole, once said. The first step in
understanding significant events is to
know when and in what order they
occurred. You must add the dimension
of time to your trace data. Without a
notion of time and sequence in your
data, you can only know the order that
events were logged but not their concen-
tration and rate. In a circular buffer, you
can’t even assume the order because of
eventual wraparound.

Most systems keep some sort of

time, and almost all that do can be
made to present time in a high-resolu-
tion manner. The systems that do not
keep time at all (e.g., simple embedded
controllers) can keep a simple sequence
number instead of a real measure of
time. This sequence number would
keep the events from appearing to
occur at the same time and thus satisfy
Dr. Wheeler’s definition.

For systems that keep time, the

default timekeeping resolution of
most portable code is either 1 s or one
tick of the system clock. Unfortunately,
this may not have enough resolution
to uniquely represent each event

recorded on a system, so you quickly
degenerate back to the appearance of
multiple events occurring all at once.

The maximum resolution of time

measurement on a system is based on
the combination of the available hard-
ware and the software. The hardware
may consist of some combination of a
real-time clock, kernel heartbeat, and
countdown registers. The software used
to measure time may include operating
system-specific calls, POSIX interfaces,
and custom drivers. Many common
system configurations allow for high-
resolution time measurement, although
there are many ways to obtain it and
some are more complex and non-
portable than others.

The standard POSIX function for

returning the current time, relative to
January 1, 1970, is clock_gettime.
This function is generally of sufficient
resolution on full-featured *nix systems
such as Linux on Intel, Solaris on Sparc,
and IRIX on MIPS. Other system types
also provide this interface without the
underlying accuracy. For example, a
default build of the VxWorks 5.0 PPC
kernel provides a clock_gettime
function with resolution of one kernel
tick at one-sixtieth of a second.

Windows, on the other hand, approach-

es time in a different manner. The POSIX
interface is not available, but a high-reso-
lution timing service is available via the
Windows-specific QueryPerformance-
Counter

and QueryPerformance-

Frequency

APIs. Rather than the time

relative to January 1, 1970, Windows
returns the time since the last operat-
ing system restart.

Custom embedded systems are gen-

erally equipped with a mechanism
similar to that of Windows in that

they generally measure time
or events since the last system
restart. The resolution of time
measurements on those sys-
tems is completely defined by
the implementation of the sys-
tem and cannot be specifically
addressed here.

Although these systems are

evidently different in how

they measure time, a high-res-
olution representation that is
consistent across measure-
ments is key to logging unique

events. A timestamp of this nature
added to each log entry will make
each entry unique, sortable, and easy
to combine with other log data that is
based on the same clock.

An example of a multiple-platform,

high-resolution timestamp function is
shown in Listing 2. The code includes
an enhancement for VxWorks on the
PPC to provide resolution much high-
er than a single kernel tick. This tech-
nique can be used with any hard-
ware/software combination that uses
a high-resolution decrement counter
to drive the kernel tick.

The entries in the previous trace

buffer example now can be enhanced
to use these high-resolution time-
stamps. Listing 3 is an example. Note
that the timestamps are entirely ficti-
tious for this example.

At this point I was able to combine

any number of logs that were collect-
ed with a consistent clock. Lacking
precise time synchronization across
multiple computers, I was left with
the ability to see the timing relation
of all of the log entries made only on a
single computer. Not perfect, but still
pretty good. However, there was still
too much arbitrary data left in the logs.

SIGNIFICANT EVENTS

A significant event is anything you

need to think about or be concerned
about now or in the future. During
debugging, this includes many things
that may have little value in the
future, so it’s important to be able to
easily add arbitrary text markers and
messages to your log data.

Even more important is the ability

to add markers to your log that indi-
cate specific, system-critical events.

Entry type

Additional data

Event send/receive

Event ID, event source, and event destination

State transition

Event ID, source, and destination state

Timer set

Timer ID and timeout value

Timer cancel

Timer ID

Timer timeout

Timer ID

Mutex take

Mutex ID

Mutex give

Mutex ID

Arbitrary text

Reasonable, succinct text message

Table 1

—In addition to the event type and a timestamp, I find it useful to

include data specific to each type of event being logged. This table shows a
set of useful events I chose to record and the data that can be added to
make these events truly informative.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

39

These would include sending
and receiving messages, state
machine changes, timer events
(set, cancel, and timeout), and
mutex/semaphore access (give
and take). Timing analyses can
be based on a set of user-defined
markers that present a resource
name and a timestamp. Other
useful entries could be func-
tion entry/exit/error markers,
but in practice these can easily
become overwhelming because
they consume log space.
Enable these sparingly.

Examples of specific log entry types

and the data that would make them
useful are shown in Table 1. Remember
that each log entry should automati-
cally receive a type identifier, the
name or ID of the software entity that
caused it to be logged and a time-
stamp or sequence number.

All of the log data was now

enhanced with new behavior-specific
data. With sufficient patience and eye-
sight, I could read the log data and
find all of the events that were impor-

tant to me. This was a huge improve-
ment in the log data from when I
started, but it screamed for something
better and more automatic.

LOG ACCESS AND FORMAT

After some amount of run-time, the

history that has been recorded in the
log may need to be examined. There
must be a safe mechanism to access
the log data while not disrupting nor-
mal system execution. The data also
must be available in a useful and con-
sistent format to facilitate later pro-

cessing and analysis.

Access to the log data must

consider thread safety, real-
time and time-critical process-
es, and responsiveness con-
cerns. These concerns are
application-specific and the
effect of each can vary greatly
across applications. As such, an

all-encompassing solution can-
not be presented here, but I
suggest using mutual exclusion
locks on the trace buffers and
well-defined I/O mechanisms

(such as HTTP).

A simple, text-based, easily parsed

format can be invented to represent
the history data. The textual nature of
the format can provide cross-platform
compatibility by eliminating binary
encoding issues. An easily parsed for-
mat makes the use of the data simple
and consistent across different types of
history entries. I chose a simple colon-
delimited format to avoid accidental
white space and comma problems. An
example of such a format is given in
Table 2. The entries in the previous

Entry type

Text format

Event send/receive

EVENT:timestamp:name:event:from:to

State transition

STATE:timestamp:name:event:from:to

Timer set

TIMER:timestamp:name:1:timer:value

Timer cancel

TIMER:timestamp:name:0:timer

Timer timeout

TIMER:timestamp:name:2:timer

Mutex take

MUTEX:timestamp:name:1:mutex

Mutex give

MUTEX:timestamp:name:0:mutex

Arbitrary text

TEXT:timestamp:name:text

Table 2

Automatically parsing the history requires a consistent format for

the data. This table shows a simple colon-delimited format that I used to suc-
cessfully represent history data. Note that “name” (the third delimited col-
umn) is the name of the entity that’s recording a given event into the log.

background image

processes. The only problem was that
the reports only made sense to me
because I already knew what to
expect. Furthermore, I was the only
one willing to read through the
reports, which were extremely terse.

PICTURE THIS

The Unified Modeling Language

(UML) defines several graphical nota-
tions for describing object descrip-
tions, associations, and interactions.
One extremely helpful notation is the
sequence diagram. A sequence dia-
gram shows the sequence of messages
and events sent between objects. It
also shows changes in the state of a
design, like timing diagrams for soft-
ware. These diagrams are extremely
valuable for designing and verifying a
system as well as documenting it for
reference and educational purposes.
An example of the format of a UML
sequence diagram can be seen in
Figure 1 (page 43).

The type of data stored in the histo-

ry logs maps extremely well to the
data that can be shown in a sequence

40

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

trace buffer example now can be
encoded again to use this format. The
result shown in Listing 4 is now much
less readable but much more easily
parsed.

This format of log data as text can

give you a wealth of information
regarding what has occurred, when,
and how long throughout the run of
the software. However, the data is still

difficult to look at and does not fulfill
the requirement of being easy to use.
As nice as this is, there must be a bet-
ter format.

The addition of this format to the

new log entries allowed me to write a
parser that automatically reduced lit-
erally tens of thousands of lines of log
data into a much simpler and specific
report of what had happened in my

Listing 4

—This version of the text log is rather cryptic, but it has a consistent format and is trivial to parse.

The text, which is encoded using the format shown in Table 2, was used to produce the HTML sequence
chart shown in Figure 2.

EVENT:1358698.281182:a:1:a:b

STATE:1358698.281198:a:-3:S1:S2

EVENT:1358698.281209:b:1:a:b

EVENT:1358698.281220:b:2:b:c

STATE:1358698.281230:b:1:S:S

EVENT:1358698.281240:c:2:b:c

EVENT:1358698.281252:c:3:c:a

STATE:1358698.281263:c:2:S:S

EVENT:1358698.281272:a:3:c:a

TIMER:1358698.281285:a:1:timer:1000

STATE:1358698.281298:a:3:S2:S1

TIMER:1358699.282611:a:2:timer

EVENT:1358699.292579:a:1:a:b

STATE:1358699.292597:a:-3:S1:S2

background image
background image
background image

to provide this type of history. The
reward for doing so is an intuitive,
visual approach to analyzing,
debugging, and documenting your
systems.

I

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

43

diagram. In fact, UML sequence dia-
grams can be created from the data
held in the history logs. The trick is
in how to approach it.

Many tools can assist you in draw-

ing sequence diagrams. The range of
options is from paper and pencil to
sophisticated software design and
analysis tools. Some tools can even
construct the diagrams from events
sampled from a simulation or sam-
ple run within a given tool set. The
tools that do this, however, are usu-
ally costly software engineering
tools that aren’t generally available
to the random developer. The chal-
lenge is creating a simple yet effec-
tive tool to generate sequence dia-
grams based on freely available
tools.

PROJECT FILES

To download the code, go to ftp.circuit
cellar.com/pub/Circuit_Cellar/2004/173.

RESOURCES

B. P. Douglas, Real-Time UML:
Developing Efficient Objects for
Embedded Systems

, Addison-Wesley,

Reading, MA, 1998.

B. Gallmeister, POSIX.4: Programming
for the Real World

, O’Reilly &

Associates, Sebastopol, CA, 1995.

Java Technology, Sun Microsystems,
java.sun.com.

Netscape, HTML Tag Reference,
devedge.netscape.com/library/manuals
/1998/htmlguide/.

Object Management Group, “Unified
Modeling Language Specification
(UML), Version 1.5,” www.omg.org/
technology/documents/formal/uml.htm.

Scott McOlash (pronounced mick-oh-
lah-sh) is an image reconstruction
software engineer at GE Healthcare
and the founder of Mitochondrion
Software. As an electrical and soft-
ware engineer, he has been designing
and integrating software systems for
more than 18 years in applied
research and in the medical imaging,
industrial control, and CAD/CAM
industries. He has a B.S.E.E. and
M.S.E.E. from Marquette University.
You may contact him at s.mcolash
@ieee.org.

Web browsers are the

most generally available
viewing tools. Few desk-
tops ship without one.
Users upgrade those that
don’t have them. In addi-
tion to being easy to use,
web browsers are equally
easy to program in terms
of creating HTML docu-
ments. I found that a web
browser could be lever-
aged to display the histo-

ry log data as a sequence
diagram using an HTML
table filled with either
text annotation or some
form of descriptive graph-
ic. The result shown in

Figure 2 corresponds roughly with the
UML sequence diagram. It is driven by
history from arbitrary software and is
viewable on any desktop platform
using a freely available browser. A
description of the graphical elements
used in the HTML sequence diagrams
is shown in Figure 3.

By rewriting my earlier log data

parser to create an HTML document
filled with arrows and icons instead of
simple text, I could read the history
logs even faster and easier. What was
more amazing was that I could show a
wide range of people the HTML
sequence diagrams and they could
understand them quickly. I had suc-
ceeded in creating a powerful produc-
tivity tool. The time to investigate the
logs involved in a typical problem was

reduced from approximately
4 h without this tool to
about 10 min. with it. Since
then, the charts have been
used in design documenta-
tion, training, design verifi-
cation, and, of course,
debugging and performance
analysis.

MONITOR BEHAVIOR

The technique I’ve

described provides a simple
but powerful approach to
collecting, formatting, and
viewing significant behavior
that occurs in a software
system. The next step is to
apply it to your software

Object A

Object B

Object C

Message description

Message ID

Message description

State change description

Message description

Message description

State change description

Message ID

Message ID

Message ID

State ID

State ID

Time

Figure 1

A sequence diagram can show the logical association, sequen-

tial behavior, and message interchange between objects or other software
entities. The components of a sequence diagram are essentially timelines
of each software entity shown in parallel. Entity names, state changes,
and messages are generally given a graphical representation with text
descriptions provided along a common or merged timeline to the left.

Active process
Idle process
Active process holding mutex
Idle process holding mutex
Active process sending message
Active process receiving message
Timer set
Timer cancel
Timer expiration
State machine transition

(

)

Figure 3

The HTML sequence diagrams use this

graphical notation to visually describe the activity of the
software entities.

Time Stamp

Description

1358698.281182 Sent

event

1

1358698.281198

Transition from S1 to S2

1358698.281209

Received event 1

1358698.281220

Sent event 2

1358698.281230

Transition from S to S

1358698.281240

Received event 2

1358698.281252 Sent

event

3

1358698.281263

Transition from S to S

1358698.281272

Received event 3

1358698.281285

Setting time to 1000

1358698.281298

Transition from S2 to S1

1358699.282611 Timer

timeout

1358699.292579 Sent

event

1

1358699.292597

Transition from S1 to S2

A

B

C

(

)

Figure 2

This HTML sequence diagram was generated directly from

the log text shown in Listing 4. Each line in the text representation cor-
responds to an entry along the common timeline. The text descriptions
are an embellished or more readable form of the same text based on
the type of entry in the log text. The graphical elements in this exam-
ple show which entity is active at any given time (the dark blue time-
lines are active and light blue inactive), the sending and receiving of
messages, and any changes in internal state.

background image

44

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

charge every day through a UPS spike fil-
ter. Even though everything is backed
up to DVD storage devices (yet another
example of remarkable technology), I’m
not too comfortable with placing years of
columns, schematics, source code, and
PCB layouts in the hands of a relatively
nasty (and noisy) AC power source.

During the melee, meteorologists and

an air crew flying a Lockheed WP-3D
Orion named “Miss Piggy” joined forces
with computer and radar/microwave sys-
tems engineers to provide the latest hur-
ricane forecasts. That information was
brought to the public thanks to audio,
video, and RF engineers with pointy hats
who converted data to electromagnetic
radiation to be received by televisions
and radios. In the meantime, web mas-
ters are disseminating the meteorological
data to millions of PCs via an old friend
called the Internet. All the great technol-
ogy that we take for granted is made pos-
sible by the cooperative effort of scien-
tists and engineers.

Unlike humans, the animals of

Florida don’t depend on plywood, elec-
tricity, and hurricane research aircraft
to weather hurricane-force winds. I
couldn’t care less about the mosquito
population. However, I was pleased to
see that following Charley and Frances,
our neighborhood’s blue heron was out
on the lawns gracefully snapping up
frogs and small snakes. I was also
happy to see a particular Rabbit in the
Florida room perking up its ears.

RabbitCore RCM3700

I won’t go into great detail about the

new RabbitCore RCM3700, because

A

s I’ve been working on this month’s

column, I’ve had lots of unexpected
engineering help from a wide assort-
ment of engineering and scientific disci-
plines. During the past three weeks, the
Florida room has experienced extended
power outages because of hurricanes
Charley and Frances. As the keys click,
this is the fourth week of bad weather,
and hurricane Ivan is quickly approach-
ing South Florida on an indeterminate
path. The Florida room is still without
public power.

My first bit of help this month came

from the mechanical and electrical
engineers who brought gas-powered gen-
erators to the market. The small 5-kW
Florida room generator provides enough
power for limited lighting and my multi-
line phone system. Cooling (if you can
call it that) is supplied via ceiling fans
and a couple of large area fans. When it’s
90°F and there’s no breeze at 8 a.m., you
learn to appreciate the guys and gals who
put the math and mechanics to work on
the electric motors in the fans.

My appreciation also reaches out to

the engineering teams that produced
the powerful battery-powered drills I
used to board up the windows. Thanks
to the engineering staffs that worked
on uninterruptible power supply (UPS)
projects, I’m using multiple UPS units
to filter enough of the roughness out
of the generator-supplied AC to get
some work done.

In addition, my UPS devices, cell

phones, and laptop computers are
obtaining charges from the generator-
supplied AC. In fact, I actually started
this month’s column on a laptop that I

most of you have working knowledge of
Rabbit microprocessor technology. For
those of you who need some Rabbit 101,
I did a series of Rabbit columns back
in 2000 that you could reference (122,
September 2000–126, January 2001). The
important thing to know about the
RabbitCore RCM3700 is that it’s based
on the latest revision of the Rabbit 3000
microprocessor. This means that the
RCM3700 supports features and add-in
modules included in the latest-and-
greatest version of Z-World’s Dynamic
C, which includes a file allocation table
(FAT) file system, secure sockets layer
(SSL), and RabbitWeb.

The RabbitCore RCM3700 consists

of a low-EMI Rabbit 3000 microproces-
sor running at 22.1 MHz, 1 MB of serial
flash memory, 512 KB of flash memory,
and 512 KB of SRAM. The module also
includes an integrated Ethernet capa-
bility, which consists of an RTL8019AS
Ethernet IC coupled with a LAN inter-
face with a set of HALO magnetics.
The programming/debugging port is
supported by the standard Z-World cus-
tom serial cable interface.

If you’ve ever wired in an RTL8019AS

(à la Packet Whacker), you know that
it is a 5-V part. A look at the Rabbit
3000 datasheet indicates that the
microprocessor is a 3.3-V part. The
good news is that the Rabbit 3000 I/O
is 5-V tolerant. However, other things
can share the Rabbit 3000’s data I/O
bus. So, on the RabbitCore RCM3700,
the RTL8019AS data bus is isolated
with a 3.3-V 74LCX245 bidirectional
buffer. The RTL8019AS’s A0–A4
address line inputs are not buffered;

RabbitWeb HTTP Server

APPLIED PCs

by Fred Eady

Nei

ther power outages nor hurri

canes can keep Fred from hel

pi

ng you create web page

i

nterfaces that control

Rabbi

t-based embedded systems. Read on to l

earn how he recentl

y

bui

l

t a Rabbi

tW eb HTTP server under some of the worst condi

ti

ons i

magi

nabl

e.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

45

they are driven directly by the
Rabbit 3000 microprocessor.

The RabbitCore RCM3700

is a self-contained micro-
processor module that uses a
set of standard 0.1

″ double-

row pins to interface to the
outside world. This type of
interface is ideal because it is
compact and easily integrated
into a final application.
However, you won’t be box-
ing up your RabbitCore
RCM3700 this time around.
Z-World is well known for
its highly functional support
boards, so you’ll take advan-
tage of that technology while
experimenting with the
RCM3700. Consequently, instead of
building a custom RCM3700 support
board, you’ll mount your RCM3700
on Z-World’s RabbitCore RCM3700
prototyping board.

The RCM3700 prototyping board is

a multipurpose support board that
includes facilities for an infrared trans-
ceiver, an RS-485 interface, an RS-232
interface, A/D conversion circuitry, and
an optional keypad/display socket area.
There is also a prototyping board subsys-
tem that provides 5- and 3.3-V regulated
power. It would be redundant to post the
RCM3700 and RCM3700 prototyping
board schematics here because you can
get them from the Rabbit Semiconductor
web site. Photo 1 shows my RCM3700
and RCM3700 prototyping board setup.

RabbitWeb

Z-World and Rabbit products hum

in their boxes when a delivery person
hands them to you. Based on experi-
ence, I can tell you that Rabbit and Z-
World stuff works before you can get it
all out of the box. The Z-World support-
ed C compiler, Dynamic C, is just as
capable as its ready-to-run hardware
platforms. Dynamic C is rich in fea-
tures and well documented. That
makes it easy to get started with Z-
World and Rabbit hardware.

RabbitWeb is a Z-World add-on

module that takes advantage of hooks
in Dynamic C 8.50 and higher. My
RabbitWeb CD-ROM, RCM3700 pro-
totyping board, and RCM3700 came
with Dynamic C version 8.61.

Even though the Rabbit-based Z-

World hardware is well engineered, the
Dynamic C libraries provide lots of
application power. For instance, the Z-
World TCP/IP functionality is superb
because it transparently supports wired
RTL8019AS-based and wireless 802.11b-
based designs. RabbitWeb brings the
services of an enhanced HTTP server to
the libraries included in Dynamic C
versions 8.50 and higher.

One time I had to implement a

Linux box complete with an Apache
web server and write some Perl CGI
code to talk to a gadget I was writing
about. At the time, I wasn’t focused on
Linux, Perl, or the Apache code, so fid-
dling with the Linux box and Perl was
something I had to do to show the func-
tionality of the Internet box I was fea-
turing in my column. This time around,
I can eliminate the hidden CGI stuff
and show you how RabbitWeb does it
sans CGI coding, Perl, and Linux.

RabbitWeb is really an enhanced

HTTP server that is deployed using a
simple scripting language. Tags are
placed inside the actual HTML page
and parsed by the HTTP server. The
latest Dynamic C versions contain
new compiler directives that allow the
application to utilize the enhance-
ments included in the RabbitWeb
enhanced HTTP server code.

RabbitWeb BASICS

I can remember when a fancy termi-

nal emulator interface was more than
sufficient for embedded devices. In fact,

Dynamic C has its own
built-in terminal emulator.
However, with the advent of
Internet surfing, most engi-
neers prefer a web browser-
based human interface.

For small embedded devices,

a robust HTML/HTTP embed-
ded web server application
spells trouble because program
memory and RAM space is
usually tight. Lots of early
embedded web server opera-
tions turned to proprietary tags

that depended on the remote
guest being able to expand and
compress the data and com-
mands. This approach offloaded
some of the strain put on

embedded web server’s system resources;
however, the embedded web server sys-
tem was dependent on the client being
smart enough to understand the sys-
tem’s shortcomings and act accordingly.

Fortunately, most of the microcon-

troller and microprocessor IC manu-
facturers are fielding larger parts that
are capable of storing compressed appli-
cation-converted web pages with ample
program memory space that can be
allocated to the embedded web server
application. Z-World already packs
memory wallop in the Rabbit-based
modules. It takes it a step further on
the firmware side with RabbitWeb.

I was able to get the Dynamic C

version 8.61 RabbitWeb example code
up in less than a minute. A simple
change of the RCM3700’s local IP
address and gateway IP address in the
Dynamic C tcp_config.lib file to
match the Florida room LAN segment
was all that was required. This is typi-
cal Dynamic C TCP/IP configuration
stuff. My mods are in Listing 1.

I think it’s more important to under-

stand what makes RabbitWeb work
than to try to stuff one of my pet appli-
cations down your throat. You already
know about defining TCPCONFIG 1
(#define TCPCONFIG 1) and what
changes to make from my code in
Listing 1. By defining TCPCONFIG as 1,
the changes I made to the Dynamic C
tcp_config.lib file are used.

Dynamic C is a rich set of libraries.

To use the functionality of the
Dynamic C code, you must specify

Photo 1—

The RabbitCore RCM3700 prototyping board makes life easy when

developing with the RabbitCore RCM3700. What you don’t see are the connec-
tors, wiring harnesses, and power bricks that come with the kit. The RCM3700
module is the smaller PCB with the RJ-45 interface.

background image

46

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

which libraries and add-on enhance-
ments you want to include in your
application. The following is the begin-
ning of a typical RabbitWeb application:

#define TCPCONFIG 1

#define USE_RABBITWEB 1

#memmap xmem

#use “dcrtcp.lib”

#use “http.lib”

The #define USE_RABBITWEB 1

definition allows you to use the
RabbitWeb enhancements and Z-
World’s ZHTML scripting language. As
you’ll see, the “Z” in ZHTML denotes
Z-World tag particulars as far as stan-
dard HTML rules are concerned.

The xmem definition steers functions

that aren’t defined to be included in
the root memory area into the Rabbit
3000’s designated extended memory
area. The root area is defined as any-
where within the 16-bit, 64-KB physical
address space. The extended memory
area is located anywhere in the 1-MB
code space. All of the TCP/IP function-
ality is summoned with the #use
“dcrtcp.lib”

statement. In this

instance, the #use “http.lib” state-
ment brings in not only the HTTP
services, but also the extended and
enhanced services of RabbitWeb con-
tained in the zserver.lib.

It would be a good idea to have an

HTML page in the RabbitCore
RCM3700 memory if you plan to
show one as an embedded HTTP serv-
er. Security is a hot subject these
days, so let’s take a look at how you
can put together some HTML and
ZHTML tags to emulate remotely
monitoring and resetting some one-
shot door switches.

Instead of actually wiring up some

doors and switches in the Florida room,
I used the services of the RCM3700 pro-
totyping board. My one-shot door
switches are actually the S1 and S2 push
button switches native to the prototyp-
ing board. To make things interesting, I
used a couple of LEDs, which are also
native to the board, to indicate the
tripped and reset statuses of the emu-
lated door alarm switches S1 and S2.

For this example, I’ll focus on how

to monitor the main entrance and the
service entrance doors. An open-door

event is emulated by pushing either S1
(main entrance) or S2 (service entrance).
After a door opens, the alarm is sticky
until the alarm administrator verifies
the validity of the alarm and resets the
alarm event via the web browser. The
HTML for the alarm monitor page can
be as elaborate as you’d like. I kept the
alarm monitor web page simple because

I’m more interested in teaching you the
nuts and bolts of RabbitWeb than
HTML coding.

As you can see in Listing 2, the

monitor page simply tells you if an
entrance alarm is active or inactive. An
active alarm means a door has been
compromised or opened. The door
switch status is updated every 5 s.

Listing 1

After you start using Dynamic C, the consistency of the programmer interface allows for easy and

quick access to the housekeeping stuff you have to do to adapt the Z-World system to your environment.

#if TCPCONFIG >= 100

#use “custom_config.lib”

#else

//General configuration: You can specify your IP address, net

//mask, name server, and gateway here, and they will be used in

//each of the individual configurations below.

#define _PRIMARY_STATIC_IP

“192.168.0.150”

#define _PRIMARY_NETMASK

“255.255.255.0”

#ifndef MY_NAMESERVER

#define MY_NAMESERVER

“192.168.0.1”

#endif

#ifndef MY_GATEWAY

#define MY_GATEWAY

“192.168.0.1”

#endif

#if TCPCONFIG == 1

//Config 1: Simple static configuration of single ethernet interface

#define USE_ETHERNET

1

#define IFCONFIG_ETH0 \

IFS_IPADDR,aton(_PRIMARY_STATIC_IP), \

IFS_NETMASK,aton(_PRIMARY_NETMASK), \

IFS_UP

#endif

Listing 2

All of the variables preceded by a dollar sign are registered to the web server and can be

accessed by the application that is driving the HTTP server. Everything that begins with <?z is a RabbitWeb
ZHTML tag, which is parsed by the enhanced HTTP server.

<HTML>

<HEAD><TITLE>Circuit Cellar RabbitWeb ** Alarm Monitor

Page</TITLE></HEAD>

<BODY>

<H1>Current Alarm Status</H1>

<?z if($main_entrance==1) { ?>

MAIN ENTRANCE ALARM IS ACTIVE

<?z } ?>

<?z if($main_entrance==0) { ?>

MAIN ENTRANCE ALARM IS INACTIVE

<?z } ?>

<p>

<?z if($service_entrance==1) { ?>

SERVICE ENTRANCE ALARM IS ACTIVE

<?z } ?>

<?z if($service_entrance==0) { ?>

SERVICE ENTRANCE ALARM IS INACTIVE

<?z } ?>

</p>

<META HTTP-EQUIV=”refresh” CONTENT=”5;URL=/index.zhtml”>

<p>

<A HREF=”/admin/index.zhtml”>ALARM ADMINISTRATION</A>

</p>

</BODY>

</HTML>

background image
background image
background image
background image

50

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

The $main_entrance and $serv-
ice_entrance

variables determine

which message (active or inactive) is
displayed in the web browser window
and which LED (DS1 or DS2) is illu-
minated on the RCM3700 prototyping
board. Depressing and releasing S1
triggers the main entrance alarm and
illuminates DS1. Toggling S2 trips the
service entrance security alarm and
enables DS2.

As I alluded to earlier, all of the

RabbitWeb tags begin with <?z and
end with ?>. The dollar sign symbol
in $main_entrance and $serv-
ice_entrance

specifies the latest

submitted value of those variables.
RabbitWeb uses @ to indicate a com-
mitted variable value. Submitted and
committed variable values come into
play when user input is checked for
validity. For instance, if you want to
limit the temperature selection to
between 1° and 120°, you must code
what RabbitWeb calls a web guard
statement in the following manner:

int degrees;

#web degrees (($degrees > 0) &&

($degrees < 121))

The degrees integer is a standard C dec-
laration and is used by the RCM3700
application code. The actual web guard
is contained within the parenthesis.
The degrees variable is registered with
the web server; its value is referenced
in the RabbitWeb script used in the
HTML pages and the HTTP application
program by declaring the variable with
the RabbitWeb directive #web. If the
input for the degrees variable falls
outside the web guard limits, the
RabbitWeb provides the programmer
with an error() function that allows
the programmer to handle the excep-
tion.

If the user input is valid (i.e., it

doesn’t generate a web guard error)
and you want to check the last sub-
mitted degree variable against the last
committed degree variable, you must
code the following:

<?z if ($degrees == @degrees) {

?>

Your HTML code

<?z } ?>

The RabbitWeb also has the ability to

assign security to variables by user
groups. To demonstrate this, I coded vari-

ables on the alarm administration page
that any user group can read. But keep in
mind that only a user in the adminis-

Listing 3

The HTML SELECT statement coupled with the RabbitWeb print_select statement cre-

ates a drop-down menu using menu items defined in the Dynamic C HTTP driver code. A RabbitWeb web
server registration statement in the Dynamic C HTTP application code followed by a RabbitWeb
select()

feature statement assigns numeric values to each item in the select() feature’s option list.

<HTML>

<HEAD><TITLE>Circuit Cellar RabbitWeb ** Alarm Administration

Page</TITLE></HEAD>

<BODY>

<H1>Reset Alarms</H1>

<FORM ACTION=”/admin/index.zhtml” METHOD=”POST”>

<SELECT NAME=”alarm_reset”>

<?z print_select($alarm_reset) ?>

</SELECT>

<p>

<INPUT TYPE=”submit” VALUE=”Submit”>

</FORM>

<A HREF=”/index.zhtml”>ALARM MONITOR</A>

</BODY>

</HTML>

Listing 4—

All of the web registration and ZHTML page loading is done in the Dynamic C application code.

The only difference in this particular HTTP application code is that the RabbitWeb extensions are supported.
This makes for an enhanced HTTP server application.

#define TCPCONFIG 1

#define USE_RABBITWEB 1

#memmap xmem

#use “dcrtcp.lib”

#use “http.lib”

#define DS1 6

//LED, port F bit 6

#define DS2 7

//LED, port F bit 7

#define S1 4

//Switch, port F bit 4

#define S2 7

//Switch, port B bit 7

#ximport “ccink\alarm_monitor.zhtml”alarm_mon_zhtml

#ximport “ccink\admin\alarm_administration.zhtml” alarm_admin_zhtml

//The default mime type for ‘/’ must be first

SSPEC_MIMETABLE_START

//This handler enables the ZHTML parser to be used on ZHTML files...

SSPEC_MIME_FUNC(“.zhtml”, “text/html”, zhtml_handler),

SSPEC_MIME(“.html”, “text/html”)

SSPEC_MIMETABLE_END

//Associate the #ximported files with the web server

SSPEC_RESOURCETABLE_START

SSPEC_RESOURCE_XMEMFILE(“/index.zhtml”, alarm_mon_zhtml),

SSPEC_RESOURCE_XMEMFILE(“/admin/index.zhtml”, alarm_admin_zhtml)

SSPEC_RESOURCETABLE_END

//Defines an “admin” group to protect certain variables

#web_groups admin

int alarm_reset;

#web alarm_reset select(“Select Alarm Event To Clear”,”main_

entrance_reset”,”service_entrance_reset”) groups=all(ro),admin

//The #web lines below register C variables with the web server, such

//that they can be used with the RabbitWeb HTTP server enhancements

int main_entrance;

#web main_entrance groups=all(ro)

int service_entrance;

#web service_entrance groups=all(ro)

void main(void)

{

int userid;

int led1, led2;

brdInit();

(Continued)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

51

tration group can write them. Before I
point you to the code, let me say a
few more things about my web pages.

The administration page is shown in

Listing 3. Note that the alarm admin-
istration handler page index.zhtml is
located in the /admin directory. To
show you how the RabbitWeb user
group security feature works, I
invoked code that allows only admin-
istration group users access to the
/admin

directory. Thus, only an

administration user has access to the
/admin

directory with read-write

access to the variables in the
/admin/index.zhtml

ZHTML code

located in the /admin directory. All
other user groups have read-only
access to the /index.zhtml file
located in the root directory.
Everything else in Listing 3 is stan-
dard stuff with the exception of the
print_select($alarm_reset)
RabbitWeb statement. The
print_select

statement automati-

cally generates the option list for the
SELECT

HTML element.

Now that you understand the

ZHTML coding of the two web pages,
let’s tie up some loose ends. In Listing 2
I coded the main_entrance and
service_entrance

variables. The

dollar signs before each of the entrance
variables denote that the variables rep-
resent the last submitted values. The C
declarations and RabbitWeb web server
registrations of main_entrance and
service_entrance

are shown in

Listing 4, which is the main Dynamic
C application code. I designated the
main_entrance

and service_

entrance

variables as read-only for

everyone by coding groups=all(ro)
after each web server variable registra-
tion statement. The results of the
HTML and RabbitWeb ZHTML coding
for the alarm monitoring web page are
shown in Photo 2.

Let’s clean up the cobwebs in

Listing 3. The alarm_reset variable
is declared and registered with the
web server in the code shown in
Listing 4. The variable is declared and
registered to the web server in a simi-
lar manner to the main_entrance
and service_entrance state-
ments. In addition, I employed the
RabbitWeb select() feature in the

Listing 4

Continued.

alarm_reset = 0;

led1=led2=1;

main_entrance=service_entrance=0;

//Initialize the TCP/IP stack and HTTP server

sock_init();

http_init();

http_set_path(“/”, “index.zhtml”);

tcp_reserveport(80);

//The following line limits access to the “/admin” directory

//to the admin group. It also requires basic authentication

//for the “/admin” directory.

sspec_addrule(“/admin”, “Admin”, admin, admin, SERVER_ANY,

SERVER_AUTH_BASIC, NULL);

//The following two lines create an “admin” user and adds it

//to the admin group.

userid = sauth_adduser(“ccink”, “embedded”, SERVER_ANY);

sauth_setusermask(userid, admin, NULL);

//This drives the HTTP server.

while (1)

{

costate

{

if (BitRdPortI(PFDR, S1))

//Wait for switch S1 press

abort;

waitfor(DelayMs(50));

//Switch press detected if got

//to here

if (BitRdPortI(PFDR, S1))

//Wait for switch release

{

main_entrance=1;

//Set alarm

abort;

}

}

costate

{

if (BitRdPortI(PBDR, S2))

//Wait for switch S2 press

abort;

waitfor(DelayMs(50));

//Switch press detected if got

//to here

if (BitRdPortI(PBDR, S2))

//Wait for switch release

{

service_entrance=1;

//Set alarm

abort;

}

}

costate

{

if (main_entrance == 1 && alarm_reset == 0)

{

BitWrPortI(PFDR, &PFDRShadow, 0, DS1);

}

if (main_entrance == 1 && alarm_reset == 1)

{

BitWrPortI(PFDR, &PFDRShadow, 1, DS1);

main_entrance=0;

alarm_reset = 0;

}

}

costate

{

if (service_entrance == 1 && alarm_reset == 0)

{

BitWrPortI(PFDR, &PFDRShadow, 0, DS2);

}

if (service_entrance == 1 && alarm_reset == 2)

{

BitWrPortI(PFDR, &PFDRShadow, 1, DS2);
service_entrance=0;

alarm_reset = 0;

}

}

http_handler();

}

}

background image

52

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

alarm_reset

web registration state-

ment to assign the values of 0 through
2 respectively to the option items
Select Alarm Event To Clear

,

main_entrance_reset

, and serv-

ice_entrance_reset

. The option

items appear as choices in the drop-
down menu I created in Listing 3 with
the HTML SELECT and RabbitWeb
print_select($alarm_reset)
statements.

At the end of the alarm_reset web

registration line, I allowed read-only
access to the alarm_reset variable to
all users. I specified read-write access
for the administration user group with
the groups=all(ro),admin Rabbit-
Web statement. The administration
user group was created just above the
alarm_reset

Dynamic C declaration

with the RabbitWeb statement
#web_groups admin

.

Inside the main code

in Listing 4, you can
see that I used the
RabbitWeb
sspec_addrule( )

fea-

ture to limit access to the
/admin

directory exclu-

sively to the users in the
administration group.
The sspec_addrule( )
feature also allowed me
to add ccink to the
administration user group
and specify a password:
embedded

. A view of

the alarm administration page and the
contents of the drop-down menu are
shown in Photo 3.

Now that you understand what

makes up the web pages and how the
variables inside them are defined, reg-
istered, and used by both the ZHTML
web pages and the Dynamic C HTTP
application, let’s take a closer look at
the actual Dynamic C HTTP applica-
tion code in Listing 4. I’ve already dis-
cussed everything up to the defini-
tions of the push-button switches and
the LEDs. I’m sure the switch and
LED definitions are clear. So, let’s talk
about the #ximport statements.

The ccink\alarm_monitor.zhtml and

ccink\admin\alarm_administration.zht
ml files are actually the alarm moni-
tor and alarm administration ZHTML
web pages, which are stored on the

host PC running the Dynamic C 8.61
compiler (see Listings 2 and 3). The
#ximport

statement pulls the files

into the RabbitCore RCM3700 extend-
ed memory area as alarm_mon_zhtml
and alarm_admin_zhtml, respec-
tively. After the files are loaded in
the RCM3700’s extended memory
and assigned names, they must be
associated with the web server. This
association is done within the
SSPEC_RESOURCETABLE

area of

Listing 4.

The alarm monitor web page

(alarm_mon_zhtml) is registered to
the web server as /index.zhtml.
The alarm administration web page
(alarm_admin_zhtml) is registered to
the web server as /admin/index.
zhtml

. You can see this relationship

in the URL address windows in
Photos 2 and 3.

Because the web pages contain

ZHTML tags, you must enable the
ZHTML parser. Doing so allows
zhtml_handler()

to be called when

a file with the extension .zhtml is
processed. ZHTML parser enabling is
performed within the
SSPEC_MIMETABLE

area of Listing 4.

The Dynamic C application code

within the main braces is easy to fol-
low. After the RCM3700 prototyping
board peripherals are initialized, a
socket opens and the HTTP server
kicks off. Because you are using
ZHTML tags, the standard default of
index.html

you’d expect doesn’t

work here. It has to be specified as
index.zhtml

to accommodate the

ZHTML parser and tags. Four
Dynamic C costates drive the HTTP
server. The first costate looks for a

Photo 2

Note that this view is brought to you by the index.zhtml

code in the root directory. This screen refreshes every 5 s in this application.
It’s accessible by all user groups.

background image

Selecting

main_entrance_reset
from the alarm adminis-
tration drop-down menu
and clicking on the
Submit button sends a
value of 1 to the
alarm_reset

variable

in the Dynamic C appli-
cation. This clears the
alarm condition on both
the LED and the alarm
monitor browser win-
dow. A service entrance
alarm sets the serv-
ice_entrance

variable.

The fourth costate looks
for a 2 to be assigned to
the alarm_reset vari-

able indicating that the
service_entrance_reset
drop-down menu item
was selected and submit-

ted in the alarm administration drop-
down menu.

GOTTA GO!

Something electrically big has

kicked in because the Florida room’s
fans have slowed a bit. This means I’d
better save this text file and get out of
here. Hopefully, I’ll be a bit drier the
next time—and so will that soaked rac-
coon I just saw walk across the lawn.

Putting together this little

RabbitWeb HTTP server in adverse
conditions has proven that you don’t
need public utilities, plywood, and air
conditioning to go embedded.

I

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

53

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

RabbitCore RCM3700 and RabbitWeb
Rabbit Semiconductor
www.rabbitsemiconductor.com

Dynamic C and RabbitCore RCM3700
prototyping board
Z-World, Inc.
www.zworld.com

push on S1. The second watches for a
push on S2.

Toggling S1 sets the main_entrance

variable to 1. The service_entrance
variable is set to 1 after S2 is toggled.
After they’re set, the main_entrance
and service_entrance variable values
can be reset only by the ccink admin
user from the /admin/index.zhtml
web page. The RabbitWeb code running
in the alarm monitor web page picks up
the values of the main_entrance and
service_entrance

variables every 5 s

and updates the display. After a door
alarm is active, you use the “alarm
administration” hyperlink to switch to
the alarm reset web page. By clicking
the hyperlink, you’ll get a user ID and
password window. Only a member of
the administration user group can enter
the alarm reset web page and reset the
values of the variables.

You’re greeted with the view shown

in Photo 3. Select Alarm Event To
Clear equates to zero when selected in
the alarm administration web page’s
drop-down menu. The third costate in
the Dynamic C application needs
both the main_entrance and
alarm_reset

variables to be equal to

one to reset the main entrance alarm.
Otherwise, the DS1 LED remains illu-
minated and the main entrance alarm
continues to show up as “active” on
the alarm monitor web page.

Photo 3

This view is restricted to users in the administration group.

Selecting one of the drop-down menu items assigns an associated value to
the admin_reset variable, which is acted on by the Dynamic C HTTP
server application.

background image

54

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

of Life” sidebar for more information
about Conway’s Game of Life.

SIMPLE HARDWARE

Despite its apparent complexity, the

Life Game’s design is straightforward. I
used four Maxim MAX7219 multiplexed
display controller ICs, which are primari-
ly used to control a row of seven-segment
numeric LEDs (see Figure 1). They also
have a No Decode mode, which gives the
software explicit control over every seg-
ment in the display. Used in this way,
each MAX7219 can display an arbitrary
pattern on an 8 × 8 patch of 64 LEDs.

The MAX7219s have several fea-

tures that make them perfect for this
application. Each has an internal oscil-
lator, 64 bits of display RAM, and
multiplexing logic. After the software
downloads a particular display pattern
to the MAX7219, the chip can display
and refresh the pattern on the LEDs
without any help from the software.

T

he hardest part about writing this

article will be describing what I built.
I call it the Life Game.

If you’re familiar with John Conway’s

Game of Life, then you’ll know what
my Life Game is about as soon as you
look at Photo 1. If you’re unfamiliar with
Conway’s work, then what’s to say? I
could say my Life Game is a simulation
of a cellular automaton invented approxi-
mately 40 years ago by the British math-
ematician, but if I did, you’d probably
stop reading. I could also say that it’s a
super-nifty blinking light gizmo, but that
doesn’t do justice to the subtle complexi-
ty behind the scenes. To make things
easier, I’ll go with what I recently started
telling people: it’s art, a performance
piece at that, and as such it doesn’t need
any explanation. That’s the reason I cre-
ated the Life Game and why it hangs on
my wall like a fine painting.

In this article, I’ll describe how my

Life Game works. Refer to the “History

As a result, the software doesn’t need
to continuously refresh the display.
This considerably reduces the time
demands on the microcontroller.

Each MAX7219 also has its own

internal constant current source that
drives the LEDs. This ensures that
each LED receives the same drive cur-
rent regardless of the manufacturing
variations between LEDs. It also makes
the LEDs’ brightness more uniform.
Better still, the MAX7219’s constant
current source is programmable, so the
software can change the display’s
brightness. The current firmware uses
this feature to generate several nice
fade-in and fade-out effects.

The MAX7219s use a simple serial

data bus to receive data and com-
mands from the microprocessor. The
four chips in this project are daisy-
chained. Bits flow through the first
chips in the chain until they reach the
last one. The software shifts out the

FEATURE ARTICLE

by Bob Armstrong

Artificial Life Display (Part 1)

Figure 1—

Four MAX7219 chips control the entire 256-LED display. Each MAX7219 controls an 8 × 8 quadrant of the display. All four MAX7219 chips are daisy-chained togeth-

er with a simple three-wire serial bus.

Bob’s artificial life display simulates a cellular automaton designed by John Horton Conway
in 1970. Is this more art than engineering? The answer is in the eye of the beholder. In the
first part of this series, Bob shows you how his innovative design works.

Design Basics

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

55

bits for U9 (last in the chain) first and
the bits for U6 (first in the chain) last.
The DISPLAY_DATA signal (port 1,
bit 5 for the microprocessor) provides
the serial data to the MAX7219 chain.
A rising pulse on the DISPLAY_CLOCK
(port 1, bit 3) signal shifts each bit
into the MAX7219. After all of the
MAX7219s have received their bits, the
software pulses the DISPLAY_LOAD
signal (port 1, bit 4). This causes each
MAX7219 to latch the data and act
on it.

If you intend to build a Life Game

display without a PC board, wiring all
the LEDs and MAX7219’s outputs will
be a huge undertaking. The MAX7219
pin labeled C10T in Figure 2 is a col-
umn driver for column 10 in the dis-
play’s top section. Likewise, R04B
would be a row driver for row 4 at the
bottom of the display.

Rows and columns are numbered 1

to 16 starting from the upper left cor-
ner of the display. IC U9 controls the
upper left quadrant of the display
(rows 1 through 8 on the left, columns 1
through 8 at the top). U8 controls the
upper right quadrant. U7 con-
trols the lower left. U6 con-
trols the lower right (rows 9
through 16 on the right,
columns 9 through 16 at the
bottom). Figure 2 shows the
wiring for a quarter of the
LEDs in the display.
Fortunately, Spare Time
Gizmos (www.sparetimegiz-
mos.com) offers a double-
sided, silk-screened, solder-
masked PC board that makes
wiring a snap.

A few final words are in

order about MAX7219s. The
resistors R6, R7, R8, and R9
program the constant current
source in the chips. They
should be 1% precision resis-
tors to ensure uniform bright-
ness in all four display quad-
rants, and the 10-k

Ω value

specified results in a maxi-
mum LED current of approxi-
mately 40 mA. That’s 40 mA
per LED, so if a particular
MAX7219 happens to have a
column with all eight LEDs
lit, it would require 320 mA

in total. And that’s per 7219, so
the worst-case power supply cur-
rent required by the display
would be 4 × 320 mA, or approx-
imately 1.3 A! Keep this in mind
when I describe the power sup-
ply. It’s also why the power con-
nections for each MAX7219 are
bypassed by both a 0.1-µF ceram-
ic capacitor and a 10-µF tanta-
lum to prevent the high currents
generated by the switching of
LEDs on and off from causing
spikes on the V

CC

supply.

MICROPROCESSOR

The microprocessor in the Life

display is a modern variation of
the venerable Intel 8051, which
has been around for at least 20 years.
The 8051 variant I used features flash
memory for program storage and can be
programmed, while it’s still plugged
into the Life Game display, from a PC
using a standard RS-232 serial port. No
special programmer is required! This is
also why no EPROM is used in the
design, and it makes it easy for you to

download the firmware to your game
after it’s built. It also makes it easy to
modify the firmware. Spare Time
Gizmos has made all the source code
for the Life Game display open source
in hopes that designers will add new
patterns and features.

Other than the flash memory and

in-system programming, the display’s

firmware needs no other spe-
cial 8051 features (e.g., PWMs,
counter/timers, A/Ds, I

2

C or

SPI ports, etc). There are actu-
ally a number of different
8051 variants that can be
used. The preferred variant is
the Philips 89C51RA2, but
this one is preferred only
because it’s the simplest and
cheapest part that will run
the firmware. The Philips
89C51RB2, RC2, and RD2 dif-
fer only in the amount of pro-
gram memory they have (but
all have more than the RA2),
and any one will work.

Atmel also makes many

8051 derivatives with flash
memory; however, only a few
of those support in-system
programming and program-
ming with a RS-232 serial
port. Note that the Atmel
AT89C51Rx2 series will
work, and parts such as the
AT89C51RB2 can be used.

Finally, note that the Philips

89C66x series of parts will
also work. These chips have

Photo 1—

What do you think of the finished and framed Life

Game? You can display it sort of like a painting. Is this art or
science?

Figure 2—

Check out the wiring for one 8 × 8 quadrant of the LED display, in

this case the upper left corner. Study the nomenclature for the row and column
connections, and then extend it for the remainder of the 16 × 16 display.

background image

56

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

extra features (e.g., I

2

C, PWMs, etc.)

that you do not need, but with a few
trivial software modifications to dis-
able them, they’ll work fine.

The rest of the circuitry around the

microprocessor is pretty conventional
(see Figure 3). The DS1233 provides a
clean power on reset and a reset if V

CC

drops too low. Plus, it can be manually
activated by a simple push button.

The 8051 has an active high reset

input (pretty unusual these days!), so
you have to invert the output of the
DS1233 with one section of the
74HC14. Transistor Q1, along with R2,
pulls the processor PSEN pin low as
long as reset is asserted. This little trick
is unique to the flash memory versions
of the 8051, and it activates the built-in
bootloader. Note that the emitter of Q1
is grounded via the serial port cable, so
that the boot loader will be activated
only when the programming cable is
connected. The Dallas DS275 is a super
simple RS-232 EIA level shifter that
allows you to interface the micro-
processor’s serial port to the PC with
proper EIA signal levels.

Figure 3—

The microprocessor section of my Life Game contains a Philips or Atmel MCU, the Sharp IR receiver,

some simple signal conditioning for the 50/60-Hz line clock, and an RS-232 interface. The latter is with the in-sys-
tem programming feature of the MCU to allow the firmware to be downloaded from a PC via a simple serial port.

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

59

INFRARED RECEIVER

U2 is a Sharp GP1UM272XK

infrared remote control receiver
intended for a carrier frequency
of 36 kHz, which is the same
frequency used by the RC5
remote control protocol. You
can also use the GP1UM271XK
if you have trouble obtaining
the GP1UM272XK.

The GP1UM271XK has a

carrier frequency of 38 kHz. Although
not ideal for RC5, it works fine in prac-
tice with perhaps a slight reduction in
range. Beware, though: Sharp makes
several other versions with carrier fre-
quencies even farther away than the
38-kHz part. These should be avoided.
The serial data from the infrared
receiver is applied directly to the INT0
microprocessor input.

LINE FREQUENCY CLOCK

A sample of 60Hz AC (or 50 Hz,

depending on where you live) is sam-
pled from the power supply and
applied to the input of Schmidt trigger
U10C. If an 8-VAC wall transformer is
used, this input will receive a peak
voltage of at least 12 V, but the input
protection diodes in the 74HC14 will
clamp it to V

CC

. Resistor R1 is there to

limit the current through the clamp
diodes to a safe value, and R10 and
C20 filter the AC waveform and
remove high-frequency noise. The
output of U10C is a clean 60-Hz
square wave, which is applied to the
microprocessor’s INT1 input, where
the software uses it to keep track of
the time of day.

POWER SUPPLY

The power supply is unusual

because it uses an AC wall wart (a real
transformer and nothing more) instead
of the much more common DC output
variety (see Figure 4). This is done just
so you can derive the 60-Hz line
clock, but it also means that you have
to include a bridge rectifier (D1) and
filter capacitors (C3, C4, C5, and C19)
on the PC board. Three or four medi-
um value filter capacitors are used
rather than one large one strictly for
mechanical reasons. A single large
capacitor would be too big for the
space available.

Although the power supply circuit

is straightforward, the components are
all carefully selected to minimize the
heat dissipation of regulator VR1. In
particular, you should use the 8-V AC
wall wart specified in the parts list;
one with a higher voltage will make
VR1 run hotter. You can’t use the
more common 7805 regulator in this
circuit either. The LM2490 was
selected because it can work with as
little as a 0.5 V difference between the
input and output, whereas the 7805
requires at least 3 V.

Finally, note that 3,600 µF of filter

capacitance (C3, C4, and C5) is gener-
ally enough. Adding more only (C19)
increases the dissipation of VR1, and
you should do so only if you really
need it.

With exactly the power supply com-

ponents specified, VR1 will dissipate
approximately 4 to 5 W with all the
LEDs on. This is certainly enough to
require a heatsink and good ventila-
tion. But the reality is that the game
only spends 1 s during the power-on
self test with all LEDs on, and the
number of LEDs on at
any time is only a
small fraction of the
total. Under these con-
ditions, VR1 can run
forever with no
heatsink other than the
copper area provided on
the PC board and it
will barely get warm.

The question of

heatsinking VR1 is left
up to the builder. If
you only want to play
the Game of Life, no
heatsink is required.
On the other hand, if
you want to modify
the firmware to display

different patterns, especially
ones with large numbers of
LEDs on at one time, then
you’ll need a heatsink of some
kind. Also be aware that some
of the clock modes have higher
LED duty cycles and will make
VR1 run hotter. Remember
that the LM2490 has internal
over temperature protection. If
it overheats, it’ll simply shut

down until it cools off.

SOFTWARE

The firmware for the Life display

consists of some 8,000 lines of 8051
assembly language code divided into
12 modules. Figure 5 shows the most
significant modules and their relation-
ship to each other and major hardware
components. Execution is a simple
foreground/background model with
interrupt-driven modules such as the
RC5 (infrared) receiver and clock in
the foreground and the Life engine
soaking up all the leftover background
time. You may download the code
from the Circuit Cellar ftp site.

The infrared.asm module contains

the code for receiving and decoding
infrared remote control messages
transmitted using the Philips RC5
code. RC5 codes are fourteen bits long
with a nominal bit time of approxi-
mately 1.778 ms. Most remotes use
nothing more than a cheap R/C oscil-
lator for a timebase, and you can’t
depend too much on the exact timing.
Instead, RC5 uses a biphase encoding

Figure 4—

The conventional power supply section uses a low-dropout, three-

terminal, 5-V regulator. The only unusual thing is that the wall wart used with
this supply is AC rather than the more conventional DC output. This is done
so you can extract a 50/60-HZ reference signal to drive the time of day clock.

Figure 5—

Take a look at the different software modules and how they inter-

act. Each software module corresponds to one source file (sometimes two
source files).

life.asm

Start up, power on,

self test, and copyright

GP1UM271XK

infrared.asm

Receive and decode

RC5 messages

INT0

clock.asm

Timekeeping

functions

50/60 Hz

INT1

nextgen.asm

Compute Life Game

generations

canned patterns

clockface.asm

analog.asm

Clock display

functions

ram.asm

Display bitmap

display.asm

MAX7219 Drive

P1.0

Beeper

MAX7219

P1.2...

P1.5

background image

60

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

system in which every bit is self-clock-
ing (in this case, every bit contains a
transition in the middle of the bit time
window), and the state of the bit (a one
or zero) depends on the polarity of that
transition.

The code maintains a bitmap of the

state of the 256 LEDs in an internal
32-byte buffer in the ram.asm module.
The display.asm module contains the
code to send this internal bitmap, along
with the necessary commands, to the

four Maxim 7219 chips. Remember
that the MAX7219s are self-refreshing,
so the display.asm module is invoked
only when the bitmap actually changes
(i.e., the next generation is computed).
After the bitmap has been loaded into
the 7219s, they can maintain a static
display without any more help from
the software.

The nextgen.asm module contains

the Life Game’s engine—the function
that computes the next Game of Life

generation from the current one. Doing
this on the 8051 required a few tricks
to conserve RAM because the 8051 has
only 128 bytes of RAM, and the regis-
ters, display buffer, and stack space
take half of that up. Interestingly,
although the 8051 is short on RAM, it
has plenty of ROM for this application.
The algorithm contains few loops,
which have been unrolled to optimize
execution speed at the cost of ROM
space. Even on a lowly 11-MHz 8051,

History of Life

In the late 1940s, mathematician John von Neumann

became interested in what the real world could teach
him about computing. Along with physicist Stanislaus
Ulam, he investigated the way in which relatively sim-
ple components following simple rules can work togeth-
er to form complex systems with elaborate behaviors.
The obvious example is the cells in your body. Each
individual cell is a fairly simple device, but large groups
of cells working together can form complex organs like
a heart and kidneys. Likewise, each individual insect in
an ant colony is a simple-minded creature, but thou-
sands of them working together build amazingly com-
plex structures.

Von Newman tried to define the set of behaviors

required for each cell and the ways in which a single cell
could interact with other cells. He set out to build a sys-
tem of cells that could replicate itself. By this I don’t
mean each cell simply copying itself. That’s trivial.
Instead, I’m talking about the entire arrangement of cells
creating an exact duplicate of itself. (It’s sort of the equiv-
alent of a termite colony starting another colony some-
where else, which it can do of course.) As you can
imagine, this was a difficult problem, but not impossible.
Ulam and von Neumann eventually found success with
a cell that had 29 states and interacted with its four
directly adjacent neighbors.

In the late 1960s the British mathematician John

Conway became interested in von Neumann’s work,
but Conway thought von Neumann had made things far
more complicated than they needed to be. After much
experimentation, Conway set-
tled on a two-dimensional
array of cells in which each
cell had only two states—alive
or dead—and interacted with
its eight neighbors according
to only three simple rules: a
living cell survives to the next
generation if it has two or
three neighbors; a living cell
dies if it has four or more
neighbors (overcrowding), or if

it has only one neighbor or none (isolation); and a dead
cell becomes a living cell in the next generation if it has
exactly three neighbors (birth).

They may be simple but, believe it or not, a sea of

Conway’s cells can do everything that von Neumann’s
cells could do. In fact, Conway went on to figure out
ways to model AND gates, OR gates, NOT gates, and
other components of modern computers with his cells. If
you have enough of Conway’s cells working together (and
it would take a lot), you can compute anything that the
most modern Pentium chip can!

Shortly thereafter, Martin Gardner, who at the time

edited the “Mathematical Games”column in Scientific
American

, wrote about Conway’s work. When that

issue hit the streets in October 1970, the floodgates
opened and a vast quantity of time—both human and
computer—was spent generating random arrays of
living and dead cells, and then running them ahead in
time thousands or millions of generations while people
looked at the results for interesting patterns. Many fas-
cinating patterns were eventually discovered. And they
aren’t just boring stable patterns; many grow and
evolve over time.

The Life Game has a dozen or so classic Game of

Life patterns built into its ROM. It can display the
initial pattern followed by successive generations (see
Figure 1).

Conway, who still lives in Britain, never intended for

his invention to be a game. And although he has always
acknowledged the parallels to living creatures, he never

intended it to be a model of
biological systems.

To a computer scientist, algo-

rithms like this one are known
as cellular automata. They have
many practical applications,
including some not so obvious
things like modeling the move-
ment of subatomic particles,
predicting the behavior of large
crowds of people, and explain-
ing the spread of forest fires.

Figure 1—

This three-cell Game of Life pattern is known as a blinker

(some people also call it a traffic signal or a flip-flop). It oscillates
between two distinct states with every new generation. If you’re inter-
ested, you can easily “play computer” and apply the rules of the Game
of Life to this 3 × 3 grid and see for yourself why it behaves this way.

Generation

1

Generation

2

Generation

3

Generation

4

Generation

5

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

61

the nextgen code can compute life
generations faster than you can see
them. It’s all you need for this appli-
cation!

Two modules display the time in

various formats (both with and with-
out Game of Life effects). Analog.asm
displays a simulation of an actual ana-
log clock with hours, minutes, and
seconds hands. (By an amazing stroke
of luck, a 16 × 16 display has exactly
60 LEDs around the perimeter!)

Clockface.asm displays a digital clock

simulation with the hours and minutes
presented in a 4 × 5 numeric font.
Either clock option can play the Game
of Life with the current clock display.

The clock.asm module counts the

50/60-Hz line time interrupts, and it
keeps track of the actual time of day
and date. The current time is set via the
remote control, and both the clock-
face.asm and analog.asm modules use it
to display the time. This module also
contains the code to turn the beeper on
and off. It belongs here only because it
uses the line clock to time the duration
of the beeps.

Life.asm is the firmware’s main

module. It contains the start-up and
initialization code as well as the inter-
rupt vectors. It also contains a power-
on self-test (POST) function that exe-
cutes a simple hardware test whenever
the system powers up. By no means is
the POST exhaustive, but it gives you
some confidence that things are work-
ing correctly.

CONSTRUCTION PHASES

Next month, I’ll cover the details of

building the Life Game. In addition,
I’ll describe the processes of in-system
programming the microprocessor and
selecting an IR remote control. In the
meantime, visit the Life Game web
page for more background information
(http://life.sparetimegizmos.com).

I

SOURCES

DS275 Level shifter
Maxim Integrated Products
www.maxim-ic.com

89C51 Microcontroller
Philips Semiconductors
www.semiconductors.philips.com

GP1UM272XK IR receiver
Sharp
www.sharpusa.com

PROJECT FILES

To download the code, go to ftp.circuit
cellar.com/pub/Circuit_Cellar/2004/173.

Bob Armstrong is currently self-
employed as a hardware and software
design consultant in Silicon Valley. In
the past, he’s worked on process control
and automation software for semicon-
ductor manufacturing, several different
EDA software products, image enhance-
ment and Braille display devices, auto-

mobile traffic-monitoring systems, and
flat panel LCDs for computers and
HDTV. In his spare time, Bob runs Spare
Time Gizmos, a small company dedicat-
ed to producing electronic projects and
kits for hobbyists. You may contact
him at bob@sparetimegizmos.com.

background image

62

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

opment environment is the WebPACK
edition of its ISE design software.
The software handles the Spartan-3
XC3S50, XC3S200, and XC3S400
parts.

First, I’ll describe the SEB3, which

can accommodate the XC3S50,
XC3S200, and XC3S400 in a PQFP208
package. After that, I’ll describe the
design flow for designing with Web-
PACK. Lastly, I’ll describe how I
hooked up an embedded 8-bit processor
to all the peripherals on the board and
an external LCD.

All of the schematics for this project

are available in a PDF posted on the
Circuit Cellar

ftp site. You might want

to download the schematics before
reading ahead.

W

hen you think of designing an

embedded product, do you think of
microcontrollers or FPGAs? For small
projects, you’d probably consider an
8-bit microcontroller with the right mix
of peripherals (both on-chip and off). For
better performance, you might choose a
16- or 32-bit processor. If your applica-
tion is in the signal-processing area, you
might go with a DSP. With all of these
options to consider, why would you
choose an FPGA? According to FPGA
manufacturers, FPGAs like Xilinx’s
Spartan-3 and Altera’s Cyclone II are not
only inexpensive, they can be tailored
to your application’s processing require-
ments. How is this done? Is it a difficult
process? In this article, I’ll shed some
light on these subjects.

One thing that

intimidates design-
ers is the complexity
and cost of FPGA
design tools. Both
Xilinx and Altera
offer free versions of
their design software
that can handle the
smaller devices in
their product lines. I
used the Spartan-3
family to build my
Spartan-3 FPGA
experimenter’s board
(SEB3). I chose the
Spartan-3 because
I’m familiar with
Xilinx parts, and
because the Spartan-3
has block RAM and
multipliers, which
are useful for DSP
projects. The devel-

HARDWARE DESIGN

I wanted an FPGA board that would

allow me (and others) to play with
FPGAs within a reasonable budget.
Therefore, I wanted to use only those
Spartan-3 parts that are supported by
Xilinx’s free WebPACK software. The
board had to be self-contained because
I didn’t want to have extra program-
ming cables and add-on boards for
external circuitry. I also wanted an RS-
232 port, SRAM, various LEDs and
push buttons, and a solderless bread-
board on which to add other circuitry.
Figure 1 is a block diagram of the SEB3.
Photo 1 shows the assembled board.

SPARTAN-3 FPGAS

Spartan-3 is Xilinx’s newest family

of low-cost FPGAs.
Although these parts
have fewer resources
than their big brother,
the Virtex II, they are
sufficient for most
hobbyists. The
Spartan-3 parts used
on the SEB3 (XCSS50,
XCS200, and XCS400)
are architecturally
derived from Xilinx’s
Virtex II and Virtex II
Pro parts (see Table 1).

Each slice in a

Spartan-3 contains
two look-up tables
(LUTs) and two regis-
ters and miscella-
neous logic for input
multiplexing and
carry logic. In addi-

tion, two of every
four LUTs can be

FEATURE ARTICLE

by Philip Nowe

An FPGA Experimenter’s Board

5-V Power

plug

Voltage regulators
3.3, 2.5, and 1.2 V

RS-232

Level shifter

SRAM

3.3-V User I/O header

Parallel III

cable circuitry

XCF02

Configuration

PROM

Parallel IV

cable connector

User clock

socket

50-MHz

clock

Spartan 3

FPGA

XC3S200

8.8.

DIP Switch

Two seven-segment

LEDs

Eight discrete LEDs

2.5- or

3.3-V

User I/O

header

Solderless breadboard

Two discrete switches

Figure 1

There are two connectors for you to access FPGA signals. One is a female header next to the

solderless breadboard. The other shares signals with the SRAM.

Philip sees an FPGA in your future. Why? They’re inexpensive, and you can tailor them to
meet your design goals. Read on to learn how easy it is to build a Spartan-3-based FPGA
experimenter’s board.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

63

used as distributed 16 × 1 bit RAM or
a 16-bit shift register (SRL16).

The Spartan-3s contain digital clock

managers (DCM) that allow many
clocking functions to be performed
easily in the FPGA. The DCM can
perform frequency synthesis, phase
adjustment, clock inversion, 50%
duty cycle correction, and more. An
architecture wizard is included in the
ISE for configuring DCMs.

Spartan-3 FPGAs have two levels of

built-in memory. The first level is the
distributed RAM in half of the LUTs
as mentioned previously. This memory
can be used to implement small scratch
pad memory and FIFOs. The next level
is the block RAM (BRAM), which is
18-Kb RAM that can be configured in
many ways (e.g., 1K × 18 and 2K × 9),
as well as in Single- or Dual-Port
modes. The BRAM is used for larger
memory. Both distributed memory
and BRAM can be cascaded to make
larger memory banks.

The Spartan-3 FPGAs are the first

low-cost FPGAs to implement hard-
ware multipliers. The small Spartan-3s
contain four to 16 18 × 18 multipliers
(see Table 1).

FPGAs are now expected to interface

to many types of logic. To meet this
goal, Spartan-3 FPGAs have a config-
urable I/O block that can interface to
single-ended standards such as LVCMOS,
LVTTL, GTL, and HSTL, as well as to
differential signals such as LVDS,
BLVDS, and RSDS. The I/O voltage
can be set from 1.2 to 3.3 V for the
various interface standards.

In addition, Xilinx’s XCITE technol-

ogy gives you the ability to reduce the
number of termination resistors used
on signal lines. This is done by

employing on-chip parallel termina-
tion resistors or by changing the dri-
ver’s output impedance.

An important thing to understand

about an FPGA is that there are multiple
voltages required to power the device.
The Spartan-3 core (VCCINT) requires
1.2 V. Auxiliary circuitry like JTAG
(VCCAUX) requires 2.5 V. The I/O
(VCCO) can run at various levels
between 1.2 and 3.3 V. The SEB3 has
some restrictions on the I/O voltages.
There are eight banks of I/O in a Spartan-
3, with two per side of the device. Each
bank can be set to a different I/O voltage
level with one restriction: banks 4 and
5 must be 2.5 V for configuration, but
they can then change to 3.3 V. Table 2
shows the voltages used for each bank
and what each bank is used for.

CONFIGURE THE FPGA

The SEB3 contains an XCF02S con-

figuration PROM. This device holds
the configuration data because the
Spartan-3 is an SRAM-based FPGA,
which means that when the power is
removed, it loses its memory. There

are connections from the XCF02S
(U10) to the FPGA (U6) and to the
JTAG connector (J7). The JTAG con-
nector is provided for those of you
who have a Xilinx Parallel Cable IV.
The FPGA’s M2 through M0 pins are
used to specify the method of configu-
ration for the FPGA. In this case, they
are set to zero, which means that the
configuration method is Master Serial
mode. This means that the FPGA is
in control of the serial configuration

from the configuration PROM,
XCF02S (U10). LED D16 shows when
the configuration is done.

PARALLEL III PORT CIRCUITRY

Besides programming the XCF02S

through a Parallel Cable IV, the SEB3
contains the circuitry of a Parallel
Cable III on the board itself. (Refer to
Xilinx’s web site for the Parallel Cable
III cable schematics.) This allows you
to program the configuration PROM
and FPGA without using the more
expensive Parallel Cable IV ($99). The
schematic on page 7 of the PDF shows
the Parallel III circuitry and how it’s
connected to the JTAG connector. In
order to prevent contention between
the Parallel IV and Parallel III cables
when both are plugged into the card at
the same time, I added U9, which dis-
ables some U8 and U7 drivers. The
input to U9 is pulled high by R73,
unless a Parallel IV cable is connected
to J7, which will ground this input.

The difference between the Parallel III

and IV cables is that the former is a
bit-banging interface. Hence, it’s slower
(28 s for programming and verifying a
XCF02S) than the Parallel IV cable,
which uses the ECP Parallel Port
mode (and takes 15 s to program and
verify the same device).

RS-232 PORT & CLOCKS

The SEB3 contains a Texas

Instruments MAX3221 RS-232 level
shifter as well as a DE-9 connector.
Refer to the schematic on page 10 of
the PDF to see how the level shifter
(U4) and the DE-9 connector (P1) are
connected to bank 0 of the FPGA. As
you study the RS-232 and clock cir-
cuitry, keep in mind that a single RS-
232 channel is provided through the
MAX3221 (U4). Note the addition of

Table 1—

This feature list is for the FPGAs supported on the SEB3.

Photo 1

What do you think of the Spartan-3 experi-

menter’s board? To save money I shortened the right side of
the PCB under the solderless breadboard.You can also see
the LCD interface circuitry on the solderless breadboard.

Device

XC3S50

XC3S200

XC3S400

System gates

50,000

200,000

400,000

Logic cells

1,728

4,320

8,064

Slices

768

1,920

3,584

Distributed RAM (bits)

12 Kb

30 Kb

56 Kb

Block RAM (bits)

72 Kb

216 Kb

288 Kb

Dedicated multipliers (and number of BRAMs)

4

12

16

Digital clock managers

2

4

4

Maximum user I/O (PQFP208)

124

141

141

background image

64

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

R40 to prevent the possibility of con-
tention if the user programs pin 205 of
the FPGA as an output. This is done
for the SRAM data lines as well as the
DIP switch and the push buttons.

Two clocks are possible on the

SEB3. I used a 50-MHz, 50-ppm oscil-
lator (Y2) in one position and added a
socket to the second site (Y1). These
clock signals are connected to two of
the FPGA’s primary clock pins.

ASYNCHRONOUS SRAM

The SEB3 contains a single Cypress

CY7C1019CV33, 128K × 8 asynchro-
nous SRAM (U5). This device is con-
nected directly to the FPGA. Refer to
the schematic on page 11 of the PDF.

Note that there is a user I/O header

(JP3) that shares the SRAM signals in
case you want more user I/O than
what’s available on JS4. If you don’t
want to use the SRAM, and if you’d

rather use the signals for user I/O, you
must pull the SRAM *CE high through
JP2. This I/O is limited to 3.3 V.

LEDs

The SEB3 has eight discrete user

LEDs (D6–D13) and a two-digit seven-
segment LED display (D5) connected
to the FPGA. As you study the LEDs
schematic on page 6 of the PDF, keep
in mind that different resistors are
used for the discrete LEDs versus the
seven-segment LEDs. This is because
the discrete LEDs use 2.5 V (bank 5)
and the seven-segment display uses
3.3 V (banks 0 and 1).

PUSH BUTTONS & SWITCHES

The SEB3 is equipped with two

momentary contact push buttons (SW3
and SW4) and an 8-bit DIP switch
(SW2). The DIP switche is connected
to bank 2 (3.3 V), and the push but-
tons are connected to bank 4 (2.5 V).
Refer to page 13 of the PDF.

Note that the series resistors used

with the DIP switch (SW2) are not
used for debouncing. They help pre-

Bank

Usage

VCCO

0

Discrete LED and part of two-digit, seven-segment LED,
50-MHz clock, RS-232 signals to level shifter

3.3 V

1

Two-digit, seven-segment LED, user code

3.3 V

2

Prototype connector

2.5 or 3.3 V (user-selectable)

3

Prototype connector

2.5 or 3.3 V (user-selectable)

4

Configuration, some not used

2.5 V

5

Discrete switches and DIP switch

2.5 V

6

SRAM/user I/O

3.3 V

7

SRAM/user I/O

3.3 V

Table 2

Here you see the I/O voltage and the uses for each FPGA bank on the SEB3.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

65

vent damage to the FPGA in case you
inadvertently drive those pins as out-
puts.

POWER SUPPLIES

An external power supply provides

5 V to the card through J2. The 3.3 and
2.5 V are derived through linear regula-
tors from the 5-V input. The 1.2 V is
derived from 2.5 V. The LMS1585 reg-
ulators are for 3.3 (U1) and 2.5 V (U2).
The LP3883 is for 1.2 V (U3). The
LMS1585s are capable of providing
5 A, and the LP3883 is capable of
supplying 3 A.

The voltage regulation circuitry,

which includes voltage supplies for 3.3,
2.5, and 1.2 V, is on page 8 of the PDF.
The bleed resistor (R100) on the 5-V line
ensures that, when the power is turned
off, the bias input to the LP3883 is below
50 mV before it is turned on again.

SOLDERLESS BREADBOARD

The SEB3 has a solderless breadboard

that allows you to attach your own
circuitry to the FPGA. The solderless
breadboard circuitry is on page 9 of

the PDF. Bank 2 and bank 3 VCCO are
selected via JP4 and JP6 respectively.
Sixteen I/O lines are available to the
protoboard area from each bank. It’s
up to you to ensure that the proper
VCCO settings are made to prevent
damage to the FPGA.

You have access to 32 FPGA signals

from banks 2 and 3 of the FPGA, as
well as 5, 3.3, and 2.5 V and GND. It’s
important to set the input/output volt-
age levels for each of bank 2 (using JP4)
and bank 3 (using JP6). The options are
limited to 2.5 and 3.3 V using the sup-
plied header, although you could supply
an alternate voltage directly to pin 2
on JP4 or JP6.

DESIGN WITH WEBPACK (ISE)

Now that I have described how the

SEB3 hardware is set up, let’s focus on
designing the FPGA. WebPACK is a
free version of Xilinx’s ISE FPGA
design software. With it, you can
design circuitry for many of Xilinx’s
smaller FPGAs.

Installing WebPACK is simple. Check

out Xilinx’s web site. You can either

use a web installer or download Web-
PACK in one file (207 MB!) and install
it. Either way, you’ll want a broadband
connection. You’ll also want to down-
load and install the ModelSim XE
starter simulator (another 97 MB),
which allows you to verify the func-
tionality of your design both before and
after you perform a place and route.
Note that WebPACK and ModelSim
require Windows 2000 or XP.

Photo 2 shows the main interface to

the ISE. There are a number of windows
that are used for managing your project,
running tools, and editing your design.
The Sources in Project window is the
Project Navigator-like window on the top
left. The Processes for Current Source
window is on the left at the bottom.

When a project file is selected in the

Sources in Project window, the process
window shows which operations can
be performed on this file. For instance,
if a VHDL module is selected, you can
create a schematic symbol out of it,
synthesize it, and then place and route
it (part of the Implement Process). If a
test bench file is selected, the Process

background image

66

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

window shows that you can, among
other things, simulate it in ModelSim.

The multi-tabbed console window

along the bottom of the ISE console
shows what the various processes are
doing. It also shows errors and warnings.
The main window for editing design
files is on the right side of the display.

Designing with ISE requires that

you know how you want to represent
your design. The ISE allows you to use
schematics, VHDL, Verilog, or state
machines. To start a new project, you
first select New Project under the File
menu. Next, select a project name and
directory. You then tell the ISE what
your top-level design will be, usually a
schematic or HDL such as VHDL or
Verilog. I’m a visual person, so I usual-
ly choose to have a schematic at the
top level. This doesn’t mean the entire
design has to be in the form of
schematics, just the top level. The
lower-level blocks can be HDL mod-
ules, schematics, or state machine dia-
grams. Then, you select the FPGA you
want to use as well as the synthesis
tool and simulator.

After you’ve started a new project,

start adding modules. Some modules
could be preexisting modules (e.g.,
PicoBlaze). You’ll create others. For
instance, adding a new VHDL module

will bring up a context-sensitive code
editor, where you can input your
design. Also available are language
templates in case you forget the syn-
tax for a particular construct or if you

Photo 2

The Sources in Project window is in the upper left corner. Below it is a list of the possible processes that

can run for the selected Source. The bottom window is the console window. The main window to the right is the
source window. The source shown is part of the input multiplexer to the PicoBlaze system developed in this article.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

67

want to know how to write code that
can be synthesized, for something like
a barrel shifter or counter .

After creating the VHDL module,

you should simulate it. Xilinx has a
graphical waveform editor called HDL
Bencher that you can use to create a
test bench for your module. I recom-
mend this for each new module. By
doing so, you’ll be able to catch design
errors as early as possible.

After the test bench is created, you

can launch ModelSim from the
process window to simulate the design.
The design isn’t synthesized at this
point, so it’s referred to as a behavioral
simulation. Again, this is important
because it catches bugs early. When
you are happy with the simulation,
add more modules as required.

When you are ready to create your

top-level schematic, select each of the
VHDL modules and select “Create
schematic symbol” in the process win-
dow. Next, add a top-level schematic to
the design. This brings up a schematic
capture program called ECS. Then all
you need to do is add your VHDL mod-

ule schematic symbols to the schematic
and wire them up. You’ll also need to
add I/O ports, which are used to speci-
fy FPGA pins (but not pin numbers).
After this is done, again, it’s best to
create a simulation test bench for the
top-level design and simulate it to
ensure no errors have crept into the
design.

The next stage is synthesis using

the Xilinx Synthesis Technology (XST)
tool. To do so, select the top level of
your design in the Sources in Project
window and double-click on
Synthesize-XST. You can review what
the synthesis tool has synthesized by
looking at the RTL view of the design.
This is a schematic of what XST has
generated from your source code. The
schematic takes a bit of getting used
to, but it will give you an idea about
the simplicity (or complexity) of your
design. If it appears to be complicated
with many levels of logic between
flip-flops, you can bet that its perform-
ance won’t be stellar.

There are a number of other steps

and tools you can use to design your

FPGA, including timing analysis, power
analysis, and state machine diagram
input. However, one thing you can’t do
without is the user constraints file
(.ucf), which contains pinout, area, and
timing constraints. At a minimum,
you’ll need to select your design’s
pinout. This is extremely important.
Without it, each time you synthesize
and implement a design, the ISE will
likely choose different pins for the I/O.
This is fine before you’ve laid out your
board, but it’s a problem after the board
is done. Trust me, I’ve inadvertently
deleted one pin definition, and some-
times it’s difficult to figure out what
went wrong.

After the design is synthesized, you

can implement the design by double-
clicking on it in the Processes win-
dow. Implementation means translat-
ing the low-level elements that the
XST tool generates to the actual place-
ment and routing of the design in the
FPGA. This is often referred to as
place and route, although this actually
refers to the last part of the implemen-
tation process.

background image

68

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Last but not least, you need to

download the design files to the FPGA
or configuration PROM. This is done in
two steps with a software package called
iMPACT. The first step is to generate
the download file using the Generate
PROM, ACE, or JTAG file under
Generate Programming File in the
Process window. Next, you need to pro-
gram of the device using Configure
Device (iMPACT) under Generate
Programming File in the Process win-
dow. In the SEB3’s case, this uses the
PC parallel port to download the code
through the on-board Parallel III circuitry
(or with the optional Parallel IV cable).

The ISE also includes an architecture

wizard that helps you design with
DCMs. This tool presents a series of
windows that allow you to specify input
frequency, output frequency, phase, and
feedback source options. The wizard
also calculates jitter for your clock
design. It generates an .xaw file that can
be used to create a schematic symbol,
which in turn can be added to the top-
level schematic.

When you’re designing in an FPGA,

there are a number of other tools that
you should use. One is Xpower, which
allows you to estimate your design’s
power consumption. This can be use-
ful when designing your power supply

circuitry. Other tools include timing
analysis, Pinout and Area Constraint
Editor (PACE), Chipviewer, and
Floorplanner.

If you have some extra cash on

hand, a useful tool is Chipscope Pro.
This is an internal logic analyzer that
allows you to see what’s happening
inside the FPGA. It’s almost impera-
tive to use when you have a large
complicated FPGA design, but the
cost ($695) is a consideration. Other
tools include DSP Generator, obvious-
ly for DSP-based designs, and System
Generator for embedded processor
applications.

PICOBLAZE DESIGN

Now that I’ve covered the hardware

and you have an idea of how to use
the development tools, it’s time to go
through an example to show what can
be done in the Spartan 3. This design
uses a PicoBlaze 8-bit microcontroller
and a UART from Xilinx and custom
circuitry to exercise all of the blocks
on the SEB3 as well as interfacing to a
2 × 16 character-based LCD module
through the solderless breadboard. The
block diagram of the design is shown
in Figure 2.

The intent is to connect the board

to the serial port of a PC and issue

commands through HyperTerminal.
The commands control various
peripherals on the board as well as
control the external LCD. Photo 3
shows the circuitry running with an
output on the LCD.

The PicoBlaze is a small, simple

8-bit processor for Xilinx FPGAs.
KCPSM3 is the version for the Spartan 3
FPGAs. The program code space for
the PicoBlaze is a single block of RAM
(BRAM) organized as 1-KB instruc-
tions by 18 bits. The PicoBlaze, which
was developed to be as small as possi-
ble, consumes only 96 slices (or 5%
of a XC3S200) and one BRAM. The
PicoBlaze executes an instruction in
two clock cycles and runs at ~87 MHz
in a –4 speed grade part. This works
out to ~43 MIPS. The main applica-
tion for a PicoBlaze is for relatively
low-speed control. It can be used
instead of a state machine where the
state machine design may be compli-
cated or high speed is not needed. In
this design, I run the PicoBlaze at
50 MHz (25 MIPS.)

The PicoBlaze, which has 16 general-

purpose registers and a 64-byte scratch-
pad memory, can handle interrupts
and call subroutines up to 31 levels
deep. It can interface to 256 input
and 256 output ports. Refer to the

Block RAM

Address

(9:0)

Data

(17:0)

PicoBlaze

Address

(9:0)

Instruction

(17:0)

In_port

(7:0)

Out_port

(7:0)

UART

RX

DIP Switch

push buttons

RX

LCD

Data

LCD

control

register

LCD
data

register

SRAM

data

register

SRAM

high addr

port

register

SRAM

low addr

port

register

UART

TX

LED

port

register

Seven-segment

port

register

SRAM

TX

LEDs

Seven-segment

LED

JS3

2

3

5

7

9

11

13

15

17

7

8

5

9

10

11

12

13

14

4

4

19

6

330

RS

R/W

E

DB0

DB1

DB2

DB3

DB4

DB5

DB6

DB7

2 × 16 LCD

Backlight

+

Backlight

GND

Contrast

V

DD

5 V

10 k

V

IN

On/Off

R1

V

OUT

V

OUT

R2

FDC6323L

32

4

5

6

10

5 V

1

3

2

10 k

SRAM

Data

1

2

3

FPGA Circuitry

Circuitry on solderless breadboard

Figure 2

The output registers shown in the FPGA circuitry are selected by PORT_ID signals not shown in the diagram. Note that the FDC6323L FET switch is controlled by

one of the push buttons on the SEB3. The interface to it is through the FPGA, but is not shown in this diagram.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

69

PicoBlaze user guide listed in the
Resources section of this article for
more information.

Designing with the PicoBlaze means

instantiating it in VHDL in this case.
An external assembler is then used to
generate the code that’s downloaded to
the BRAM. One of the assembler out-
puts is a VHDL file that defines the
BRAM and its contents. This is added
as a source to the project, and that’s
all there is to it.

The PicoBlaze comes with an option-

al UART, which handles 8 bits, no par-
ity, 1 stop bit, and has a 16-byte FIFO.
The UART occupies 40 slices (~2% of
XC3S200). It can be used at regular RS-
232 speeds such as 38,400 bps, or it can
be used at rates exceeding 10 Mbps for
inter-FPGA communications.

I used a 2 × 16 LCD module from

Lumex that uses a Samsung S6A0069
controller. One thing that is possible
in FPGA design is to have various
trade-offs between hardware and soft-
ware. For example, I implemented a
hex-to-seven-segment decoder in hard-
ware. I could just as easily done it in
SW, but I already had the hardware
version completed from when I was
debugging the board.

PICOBLAZE SOFTWARE

Programming for the PicoBlaze is

done in assembler only. Remember that
there is only 1 KB of instructions. I
used the standard assembler that comes
with the PicoBlaze core, but I could
have used Mediatronix’s
PicoBlaze IDE.

Table 3 shows the com-

mands implemented in
the PicoBlaze code. They
are similar to what you
might find in a simple
general-purpose monitor. I
started with the UART
real-time clock reference
code that Xilinx provides
with the PicoBlaze. It con-
tains routines for handling
the UART. I used this
code as a starting point,
stripped out the real-time
clock routines, and added
the code to handle the
LEDs, switches, SRAM,
and the LCD.

Listing 1 (page 70) shows the VHDL

code for the data input multiplexer
for the PicoBlaze, as well as the
seven-segment display output register.
Listing 1 also shows the VHDL com-
ponent instantiation of a hex-to-
seven-segment decoder for one of the
seven-segment displays. Note how
easy it is to specify the input multi-
plexer. To add more inputs, you must
specify the port ID address and add it
to the multiplexer.

The output registers were also rela-

tively easy, but to maintain maximum
performance, the addresses were one-
hot encoded (i.e., each bit selects a
register.) I used all 8 bits for this proj-
ect, so I’ll do a different encoding (or
pipelining) to add more registers while
maintaining performance.

IMPLEMENTATION

Only 9% of the slices are used and

one of the 12 BRAMs. Theoretically,
this means that there could be
10 instances of this circuitry in the
XC3S200. Not bad for a part that costs
less than $30 (in low quantities). In
addition, note that my code con-
sumes only 604 of the 1,024 bytes in
the single BRAM.

FPGA APPLICABILITY

I hope I’ve shown you that it isn’t

difficult to design with an FPGA.
There is a lot to learn about process
flow and the tools, but the tool inter-
face makes it relatively straightfor-
ward. There are a number of tutorials

online that can help you out.

An FPGA can be used for a number

of different things. You can connect it
to many types of external circuits.
Your imagination is probably the only
limiting factor (other than your pock-
etbook, of course!).

What am I going to do with the

board now that it’s working? Well, I
have been thinking about a couple of
designs that will put those multipliers
and block RAM to good use. Maybe
I’ll put another processor core from
www.opencores.org in the FPGA and
play with them or some DSP blocks
(or maybe all of the above)! If it is digi-
tal and is not too large, it probably can
be done in one of these devices.

I believe that FPGAs are an impor-

tant part of a designer’s toolbox. They
may not always be the right tools for a
project, but because of their affordabil-

Table 3

As you study the PicoBlaze design SW commands, note the following limitation: A16 to the SRAM is currently set to zero

(i.e., only the lower half of the SRAM is accessible).

Com m and

Description

Syntax

7seg

Outputs data to seven-segment LEDs

7seg hh

LED

Outputs value to show on discrete LEDs

LED hh

DIP

Read DIP switch settings

DIP

PB

Read push button settings

PB

RD

Read byte from SRAM

RD hhhh* where hhhh is the address in the SRAM

WR

Write byte to SRAM

WR hhhh,xx writes xx(in hex) to address hhhh

BD

Block dump from SRAM, returns 256-byte
block

BD hh, where HH is the upper byte of the address of the 256-byte
block in the SRAM

FILL

Fill 256 bytes of SRAM with a value

FILL hh,xx, where hh is the upper byte of the of the
256-byte block in the SRAM, and xx is the data

LCD

Outputs string (16 characters maximum)
on line of LCD

LCD ln,string, where IN is either line 1 or 2 and the on line of string
is up to a 16-character string ending with a carriage return

*A limitation is that A16 to the SRAM is currently set to zero (i.e., only the lower half of the SRAM is accessible).

Photo 3

Take a look at the SEB3 running with

PicoBlaze driving the LCD and LEDs. The FET switch is
mounted on a SOT-23 proto adapter shown near the
bottom of the solderless breadboard. Resistors are
used to current-limit the 5-V data outputs from the LCD
to the 3.3-V I/O of the FPGA.

background image

SOURCES

Quartus II Web Edition software
Altera
www.altera.com

33206 SOT-23 Adapter board
Capital Advanced Technologies, Inc.
www.capitaladvanced.com

CY7C1019CV33 128K × 8 SRAM
Cypress Semiconductor Corp.

www.cypress.com

Spartan-3 experimenter’s board
www.dulseelectronics.com

FDC6323L FET switch and MAN6910
dual seven-segment LED
Fairchild Semiconductor
www.fairchildsemi.com

LCM-S01602DSF/C
Lumex, Inc.
www.lumex.com

LMS1585 and LP3883 1.2-V regulator
National Semiconductor Corp.
www.national.com

MAX3221 3.3-V RS-232 level shifter
Texas Instruments Incorporated
www.ti.com

XC3S200 Spartan-3 FPGA, XCF02S
configuration PROM, WebPACK, and
PicoBlaze
Xilinx, Inc.
www.xilinx.com

PROJECT FILES

To download the schematics and code,
go to ftp.circuitcellar.com/pub/Circuit
_Cellar/2004/173.

RESOURCES

Free open-source IP cores and chip
design, www.opencores.org.

C. Maxfield, The Design Warrior’s
Guide to FPGAs: Devices, Tools, and
Flows

, Elsevier, Burlington, MA, 2004.

Mediatronix, pBlazeIDE PicoBlaze
IDE, www.mediatronix.com.

Xilinx, Inc., “PicoBlaze 8-bit Embedded
Microcontroller User Guide for
Spartan-3, Virtex-II, and Virtex-II Pro
FPGAs,” UG129, 2004.

———“Spartan-3 FPGA Family:
Complete Datasheet,” DS099, 2004.

Philip Nowe holds a degree in
Engineering from Carleton University

ity (for both devices and tools), FPGAs
should be considered for future proj-
ects. Remember: have fun, and FPGAs
can be embedded too.

I

in Ottawa, Canada. He has been
working in the hardware design
industry for more than 20 years.
Philip has experience in board design,
PLD/FPGA design, and hardware
management. Currently, he is a digi-
tal design consultant. You may con-
tact Philip at pnowe@sympatico.ca.

www.circuitcellar.com

CIRCUIT CELLAR

®

70

Issue 173 December 2004

Listing 1

This is the VHDL code for the data input multiplexer, the seven-segment display output register,

and the instantiation of a hex-to-seven-segment decoder for one of the seven-segment displays for the
PicoBlaze.

******************************************************************

//KCPSM3 input ports

******************************************************************

//UART FIFO status signals to form a bus

uart_status_port <= “000” & rx_data_present & rx_full & rx_half

_full & tx_full & tx_half_full ;

//Pushbutton signals SW3 and SW4 to form a bus

pushbutton_port <= “000000” & SW3 & SW4 ;

//The inputs connect via a pipelined multiplexer

input_ports: process(clk)

begin

if clk’event and clk=’1’ then

case port_id is

//read UART status at address 00 hex

when “00000000” => in_port <= uart_status_port;

//read UART receive data at address 01 hex

when “00000001” => in_port <= rx_data;

//read DIP switch at address 02 hex

when “00000010” => in_port <= not(DIPSWITCH);

//read pushbuttons at address 03 hex

when “00000011” => in_port <= pushbutton_port(7 downto

0);

//read SRAM at address 04 hex

when “00000100” => in_port <= SRAMDATA(7 downto 0);

//read LCD at address 05 hex

when “00000101” => in_port <= LCD_DATA(7 downto 0);

//Don’t care used for all other addresses to ensure min

imum logic implementation

when others => in_port <= “XXXXXXXX”;

end case;

read_from_uart <= read_strobe and port_id(0);

end if;

end process input_ports;

******************************************************************

//LED_7seg_port output register

******************************************************************

write_to_7seg <= write_strobe and port_id(1);

LED7seg_port: process(clk)

begin

if clk’event and clk=’1’ then

if write_to_7seg =’1’ then

if port_id(1)=’1’ then

LED_7seg_port <= out_port(7 downto 0);

end if;

end if;

end if;

end process LED7seg_port;

firstLED_output: Hex2SevenSegment

port map( HEX => LED_7seg_port(7 downto 4),

LED => FIRSTLED(7 downto 0) );

background image
background image

72

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

unknown frequency is to measure its
phase relative to the known source and
to track the result over time. A phase
error of 1° is easily detected, so the fre-
quency of a 60-Hz input can be measured
with an accuracy of better than 50 ppm
per second of measurement time. Given
a perfect reference, you can measure the
average AC line frequency to 1 ppm in
1 min. The snag is that you must track
the phase continuously. Phase detec-
tors can only measure phase unam-
biguously over 180° or 360°.

Logging and processing the results

requires little precision. I used an analog
phase detector with a linear phase/volt-
age scale. Digitizing its output with
8-bit resolution gives you nearly the

I

really hadn’t intended to write more

about numerically controlled oscilla-
tors (NCOs), so this project wouldn’t
have come about if Ed Nisley hadn’t
wanted to track frequency variations
in the AC line, as he explained in
“Multiplying, Dividing, and Filtering”
(161, December 2003) and “Filters and
Firmware” (163, February 2004). You
see, several years ago I’d done some
work on those lines myself.

I’d been doing occasional jobs for a

company that makes transmission line
monitoring equipment. Being software
people, they use a processor running a
Fourier transform to shut down faulty
transformers before they explode. I’d
wondered if an analog approach would
work. For example, could you generate
a pure 60-Hz sine wave with an NCO
phase-locked to the input and compare
the two?

Not having an immediate use for this

idea, I carried it no further. Then I
saw Ed address a related problem—
that of generating 60 Hz locked to an
extremely precise 10-MHz reference.
This seemed an ideal application for
one of my PIC-based firmware NCOs,
so I crunched some numbers. I’d pushed
the upper frequency limit for so long
that trying low-frequency generation
was a welcome change. The results
were so favorable that I went ahead and
built a 60-Hz generator (see Photo 1).

FREQUENCIES AND PHASES

If you have a known frequency and

a similar but unknown frequency, the
most accurate way of determining the

1-ppm resolution per minute I postu-
lated earlier. As you’ll see, the inherent
accuracy of this detector can be nearly
as good as the 10-MHz clock signal
supplied to it.

NCOs: THE DOWNSIDE

NCOs have their limits, some of

which I’ve mentioned in past articles.
They can generate some frequencies
exactly. That’s why you usually choose
the clock crystal to permit, for example,
the generation of exact integer frequen-
cies. Given a long enough accumulator
(32 or 48 bits is standard), an NCO chip
can generate any frequency to within a
tiny fraction of a hertz. However, if the
timing source is 10 MHz, an NCO can-
not output exactly 60 Hz. I’ll defer for
a moment the question of how close it
can come.

NCOs generate many frequencies

simultaneously. Only one is the one you
want. An output low-pass filter removes
the others. The lowest unwanted fre-
quency is the clock frequency minus the
wanted output. If you can reduce that to
an acceptable level, the higher image
frequencies can be ignored.

A subject I haven’t addressed in pre-

vious articles is quantization noise,
which arises because the amplitude of
each output sample is a finite approxi-
mation to an actual sine wave at that
moment in time. NCO chips usually
have 12 output bits. Because PICs
have 8-bit ports, my firmware NCOs
have used 8-bit samples and an 8-bit
DAC. Each sample is truncated to the
next lowest of 256 different voltages

FEATURE ARTICLE

by Tom Napier

Reference Generation

Photo 1

An 18-pin PIC with a lot of filter components

lets you check the phase drift of your AC supply.

Is it possible to generate a pure 60-Hz sine wave with an NCO? After crunching some num-
bers and looking through past issues of Circuit Cellar, Tom did just that. Read on to learn how
he used a PIC-based firmware NCO to build a 60-Hz generator.

Build a 60-Hz Generator with an NCO

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

73

and hence can have an error of up to
0.4% of the full-scale signal.

Quantization generates spurious fre-

quencies (commonly called “spurs”) in
the output. These appear as grass-like
spikes throughout the NCO’s output
spectrum. Some lie within the pass-
band of the output filter. Their ampli-
tude depends on the magnitude of the
quantization error, their frequency on
the moment-to-moment phase of the
output relative to the clock. Given an
ideal DAC, the peak spur amplitude is
a function of the number of bits in the
sample. For an 8-bit sample, the peak
amplitude is –55 dB relative to the sine
output. That’s approximately 0.18% of
the signal, so you can see why I’ve
ignored it until now.

Reducing quantization error produces

a purer sine wave. A 12-bit sample and
a 12-bit DAC reduce the spurs by
another 20 dB. Their worst amplitude
is nominally 0.018% of full scale.

Some problems with NCOs are the

fault of the DAC, not the NCO. DACs
are less than perfectly linear. Putting
the output of a 12-bit NCO into a DAC
with a

±1 unit linearity is almost as bad

as using an 11-bit NCO. All the other
common DAC problems apply. Careful
layout is essential because the analog
output may pick up digital noise. The
DAC may generate glitches as the
input bit pattern changes. And so on.

60 Hz FROM AN NCO?

Were you to run a 32-bit NCO chip

from a 10-MHz clock, its minimum
frequency step would be 0.00233 Hz.
The closest you’d get to 60 Hz is
60.000457 Hz. Now this is off by only
7.6 ppm and would be acceptable, for
example, when running from a 50-ppm
crystal oscillator. Still, you can do
much better.

You needn’t use the 10-MHz refer-

ence directly. Lowering an NCO’s
clock speed improves its resolution
proportionately. The output of an NCO
is virtually perfect when the clock is,
say, 100 times the output frequency.
Consequently, any clock between 6 kHz
and 10 MHz is acceptable. Using a
slower clock also lets you get away
with a much cheaper and possibly
more accurate DAC.

Divide the clock by 1,024, for exam-

ple. The minimum frequency step
becomes 0.00000227 Hz. You can now
set 60 Hz to better than 0.002 ppm—a
frequency error of one cycle in 83 days!

For even better accuracy, take

advantage of your new degree of free-
dom. Is there some division ratio that,
when combined with a suitable fre-
quency selection number for the
NCO, will give 60 Hz close enough to
satisfy any purist?

Would I let you down? Dividing

10 MHz by 437 gives a systematic error
of 10

–11

, which is way less than the

error of any clock source other than an
atomic standard or Ed’s GPS receiver.

Can you achieve this ratio without an

oddball hardware divider? So far, I’ve
assumed a $50 NCO chip and a paral-
lel input DAC. What about my old
standby, a firmware NCO implemented
in a PIC?

TRY IT IN FIRMWARE

In my past NCOs, you could set an

arbitrary frequency. With a low and
constant frequency, the rules change.
Above some minimum, the number of
instructions in each sample loop is
that aforementioned extra degree of
freedom. If you run a PIC at 10 MHz
(that’s 2.5 MIPS), even if each sample-
generating loop takes a few hundred
instructions, you’ll still have far more
than enough samples per output cycle
to satisfy Mr. Nyquist.

A software accumulator can have as

many bytes as you please, but because the
complexity of multibyte addition rises
rapidly, I tried a 3-byte one. In that case
the output frequency is the following:

Now you need to find the two magic
numbers, N and L. N is the number
you add to the accumulator every
time around the loop. L is the total
length of the loop in instruction peri-
ods. N can be any integer, but L is con-
strained to lie between the minimum
practical loop length and a maximum
determined by how few samples per
output cycle you can get away with.

FINDING MAGIC NUMBERS

I started testing likely numbers

with a 10-digit calculator but soon

realized I was uncomfortably close to
its resolution limit. I finished the job
with a quickly written Forth program.

One combination, L = 173 and N =

69659, happens to be extremely accu-
rate. With these parameters, the out-
put frequency is 59.99999927 Hz, or
just 0.012 ppm under 60 Hz. The fre-
quency error is approximately one
cycle every 16 days—a phase drift
approximately 1° per hour. A 173-
instruction loop generates an NCO
clock of 14.451 kHz and runs at nearly
241 samples per output cycle. Looking
good so far!

Being used to writing 15- to 25-

instruction NCO loops, I’d thought of
173 instructions as having all the time
in the world. To take advantage of the
lower sample rate, I decided to use a
12-bit serial DAC, thus minimizing
spurs. I’d underestimated the com-
plexity of the firmware needed to
implement a serial output. My first
draft ran to over 300 instructions.
Tricks such as unrolling inner loops and
using a port as a shift register brought
that down to 187. Saving one or two
more instructions looked feasible, but
not 14. Meanwhile time was flying by.

The next best option was a 222-instruc-

tion loop with a 11.261-kHz clock fre-
quency and an error of one cycle in
60 h. Because I would be evaluating the
generator with a conventional (50 ppm
if you’re lucky) crystal oscillator, that
was good enough. Software and hard-
ware development moved ahead.

After everything was working, I took

another stab at the 173-instruction loop.
I finally got the code down to exactly
173 instruction periods. (For a while it
was 171 and a bug. Fixing that took two
instructions, leaving no room for wave-
form improving gimmicks such as
addition with rounding.)

A LONGER ACCUMULATOR?

You can get considerably better accu-

racy with a 32-bit accumulator. I’d resis-
ted that upgrade because adding the
lower bytes can cause a carry to propa-
gate through all of the higher bytes.
Allowing for this rare event takes more
and more instructions as the number
of bytes increases.

This is another rule that no longer

applies. When adding a constant, the

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

75

multiple-carry situation either can or
cannot arise, depending on the constant.
It can’t in this case.

With a 32-bit accumulator, the fre-

quency equation becomes the following:

The best result my search program

found was the aforementioned “divide
by 437.” With 437 instructions per
loop, the frequency error is one cycle
every 68 years, assuming a perfect
clock driving the PIC.

In a practical system, it’s probably

worth trading unneeded accuracy for the
output sample rate. With 265 instruc-
tions per loop, there will be 157 sam-
ples per cycle. The systematic error is
one cycle in 5.7 years. My source
code, which is available on Circuit
Cellar

’s ftp site, uses a 3-byte accumula-

tor and has a 173-instruction loop. Hints
for its modification to 4 bytes and
265 instructions are included.

GETTING A SINE

As in any NCO, the accumulator con-

tent rises linearly and rolls over once per
output cycle. Feed that to a DAC, and
you’ll get a saw-tooth waveform. How
can you convert it to a sine wave?

With 8-bit resolution, a look-up table

is practical, at worst it has 256 bytes, and
there’s room for it in the PIC. Ideally, a
12-bit sine output requires 14 or more
bits of input resolution. A look-up table
would need a 32-KB PROM (I briefly
considered a serial EEPROM), but the
alternative, a sine algorithm, requires
several multiplications. That’s a slow
process on a small PIC.

I ended up doing a piecewise linear

approximation. Each output cycle is
split into 256 segments. A one-quadrant
look-up table stores 65 15-bit sine val-
ues. The most significant accumulator
bit specifies the sign of the 12-bit out-
put sample. The next bit reverses the
direction in which the table is read.

The lower 6 bits of the upper accumu-

lator byte specify a waveform segment.
Each segment contains 256 points. The
10-bit difference between the sine sam-
ples at the two ends of a segment is
multiplied by the middle accumulator
byte and divided by 256 to interpo-
late between them. This takes one

10-bit × 8-bit multiplication. The
result is added to the segment base. If
the accumulator’s sign bit is set, the
result is negated.

SAMPLES TO SINE WAVES

To drive a 12-bit parallel DAC with

a PIC would require external latches
to change all 12 bits simultaneously.
Some DACs have built-in latches, but
I didn’t happen to have one handy.

I did have some eight-pin, 12-bit, serial

input DACs. At a high clock rate, the
loading time of a serial DAC would be
prohibitive. With loop time to spare, you
can afford to send samples in serial form.

My NCO processor is a PIC16C54. I

saved loop instructions by using its port
A as a 4-bit shift register. The most sig-
nificant bit is the serial data output; the
other three drive nothing. Instead of
shifting and testing data bits, I dumped a
nibble into port A and did “clock up,
clock down, port shift” four times. Serial
output took 52 instructions rather than
the 134 I’d started with.

The serial DAC is an AD7233,

which has a built-in reference, a bipo-
lar voltage output, and costs approxi-
mately $15. Unfortunately, its inter-
face requires you to shift in 16 bits.
The first four are ignored, but sending
them chews up processor time. The
AD7233 needs a

±12-V power, so I

killed two birds with one wall-wart.
Its 13-VAC output powers the board
and also supplies a phase reference at
a safe voltage. 7812, 7912, and 7805
regulators supply the power.

SMOOTHING THE WAVE

The DAC output filter requires seri-

ous thought. In addition to your want-
ed signal at 60 Hz, the raw DAC out-
put also contains two image frequen-
cies at clock (14.450 kHz) plus and
minus 60 Hz, as well as higher images
you can ignore. Because of the sine(x)/x
DAC output spectrum, the unwanted
frequencies are already 47 dB below the
output before you add a filter.

Theoretically, you only need to filter

out frequencies above 5.5 kHz. In prac-
tice, you can lower this substantially
and cut out some of the spurs. However,
it’s easy to forget that filters have a sig-
nificant phase shift well below their cut-
off frequency. When looking for tiny

background image
background image

76

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

phase shifts between this reference
and the AC line, having an output fil-
ter whose phase shift at 60 Hz is signif-
icant and might drift with tempera-
ture is not too swift an idea.

Funnily enough, the obvious choice,

a narrow 60-Hz band-pass filter, is the
worst one possible. The phase shift of
a band-pass filter swings through 180°
or 360° around its center frequency.
Although the output frequency is
fixed, component drift with tempera-
ture can introduce phase changes that
could swamp any real differences.

I settled on a three-pole active filter

with a 600-Hz corner frequency. This
gives a clean 60-Hz sine wave and atten-
uates the images by an extra 80 dB. Its
phase shift at 60 Hz is approximately
10°. I passed the 13-VAC input through
an identical filter to balance the phase
shifts and to remove extraneous junk.

FUDGING THE FILTER

Active filter design can be extreme-

ly frustrating. It isn’t too hard to cal-
culate exact component values, but if
you opt for a specific design like a
Bessel or Butterworth filter, the capac-
itors can have extremely odd values.
Here I took a different approach. I
assumed practical capacitor and resis-
tor values and checked to see if the
resulting filter was acceptable. You

want good attenuation at 14 kHz and
a minimum phase shift at 60 Hz.
What the filter does in between isn’t
too important. I ended up with an “I
can’t believe it isn’t Butterworth” fil-
ter using readily available capacitors
(see Figure 1).

Normally, I insist on using plastic

foil capacitors in filters because
ceramic ones can have poor accuracy
and high tempcos. Here, your only
requirement is that two identical fil-
ters phase-shift 60-Hz signals by the
same amount. You might get away
with matched ceramic capacitors. The
resistors should be matched too, but I
didn’t bother.

COMPARING PHASE

To compare the phase and frequen-

cy of your reference with the power
company’s 60-Hz input, you need a
phase detector to drive a recording
device, be it a chart recorder or your
favorite computer ADC board. An
ideal detector would multiply the
incoming AC by the reference and
integrate the result; however, this
gives an output that’s the sine of the
phase difference. A linear output is
handier in this context. Besides, my
local AC (and probably yours too) has
a large third-harmonic content.

A simpler recourse is to compare

the zero-crossing times of the AC and
the reference. This gives a linear out-
put but is susceptible to phase jitter
and comparator oscillation.

The filtered NCO output has no

measurable phase jitter. Jitter arises
only when the output frequency is
either extremely low or high. In the
former case, the same output sample
may be generated for several clocks in a
row. This generates a level output fol-
lowed by a step to the next level,
which the filter is powerless to smooth
out. The zero-crossing detector tends to
switch only on the transitions. The
good news is that the resulting jitter is
at most a few clock cycles in ampli-
tude. By assuming a high clock and a
low output frequency, this cannot
amount to much.

The other case arises when operat-

ing close to the upper frequency limit.
If too much of the image frequency
leaks through the filter, the output
will have wonderful wobbles. Neither
case applies here.

BUT, IN THE REAL WORLD

Originally, I had designed in a

74HCT4046 PLL chip. (Its VCO section
was part of my old 60 Hz phase-lock con-
cept.) Its three phase detectors have TTL
outputs the PIC can sense. Because the
phase detector inputs are self-biased to

Figure 1

Building this part of the circuit lets you compare the AC supply and a local 60-Hz reference with an oscilloscope. You can line up the two signals manually with the

phase Reset button.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

77

Tom Napier is an electronics design
consultant and writer. His specialty is
spotting better and cheaper ways of
getting a job done.

2.5 V, I added a fixed DC offset to both
the sine reference and AC input signals.

Unfortunately, the 74HCT4046 isn’t

happy with slowly changing inputs; it
tends to oscillate as the threshold is
crossed. Adding speed-up and limit
amplifiers to the analog inputs helped
a little, but the phase detector output
still generated a spurious output pulse
every few seconds.

I got the best results from the

74HCT4046 exclusive-OR phase detec-
tor. This has only a 180° range. At
equilibrium there is a 90° phase differ-
ence between the signals. Even though
it worked, it isn’t the best state for
examining the phase on a oscillo-
scope.

Because I was using only the exclu-

sive-OR part of a complex chip, I sub-
stituted an HC gate for the 74HCT4046.
Without a 74HC86 on hand, I wired
up a 74HC00 as an exclusive-OR gate.
Apart from demonstrating that I still
remembered the procedure, this
approach would have let me use a
Schmitt trigger chip if I’d still found
oscillation problems. (Paranoia was
setting in by that time.)

DISPLAYING PHASE

The phase detector output is a vari-

able mark-space ratio rectangular wave-
form with nominal 5-V amplitude. I had
slight misgivings about running the PIC

and the phase detector from the same
rail because the output phase error volt-
age is proportional to the 5-V supply.
Critical users can add a separate 5-V ref-
erence for the phase detector.

Heavily filtered, this output can

drive a meter or chart recorder. I used
a 3-Hz Bessel filter to minimize distor-
tion of any step changes in phase.
Because the inherent scale is 0 to 5 V,
an offset and a gain of two are incorpo-
rated in the output filter to give a

±5-V

output. Figure 2 shows the phase
detector and output filter.

A systematic frequency difference

appears as a series of full-scale up and
down traces on the recorder. Each
straight section corresponds to a 180°
shift but gives no indication whether
or not the long-term phase trend is
increasing or decreasing (i.e., whether
the input AC is above or below 60 Hz).

RESETTING THE PHASE

Power up the board, and you’ll get

a highly stable 60-Hz output with a
10-V

PP

amplitude and a fixed but

unknown phase relationship with the
AC input. Test points 1 and 2 let you
compare the AC and the reference.

The next step is to reset the phase.

This turned out to be rather simple.
Pushing the phase Reset button allows
the phase detector output to switch
the number of instructions per loop

SOURCES

AD7233 D/A Converter
Analog Devices
www.analog.com

PIC16C54 Microcontroller
Microchip Technology, Inc.
www.microchip.com

PROJECT FILES

To download the code, go to ftp.circuit-
cellar.com/pub/Circuit_Cellar/2004/173.

between, in my case, 172 and 174.
These numbers create a frequency
error of

±0.35 Hz, quickly forcing the

phase detector’s mark/space ratio to
50/50. (A slower but more accurate
phase-lock mechanism would modify
N rather than L.) After you release the
button, any phase difference you see is
the power company’s fault.

I was more concerned with a proof-

of-concept than a finished product, so
I made this generator on a 2.5

″ × 4″

wire-wrap board. My clock input was a
20-MHz crystal divided down to 10 MHz.
Even that matches the power compa-
ny’s input pretty closely.

I

Figure 2

Adding limiters, a phase detector, and an output filter lets you make a permanent record of the power company’s performance. The phase Reset button now sets an

automatic 90° phase difference.

background image

78

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Photo 1). Originally designed to serve
as a navigation system for the military,
GPS now also provides indispensable
service in commercial applications on
land, sea, and air. As an aside, the
Soviet Union closed the GPS gap in
1982 with its own version (GLONASS),
although that system has subsequently
fallen into a state of marginal disrepair
even as GPS has flourished.

The GPS concept is simple enough.

Assume all the satellites and an earth-
bound receiver share a precisely syn-
chronized clock. Further assume the
receiver knows the exact position of all
the satellites at a particular point in
time. Then it’s just a matter of each
satellite sending time-stamped packets
that are detected by a receiver some time
later. How much later is the key, with
the time difference between transmis-
sion from the satellite and receipt by the
receiver allowing the distance traveled to
be calculated. In turn, the distance from
each satellite allows the receiver’s
position to be determined.

Getting a 2-D (latitude and longi-

tude) or 3-D (latitude, longitude, and
altitude) position fix requires measure-
ments from three and four satellites,
respectively. Typically, up to eight
satellites are in view under open sky
conditions, leaving the GPS receiver
to choose the most visible ones at any
point in time. Other factors (besides
physical obstruction) that go into
satellite selection include geometric
considerations (i.e., tightly clustered
satellites dilute precision) and atmos-
pheric conditions (i.e., signals from

W

hat’s that old saying about men

never asking for directions? I suppose
it’s politically incorrect either way
you cut it: men are actually better
navigators, or they aren’t and are just
too dumb to know it.

On the other hand (no, I mean the

other other hand), my dear wife Laura
would be the first to admit she is
directionally challenged. When she is
behind the wheel, a simple trip across
town sometimes seems like an auto-
motive demonstration of the random
walk theory: flip a coin at any inter-
section, and you’ll eventually end up
where you wanted to go (admittedly,
only after cruising past a lot of places
you didn’t need to go by).

Believe me, I’m making sure her next

vehicle has one of those built-in GPS
navigation systems. I’ve seen them in
action, and they’re wonderful. I imagine
future versions with HAL-like interac-
tion capabilities such as a soothing
voice that says, “I’m sorry, Laura, but
you really should have turned right,”
maybe with some flashing LEDs or
such to clarify just what the meaning of
“right” is. Meanwhile, I can remain
silent and safely immune from accusa-
tions of backseat driving while she
tongue-lashes the GPS.

A LITTLE LATITUDE

The GPS itself is old news, with

Cold War roots dating back to 1978 and
the launch of the first of what is now
24 NAVSTAR satellites (12 each in the
Northern and Southern hemispheres)
that comprise the GPS space fleet (see

satellites low on the horizon encounter
more atmospheric interference). As con-
ditions change (e.g., a vehicle traveling
through an “urban canyon”), the receiv-
er dynamically changes the tracking set
(i.e., satellites used in the position cal-
culation) and may fall back from 3-D to
2-D position fixes (four to three satel-
lites) if necessary.

TIMING IS EVERYTHING

Light travels approximately 1

′ per

1 ns, so when it comes to an accurate
GPS position measurement, timing is
indeed everything. No problem for the
satellites themselves, each of which
carries a high-precision atomic clock.
Better yet, a network of ground con-
trol stations continuously monitors
and, if necessary, fine-tunes the atom-
ic clocks.

But needless to say, Economics 101

tells us the commercial prospects for
GPS would be poor if each receiver
were required to have its own atomic
clock. But the typical (i.e., low-cost)
free-running crystal you find in most
consumer gear is nowhere near accu-
rate enough to deliver reliable results
over time (drift, aging) and the likely
range of operating conditions (notably
temperature). What to do? The answer
is simple. There are 24 well-main-
tained, super-accurate clocks up in the
sky. Use them.

After a GPS receiver finds even one

satellite, the first thing it does is start
using the satellite’s atomic clock-
based timing to continuously correct
its own relatively inaccurate local

Position Statement

SILICON UPDATE

by Tom Cantrell

Tom says Xemi

cs’

s Sl

i

mGPS represents a technol

ogi

cal

breakthrough that wi

l

l

bri

ng GPS

capabi

l

i

ty to a sl

ew of products l

i

ke cel

l

phones, PDAs, and economy cars. Not onl

y i

s the

ti

ny, l

ow-power, three-chi

p modul

e easy to work wi

th, i

t’

s surpri

si

ngl

y af

fordabl

e.

background image

www.circuitcellar.com

Issue 173 December 2004

79

C

IRCUIT CELLAR

®

oscillator. Typically, a GPS
receiver will deliver the cor-
rected clock to the outside
world in the form of a pulse-
per-second (PPS) output tight-
ly synchronized to GPS time.
Thus, the ultimate timing
accuracy at the receiving end
pretty much boils down to the
resolution with which the
receiver circuitry can steer the
local clock.

Ironically, even as the engi-

neer designing in a GPS
receiver struggles to achieve
accuracy, the government
imposes some ultimate lim-
its. Harkening back to its mil-
itary roots, GPS satellites put
out two streams of data. The most
precise datastream is encrypted and
reserved for the military and other
authorized users. The unencrypted
channel mere mortals can use (i.e.,
commercial GPS) can be intentionally
dithered to limit accuracy. What are a
few meters between friends?

Understandably, the military is

mostly concerned with limiting the
ability of a hostile party to use GPS
for something like a missile guidance
system. So, the government also
imposes caps on, for example, the
velocity and altitude the receiver is
allowed to output. Note that there are
loopholes that allow GPS to be used
for applications such as a high-altitude

research balloon. (High but
slow might be allowed, but
not high and fast.)

Similarly, there are practi-

cal and legal ways to get
around the inaccuracy inten-
tionally built in to the com-
mercial channel. The sim-
plest is to simply let the GPS
receiver sit awhile and aver-
age a bunch of position fixes
to filter out the noise (inten-
tional error). As noted previ-
ously, the Pentagon isn’t that
worried about accurate-but-

slow scenarios.

A more sophisticated

approach for achieving higher
accuracy is known as differ-

ential GPS (DGPS). This scheme relies
on a permanent fixed location ground-
based station with its own GPS. A
mobile DGPS receiver includes an
additional radio that receives trans-
missions from the fixed reference sta-
tion. The reference station compares
its known location with where the on-
site GPS indicates it is. The differ-

Photo 1

Twenty-four GPS satellites aren’t lost in space. Their precise position

is known at all times, so you don’t have to get lost on Earth.

background image

80

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

ence, representing the intentional
error, is then transmitted to the
remote DGPS receiver, which is listen-
ing to the same satellites. Thus, the
DGPS receiver can adjust its own posi-
tion fix by subtracting out the error as
reported by the reference station.

The result is that DGPS can deliver

astonishing accuracy, on the order of
1 m, relatively quickly. There are ref-
erence stations scattered around the
globe that are run by a mix of govern-
mental (e.g., the U.S. Coast Guard)

and commercial (e.g., survey) organi-
zations. But for most folks, plain old
GPS is more than adequate. And, as
you’ll see later, the price for basic
GPS is right—and getting better all
the time.

MAP ROOM

Booting up is a big deal for a GPS

receiver. Just consider what has to
happen when it powers up for the first
time. First, the receiver must start
searching for the signal from any satel-

lite. This is nontrivial because the sig-
nal may be weak or intermittent, and
the system relies on relatively complex
spread-spectrum coding that crams
the signals from all 24 satellites onto
a single frequency.

The receiver also needs information

that comprises the almanac, which is
a chunk of data that defines the over-
all state of the GPS system including
detailed satellite information, atmos-
pheric data, and special system mes-
sages. The GPS ground control stations
update the almanac weekly. Question:
Where does the receiver get the latest
version of the almanac? Answer: From
the first satellite it can get it hands on.
Thus, each and every GPS satellite
must repeatedly transmit the almanac,
and it usually takes approximately
10 min. for the receiver to grab a copy.
In addition, every 30 s each satellite
transmits its own ephemeris comprised
of satellite-specific and timely (updated
hourly) orbital information and clock
correction factors.

Obviously, a 10-minute-plus cold

start, as described above, is a pain for
users, so GPS receivers typically store
the latest copy of the almanac and
ephemeris in local flash memory.
Thus, cold start is typically encoun-
tered only the first time out of the
box, or in other special circumstances
such as when shipping a powered
down GPS to a distant location. If the
almanac (warm start), and better yet,
the ephemeris (hot start), in flash
memory is up to date, the so-called
time-to-first-fix is cut dramatically to
typically tens of seconds.

What if the GPS receiver thinks it

should be able to hot start (i.e.,
almanac and ephemeris in flash mem-
ory are current) but can’t find the
expected satellites? Such might be the
case for a GPS receiver in a vehicle
that enters and exits a tunnel or
canyon. As a matter of course, GPS
receivers must constantly evaluate the
current tracking set while prospecting
for a better one to decide if and when
to switch.

After the GPS receiver establishes

a good fix, it starts outputting so-
called position-velocity-time (PVT)
messages, typically once per second.
The specific list and format of the

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

81

message output may be standard, such
as the National Marine Electronics
Association standard 183 (NMEA 0183),
proprietary, or a mix of both. This
puts a bit of a burden on both the
designers and users of GPS receivers
in that both parties need to support a
variety of message formats to guarantee
interoperability.

GETTING PRETTY SMALL

It isn’t my intention to delve deeply

into the details of the GPS system
itself. That subject has been well cov-
ered in the pages of Circuit Cellar and
elsewhere. (Refer to the Resources sec-
tion at the end of this article for more
information.) So now let’s turn our
attention from how GPS works to how
easy it is to put it to work for you.

First, consider the basic functions a

GPS receiver requires. Of course, it
needs a decent radio to capture the
challenged (weak, distorted, blocked)
signals from the satellites. It
also needs high-speed process-
ing to search for and sort out
(hopefully quickly) the specif-
ic signals from multiple satel-
lites that are all riding on the
same 1575.4-MHz carrier.
Finally, the navigation plat-
form has the job of translating
the multiple flight-time meas-
urements (referred to as “pseu-
do-range” in GPS-speak) to
something useful like latitude,
longitude, and altitude—a
problem that is harder than it
sounds, and it sounds pretty
hard!

Moore’s law to the rescue.

The latest and greatest mod-
ules shrink each of the three

boxes on the GPS receiver block dia-
gram to a single chip, making for a tidy
three-chip solution. Let’s take a closer
look at an excellent example of the
new breed, the aptly named SlimGPS
from Xemics (see Figure 1).

In addition to a Colossus radio IC,

high-speed aspects of RF-to-digital
processing and baseband conversion
are handled by the XE16BB10 corre-
lator IC, which supports the capture,
extraction, and tracking of the signals
from up to eight satellites in parallel
(see Figure 2).

Beyond that, all further navigation

platform processing and storage (includ-
ing flash memory for the almanac and
ephemeris) are crammed into an
ARM7TDMI-based AT91 controller
from Atmel, an impressive demonstra-
tion that 32-bit microcontrollers have
truly come of age.

With the silicon doing the heavy

lifting, designing in SlimGPS is a

snap. There are only 24 pins to begin
with, and half of them are devoted to
power (3- to 3.65-V main supply and
1- to 3.65-V backup supply for the
built-in RTC) and ground (digital and
RF). TDI, TCK, TDO, and TMS com-
prise a JTAG test and debug interface,
and an additional pin (BTM) is used
for Board Test mode. That means
there are really just seven pins the

designer has to spend more (but not
many more) than a few moments
thinking about.

Naturally, RF IN is one of the key

ones. I’ll leave detailed discussion of
antenna design to the experts, but
SlimGPS uses an active (i.e., powered)
one supported by a low-power mode (one
of the three available) that leaves the
chips on but cuts power to the antenna.
Speaking of power consumption, even at
full throttle (i.e., when searching, track-
ing, or fixing), the module consumes
only 25 mA. At the other extreme, the
lowest power mode (everything is off
except the battery-backed RTC) sips a
mere 2 µA.

Two other relatively self-explanatory

pins are TXDA and RXDA, which com-
prise the tried-and-true UART interface
to and from your application. That
leaves you with just a final four of
GPS-centric pins: PPS, ALMRDY,
DELPOSN, and POSFIX.

As I described earlier, the pulse-per-

second (PPS) output gives your appli-
cation its own blue light special atom-
ic clock. As the name implies, after

the GPS engine is tracking,
PPS puts out a pulse (approxi-
mately 100 ms) each and every
second on the dot (i.e., the
leading edge of PPS is synchro-
nous to GPS time within
±100 ns). PPS is a better tim-
ing reference than anything
you can afford to design in, so
feel free to use it to discipline
(continuously correct) the
sloppier clocks (e.g., crystal
oscillators and application
timers) in your system.

The almanac ready (ALM-

RDY) output reflects whether
the previously described GPS
almanac stored in the AT91
on-chip flash memory is up to
date. In turn, the delete posi-

Antenna

BP

Filter

LNA

Active antenna

BP

Filter

RF+

RF–

RF

Down

converter

Q LPF I LPF

TCXO

I

Q
MCLKI
SCLK

GPS

Baseband

processor

KE1610-OEMPVT

Application

API

RTOS

First GPS

software

RX

TX

PVT

Board

interface

AT91 MCU

Colossus radio

XE16BB10

Correlator

Figure 1

The Xemics SlimGPS marks a new low—in price, power consumption, and size—for GPS implementa-

tions.

POR

Clock management

*

MCLK

*

SCLK

MSECIN

CR816

IROM

DROM

SRAM

Channel 1

Channel 2

Channel 8

MPU

PPORT

UART

TCO

GPS

TX

RX

*

PWRRF

*

IRF

*

QRF

D[7.0]
RDY
nINT
RnW
nCE

TIN

TC

TOUT

TE

V

SS

Figure 2

Key to SlimGPS streamlined implementation is the XE16BB10 cor-

relator IC. Able to track eight satellites in parallel under the supervision of a
built-in Xemics CoolRISC MCU, the XE16BB10 fills the gap between the
Colossus radio IC and the ARM-based navigation platform.

background image

low-power Standby
mode.

The TR command

allows you to pass
API calls through the
NMEA interface. API
functions include ini-
tializing the real-
time clock date and
time, setting an
approximate initial
position, or deleting
the current position
stored in flash mem-

ory (the same as
asserting the DEL-
POS pin). These are
particularly useful for

first-time, out-of-the-box situations,
where even approximate date, time,
and position information can help
SlimGPS get a head start on searching
for the initial tracking set.

EASY EVAL

The SlimGPS evaluation kit pack-

ages the GPS module with a carrier
board that also incorporates a USB
interface (see Photo 2). I got a chance
to play with one, and things pretty
much went without a hitch. Indeed,
the only glitch was with the software
installation for the USB interface, not
SlimGPS itself. Like many of the other
“formerly RS-232, now USB” gadgets
I’ve played with, Xemics uses a UART-
USB translator chip and virtual COM
port driver from FTDI.

82

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

tion (DELPOSN)
input allows for the
clearing of all data
(current position,
almanac, and
ephemeris) and trig-
gers a cold start
recomputation of the
tracking set.

POSFIX is an out-

put that toggles high
and low at 1 Hz
when the GPS
engine is searching
for satellites. It stays
low after a tracking
set is established.
Consider it kind of a
hardware quality of service (QoS) indi-
cator that could be used, for example,
to wake up your application hardware
after valid fixes become available.

MESSAGE IN A BOTTLE

As I explained, after the tracking set

is established, SlimGPS repeatedly
outputs one or more NMEA messages
that you choose from the list in
Table 1. Probably the most popular
one is RMC (i.e., $GPRMC), which
combines all of the useful information
(position, velocity, and time) in a sin-
gle message.

There’s one problem with the

NMEA standard messages though.
They are all outputs from the GPS
engine, meaning it can talk to you,
but you can’t talk to it. In order to

solve the problem, NMEA defines a
format for proprietary messages that
can go both ways. Xemics implements
10 proprietary messages (also shown
in Table 1) that allow your application
to configure and control SlimGPS
operation.

Here are some examples. The NM

command allows you to specify which
one (or more) of the nine NMEA stan-
dard messages supported that you
want SlimGPS to output, and at which
repeat rate (1 to 99 s). The PT com-
mand allows you to configure the seri-
al port format including speed (2,400
to 57,600 bps), data length (7 or 8 bits),
parity (even, odd, none), and stop bits
(1 or 2). The RT command is a soft-
ware reset with cold, warm, or hot
start options. LP puts the GPS into

Photo 2

The SlimGPS evaluation kit combines the GPS module (with three chips located near the

antenna connector) with a mezzanine UART-to-USB converter (located on the edge of the board) and an
active antenna.

Photo 3

Software that comes with the SlimGPS evaluation kit includes GPSDiag

(a)

and VisualGPS

(b)

.

The kit will also work with commercial mapping software such as

Microsoft AutoRoute Express.

a)

b)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

83

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.

SOURCES

UART-to-USB Interface and virtual
COM port driver
FTDI
www.ftdichip.com

SlimGPS module
Xemics
www.xemics.com

RESOURCES

J. Bachiochi, “Where’s Waldo?:
Pinpointing Location by Interfacing
with a GPS Receiver,” Circuit Cellar
126, January 2001.

M. Chao and L. Ming, “GPS-GSM
Mobile Navigator,” Circuit Cellar 151,
February 2003.

I. Cyliax, “Where in the World?”
Circuit Cellar

109–110,

August–September 1999.

J. Stefan, “Navigating with GPS,”
Circuit Cellar

123, October 2003.

As with most USB gear, the evalua-

tion kit documentation walks you
through a procedure that requires you to
plug in the board after the PC boots, but
no sooner. That’s so you can tell the
Microsoft New Hardware Found wizard
you’d rather do it yourself by specifically
browsing to and selecting the FTDI
driver on the CD that comes with the
kit rather than letting Microsoft do its
own thing.

But when I plugged in the Xemics

board, the Wizard didn’t show. Instead,
after the usual New Hardware Found
message, which normally precedes the
Wizard’s arrival, my PC reported that it
had indeed found the necessary soft-
ware, automatically installed it, and
returned me to the desktop. Indeed, the
installation was completely automatic,
which is presumably the way USB
should work but almost never does.

Anyway, next, the documentation

says you should install and run one of
the pair of GPS utility and mapping
software packages that come with the
kit (see Photo 3). In turn, the first step
is to tell those applications which (vir-
tual) COM port to use. Suspecting
trouble, I double-checked using the PC
Device Manager control panel to con-
firm that there was indeed an FTDI
USB driver attached to COM port 5.
But when I tried to tell the GPS appli-

cation to use COM port 5, it was
“unable to connect.” Grrrr!

Because the installation procedure

clearly had deviated from the documen-
tation (no Wizard), I was on my own.
Oh, well, if in doubt, why not try the
three-finger salute (CTL-ALT-DEL) to
reboot the PC? Sure enough, after a
reboot, the GPS application was able to
connect to COM port 5.

It was smooth sailing from then on.

After a few minutes of cold starting,
position fixes started rolling into my
PC. I found that the active antenna
supplied worked well; notably, it has a
long cable (20

′ or so) and does the job

(a decent signal-to-noise ratio from
enough satellites) sitting inside the
house on a window frame with a rela-
tively limited view of the sky.

POSITION STATEMENT

I think SlimGPS represents a break-

through for GPS. Xemics, via their dis-
tributor Future Electronics, quotes a
low-volume price of less than $50, but a
look at what’s on the board sends a clear
message: GPS is a real bargain now, and
as usual with all things silicon, the price
won’t be going up.

The onward-and-downward (in price)

momentum of Moore’s law means two
things. First, expect even more pene-
tration into existing applications. For

example, I expect GPS-based naviga-
tion systems will increasingly become
standard equipment in ever lower-end
vehicles. Indeed, at this point the cost
issue is probably more about the fancy
user interface (e.g., a high-resolution
LCD) and extra dashboard space than
the GPS circuits themselves. Along
the same lines, expect to see more
hand-held devices (e.g., cell phones
and PDAs) adding GPS to their list of
features.

To me, the most interesting aspect of

the march of silicon isn’t about doing
more of the same old same old. Rather,
it’s when cost falls below a threshold
so that brand new applications are able
to emerge and flourish. Now, thanks
mini-me implementations like
SlimGPS, I think practically anything
that moves is a candidate for GPS.

I’ve got a lot of neat project ideas.

How about you?

I

Command

Description

$GPCGA

Global positioning system fixed data

$GPGLL

Geographic position (latitude and longitude)

$GPGSA

Reports satellites used in the navigation solution

$GPGSV

Reports satellites in view and the IR elevation, azimuth, and SNR

$GPRMC

Reports position, velocity, and time (PVT)

$GPVTG

Course over ground and ground speed

$GPZDA

Time and date

$PXEMTF

Reports receiver status (e.g., almanac up to date, number of satellites in view)

$PXEMNM

Defines which NMEA 0183 messages are to be output and repeat rate

$PXEMPS

Enables/disable pulse-per-second (PPS) output

$PXEMPT

Configures serial port (e.g., speed, parity, stop bits)

$PXEMRT

Initiates receiver reset (i.e., cold, warm, or hot start)

$PXEMVR

Reports software version number and date

$PXEMGS

Defines geodetic configuration (i.e., ellipsoid used for position calculation)

$PXEMLP

Puts receiver in Low Power mode, subsequent valid command reawakens

$PXEMTR

Transparent mode—invokes underlying API function calls

Table 1

SlimGPS supports various NMEA 0183 standard output messages ($GPxxx). You can configure which

(any or all) of the standard messages are output and the repeat rate (1 to 99 s). In addition, Xemics defines propri-
etary two-way query/response commands ($PXEMxx) that allow configuring and controlling SlimGPS operation.

background image

84

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

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

″ ×× 3FORMAT. Call for current rate and deadline information. Send your disk and digital submission

sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail kc@circuitcellar.com. For more information call Sean Donnelly at (860) 872-3064.

The Suppliers D irectory at w w w.circuitcellar.com /suppliers_dir/

is your guide to a variety of engineering products and services.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

85

background image

86

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

87

background image

88

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

89

background image

90

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

91

background image

92

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 173 December 2004

93

background image

94

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Z8 Encore!-Based Audio Processor

Build a Digital Video Recorder

Microcontroller-Based Nitrox Analyzer

Signal Processing with the AduC812

PC-Controlled RC Device

Digitally Control Power Factor Correction

APPLIED PCs

Embedded Wi-Fi with TRENDnet

FROM THE BENCH

Light-to-Frequency Conversion (Part 2): Pulse and Oxygen Content

SILICON UPDATE

Hot Enough for You?: Hot Chips 16 Roundup

87

Abacom Technologies

91

All Electronics Corp.

88

AP Circuits

79

APEC

13

Arcom

88

Ashware

85

ASIX

7

Atmel

86

Bagotronix, Inc.

75

Bellin Dynamic Systems, Inc.

41

Bitscope Design

86

BusBoard Prototype Systems

80

CadSoft Computer, Inc.

89

Carl’s Electronics

90

CCS-Custom Computer Services

92

Conitec

21

Cypress PSoC Contest

1

Cypress MicroSystems

65

CWAV

53

Datadog Systems

91

DataRescue

84

Decade Engineering

66

DesignCon 2005

84

DLP Design

27

Earth Computer Technologies

87

EE Tools

(Electronic Engineering Tools)

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page

67

EMAC, Inc.

74

ESC West

30

ExpressPCB

84

FDI-Future Designs, Inc.

89

FieldServer Technologies

92

Front Panel Express

92

Futurlec

52

General Assembly

85

Hagstrom Electronics

12

HI-TECH Software, LLC

57

Holmate/Holtek Semiconductor, Inc.

56, 90

ICOP Technology, Inc.

89

IMAGEcraft

42

Imagine Tools

91

Information Analytics

85

Intec Automation, Inc.

85

Intrepid Control Systems

86

Intronics, Inc.

47

Jameco

64, 86

JK microsystems, Inc.

75

JR Kerr Automation & Engineering

11

Keil Software

53

LabJack Corp.

75

Lakeview Research

91

Lawicel HB

86

Lemon Studios

25

Lemos International

2

Link Instruments

61, 79

Linx Technologies

64

MaxStream

89

MCC (Micro Computer Control)

86

MicroControls

92

microEngineering Labs, Inc.

88

MJS Consulting

86

Mosaic Industries, Inc.

17

Mouser Electronics

95

MVS

86

Mylydia, Inc.

C2

NetBurner

53

Nurve Networks LLC

88

OKW Electronics, Inc.

93

Ontrak Control Systems

39

PCB123

71

PCBexpress

89

PCB Fab Express

C4 Parallax, Inc.

84

Phytec America LLC

87

Phyton, Inc.

93

Picofab, Inc.

84

Pulsar, Inc.

87

R2 Controls

29

R4 Systems, Inc.

Page

Page

Page

40

R.E. Smith

19,89

Rabbit Semiconductor

88, 90

Radiotronix

39

Remote Processing Corp.

93

Rogue Robotics Corp.

58

Saelig Company Inc.

87

Scidyne

3

Scott Edwards Electronics, Inc.

88

Sealevel Systems

5

Sierra Proto Express

9

Silicon Laboratories, Inc.

85

Softools

92

TAL Technologies

C3

Tech Tools

48, 49

Technologic Systems

87

Technological Arts

90

Tern, Inc.

85

Trace Systems, Inc.

91

Triangle Research Int’l, Inc.

67

Trilogy Design

24

Tri-M Systems Inc.

91

VNISource Design

93

Weeder Technologies

86

Zagros Robotics

93

Zanthic Technologies, Inc.

90

Z-World

February Issue 175

Deadlines

Space Close: Dec. 10

Material Due Date: Dec. 17

Theme:

Wireless Communication

B

ONUS

D

ISTRIBUTION

:

CTIA W

IRELESS

E

XPO

IPC P

RINTED

C

IRCUITS

E

XPO

A

TTENTION

A

DVERTISERS

Call Sean Donnelly now to

reserve your space!

860.872.3064

e-mail: sean@circuitcellar.com

INDEX OF ADVERTISERS

Preview of January Issue 174

Theme: Embedded Applications

background image
background image

96

Issue 173 December 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

have been writing my editorial for 16 years, but I still can’t predict whether or not something is going to strike a chord. I rant about significant issues

like global Internet security and RFID technology, and I get one or two e-mails about it. Another time, I’ll make a simple comment about the “paperless
office,” where I seem to have more paper than ever before, and I’ll get a couple dozen very detailed communications. These people aren’t just agreeing
with me, mind you. A subscriber comment in

Circuit Cellar’s techno-consumed readership means I get e-mails describing the medical impact of the

increased stress of maintaining a paperless office, about environmental impact studies on the paper production industry, and paper manufacturing sta-
tistics for the last 20 years. There is certainly a wealth of opinion and information in this readership. I love it.

I shouldn’t be surprised by all of the responses I got regarding last month’s editorial (www.circuitcellar.com/library/priorityinterrupt/archive.asp) in

which I described my excited revelation that all of the power leaks from wall warts around my house were adding up to hundreds of dollars a month. I
started receiving e-mails within a few hours of

Circuit Cellar’s Electronic Edition posting. Here are a few of the first ones:

“Just finished your editorial in

Circuit Cellar. As always, enjoyed it immensely. But this time I actually felt that I had something to contribute in return…A

friend recently went ‘off the grid.’ Built a big home back side of nowhere, solar panels, UPS, batteries, etc. The #1 energy waster? Those wall warts! Even

when turned off, they still suck milli-amps. This probably isn’t any great surprise to you, but it was great to see that Zilog’s eZ80 development kit had a

couple solid-state wall warts to replace the big heavy transformers. Just from my measurements I estimate their efficiency at over 98% from disconnect-

ed to fully loaded (5V at over 3A)!”—

George Warner

“I guess I’m an Amish farmer at heart. My electric bill peeks at forty dollars. Other than three X-10 switches and one X-10 floodlight everything gets

unplugged when not in use. I like the Stone Age. :-)…As for your dog Katy needing a miner’s lamp, she doesn’t need one. Dogs do not see in color. That

advantage allows them to collect more ambient light in the eye. They also go more by the sense of smell. Blind dogs can do quite well.”—

Bob Paddock

“I have been where you were when you wrote about the power consumption of ‘always on’ devices. I live in air-conditioned South Florida and I also have an

electric water heater and an electric range. Still, I consider my power bill very high. When my bill went over $450/month this summer, I started looking around.

At about 10 cents/KWh, I’m also spending about $70/month on ‘quiescent power,’ and the rest is PCs on 24×7, AV components on standby, etc.…At this point

I’m truly wondering if it’s time to get back to devices that draw nothing when they are off, and have no leakage/sense current flowing for things like X-10 switch-

es, RF and IR interfaces, etc. Maybe it’s time to look at an 89-cent solution—the old mechanical toggle light switch from Home Depot! ;-)”—

Gordon Cunningham

“The electric bill here (New York Con Edison) is 21.1648 cents per kWh. Even a single person in a small apartment can easily run over $100/month bill

without using HVAC. [In] the old days you flipped a switch to the OFF position and [the] problem was solved. Today’s appliances and gadgets remain ON

even with the switch turned OFF.”—

Dusan Benko

“I’m (thankfully ;) not running in the same league as you for home power consumption—but I became interested in characterizing power usage in my home

just about a year ago. I thought briefly about putting a current sense transformer on every circuit at the power panel, then factored my work and family

schedule and projected when that project might be complete…So, I backpedaled and started quite simply—whole house power recording [by non-intru-

sively monitoring the existing outside power meter]…The result is my WattWatcher (http://smartfamily.home.mchsi.com/Hardware/WattWatcher/). There

you can find [the complete design details and software for] this simple system and my findings on several charts from 5 minute resolution to most of the

last year. The big spikes are the electric clothes dryer.”—

Dave Smart

My hat is off to these early birds who were inspired (or riled) enough to add their opinions on a hot topic. Unfortunately, I also appreciate that the true

solution may be something I don’t like and, as Bob put it, living in the Stone Age. Certainly, there will be a compromise between energy consumption
and cost that gets the power industry replacing power-wasting transformers the same way they replaced regular light bulbs with fluorescents. We just
have to wait until they need those extra watts and they give us something more efficient as a replacement.

In the meantime, I can’t just shut off the lights. While Katy may certainly see very well in the dark, there is the unresolved issue of which one of us is

the real dog who can’t learn new tricks. We’ve both become accustomed to certain accommodations and conveniences. In her case, I’m welcome to shut
off the floodlights, but I better plan on holding a flashlight and bringing a big cookie every time she goes out at night from now on.

What’s Another Watt or Two?

PRIORITY INTERRUPT

steve.ciarcia@circuitcellar.com

by Steve Ciarcia, Founder and Editorial Director

background image
background image

Wyszukiwarka

Podobne podstrony:
circuit cellar1995 12
circuit cellar1996 12
circuit cellar1993 12
circuit cellar1994 12
circuit cellar1990 12,1991 01
circuit cellar1997 12
circuit cellar1992 12,1993 01
circuit cellar2001 12
circuit cellar2000 12
circuit cellar2002 12
circuit cellar1991 12,1992 01
circuit cellar1995 12
circuit cellar1992 12,1993 01
circuit cellar1996 12
circuit cellar1997 12

więcej podobnych podstron