circuit cellar2004 08

background image

7

9

25274 75349

0 8>

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)

#169 August 2004

Secure Your Embedded Applications

Locate Ham Radio
Repeaters On The Road

Build A Graphics LCD Driver

Improve Robot Motion Control

EMBEDDED PROGRAMMING

Secure Your Embedded Applications

Locate Ham Radio
Repeaters On The Road

Build A Graphics LCD Driver

Improve Robot Motion Control

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

W

hen you work in publishing, you often lose track of time. At any

given moment, we’re working on three different issues, which can make
it difficult to remember what month you’re in. Then again, this problem
isn’t exclusive to publishing. Have you ever had one of those moments
when someone asks you what day it is, and you just stare blankly? Then
you realize it’s the 30th and that you completely forgot to pay your phone
bill because it seemed like it arrived just two days ago. Time actually
does seem to fly by.

Although it’s only August, it’s time to start looking ahead to next year.

We’re announcing the 2005 editorial calendar this month. I hope you’ll
take a look not only to see when the next Robotics or Signal Processing
issue is, but also to see when you should submit your article proposal.
As we say, this magazine is written by engineers, for engineers. Our
readers are our best writers. So, if you have an interesting project, con-
sider turning it into an article. We’re looking for innovative applications,
practical solutions, and efficient projects.

For definitions of our monthly themes along with details about the

specific topics we’re interested in, please see the Author’s Guide on our
web site (www.circuitcellar.com/authors). We have purposely chosen
broad themes that encompass a wide spectrum of engineering.
However, with only 12 months to work with, the themes don’t cover
everything. Don’t worry if your project doesn’t fit neatly into one of the
themes; we’ll certainly find space for valuable articles that fall outside the
main categories.

Looking at the calendar below, please note that the deadlines are for

completed articles. Proposals should be sent at least one month prior to
the deadlines to be considered for specific issues.

2005 Editorial Calendar

Issue

Theme

Deadline*

174 January

Embedded Applications

October 1

175 February

Wireless Communication

November 1

176 March

Embedded Programming

December 1

177 April

Robotics

January 3

178 May

Communications

February 1

179 June

Measurement & Sensors

March 1

180 July

Internet & Connectivity

April 1

181 August

Embedded Development

May 2

182 September

Signal Processing

June 1

183 October

Analog Techniques

July 1

184 November

Graphics & Video

August 1

185 December

Data Acquisition

September 1

*Proposals should be submitted at least one month prior to the article
deadlines.

4

Issue 169 August 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 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 pub-

lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at

Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico

$31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico

$55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money

order, or check drawn on U.S. bank.

Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH

03755-5650 or call (800) 269-6301.

Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

For information on authorized reprints of articles,

contact Jeannette Ciarcia (860) 875-2199 or e-mail jciarcia@circuitcellar.com.

Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the
consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-
er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or
from plans, descriptions, or information published by Circuit Cellar®.

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

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

jennifer.huber@circuitcellar.com

TASK MANAGER

background image
background image

6

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

August 2004: Embedded Programming

4

TASK MANAGER
Looking Ahead

Jennifer Huber

8

NEW PRODUCT NEWS

edited by

John Gorsky

12

TEST YOUR EQ

edited by

David Tweed

FEATURES

COLUMNS

DEPARTMENTS

94

INDEX OF ADVERTISERS

September Preview

96

PRIORITY INTERRUPT
Cyber Dossiers

Steve Ciarcia

48

FROM THE BENCH

Is There a Robot in Your Future?

Emerging Robot Technologies
Jeff Bachiochi

62

ABOVE THE GROUND PLANE

Stepper Drive (Part 1)

Analog
Ed Nisley

68

APPLIED PCs

PSoC 101

Fred Eady

78

SILICON UPDATE

Motoring (Part 2)

Motor Control Chips and Software

14

Ham Radio Repeater Locator

Glen Worstell

22

Understanding Embedded Security

Joe Grand

28

PICs, DRAMs, and Graphic Displays

Build a Graphics LCD Driver
Tom Napier

34

Closed-Loop Motion Control for Mobile Robotics

Rich LeGrand

52

E-Field Sensor-Based Monitoring System

Seenath Punnakkal & Sameer Cholayil

Innovative Robots (p. 48)

Quieting the Stepper Drive (p. 62)

Find Repeaters on the Road (p. 14)

background image
background image

and 16 to 24 bytes of data RAM. These devices also fea-
ture a precision 4-MHz internal oscillator, 33 instructions,
two stack levels, 25-mA source/sink current I/O, and a
low-power (100 nA) sleep current. In addition, they also
have a wide operating voltage range (from 2 to 5.5 V), one

8-bit timer, a watchdog timer,
in-circuit serial programming
(ICSP) technology, power-on
reset, power-saving Sleep mode,
and an analog comparator mod-
ule (in the PIC10F204 and
PIC10F206 only).

The PIC10F200, PIC10F202,

PIC10F204, and PIC10F206 are
offered in six-pin SOT-23 pack-
ages. In 10,000-piece quantities,
the PIC10F200 is $0.49, the
PIC10F202 and PIC10F204 are
$0.57, and the PIC10F206 is
$0.65.

Microchip Technology, Inc.
www.microchip.com

8

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

SIX-PIN MICROCONTROLLER

The PIC10Fxxx family, which is comprised of the world’s

smallest microcontrollers, packs the high performance of
the PIC microcontroller architecture into the ultra-small
form factor of an SOT-23 package for highly space-con-
strained and extremely low-cost applications. These revolu-
tionary six-pin flash devices pro-
vide an ideal solution for many
markets and applicaitons not
typically served by microcon-
trollers today, including “elec-
tronic glue” to enable easy bug
fixes for ASIC and PCB designs
and to replace standard logic and
timing components or traditional
mechanical timers and switches.

The PIC10Fxxx 8-bit flash

memory microcontroller family
debuts with four members
(PIC10F200, PIC10F202,
PIC10F204, and PIC10F206) that
offer 256 to 512 instructions
(multiplied by 12-bit program
words) of flash program memory

Edited by John Gorsky

LOW-POWER, MULTIRATE LIMITING AMPLIFIERS

The MAX3747/MAX3747A are low-power, multirate

limiting amplifiers with a programmable loss-of-signal
(LOS) indicator. Operating from a single 3.3-V supply, the
devices have better than 4-mV input sensitivity and 120-µV
RMS input-referred noise, while consuming only 60 mW.
Each amplifier has a programmable signal-detect function
that can be set to different assert and deassert levels while
maintaining a 2-dB hysteresis. The MAX3747 features low
13-ps deterministic jitter and less than 3.5-ps RMS random
jitter. The devices accept input voltages from 4 to 1,200
mV, and provide 500- (MAX3747) or 800-mV

PP

(MAX3747A)

output swing.

The MAX3747/MAX3747A are packaged in a 3-mm, 10-

pin microMAX. They operate over an extended tempera-
ture range (–40° to 85°C). Prices start at $4.50 in 1,000-
piece quantities. An evaluation kit is available.

Maxim Integrated Products
www.maxim-ic.com

PC/104 GPS RECEIVER

The OrbiTrak 8R is a low-cost GPS receiver designed

for mobile and vehicular PC/104 embedded computer sys-
tems. Supporting both NMEA 0183 and TAIP ASCII pro-
tocols, as well as binary TSIP GPS data formats, the board
integrates an eight-channel Trimble Lassen LP GPS mod-
ule, two TTL serial ports, 16 digital I/O, external battery
backup, odometer input, and clock input.

The OrbiTrak 8R can be used with any of Parvus’s

SpacePC series CPU boards. It interfaces with the host
through a standard
16C550-compatible
UART to provide a
direct connection to
most commercial navi-
gation or map software
packages.

This product is

specifically designed
for vehicle navigation,
telematics, location,
and fleet management systems, as well as marine, air-
borne, and any other application that requires navigation,
tracking, data logging, timing, and communication func-
tions in a small and rugged form factor. The OrbiTrak
8R’s fast satellite signal acquisition and low-power con-
sumption make it an ideal choice for a variety of mobile
and battery-powered applications.

The OrbiTrak 8R costs $239 each in volume orders of

100 or more units.

Parvus Corp.
www.parvus.com

background image
background image

10

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

POWER SYSTEM-ON-A-CHIP IN A SMALL PACKAGE

The EN5330 is the first of the iPOWER line of integrated

DC-to-DC converters for use in point-of-load applications.
The first to feature an integrated inductor, the EN5330
reduces real estate requirements and the part count by
more than half while slashing development costs and time-
to-market. This approach capitalizes on semiconductor
geometry advances that enable a 10× switching-frequency

POWER SUPPLY DESIGN TOOL

The PI Expert Suite 5.0 is a power supply design tool

that delivers short design times for switched-mode power
supplies (SMPS) built with Power Integrations’s highly scal-
able power conversion integrated
circuits. The PC-based software
automates the design of fly-back,
forward-converter, and buck-topolo-
gy power supplies. It uses an intu-
itive user interface and new pro-
ductivity-enhancing features.

The new software suite consists

of three major components: PI
Expert Design Software, PIXIs
Designer, and PI Viewer. PI Expert
Design Software is an interactive
program that takes your power sup-
ply specifications and automatical-
ly determines the critical compo-
nents needed to generate an energy-
efficient switch-mode power sup-
ply. These include transformer
specifications, bulk input capaci-
tance, and the selection of the cor-
rect power conversion IC.

PIXls Designer offers spreadsheet design support for

recently released products as well as for users who prefer a
simplified spreadsheet approach. PI Viewer allows the
viewing of designs created with previous versions of PI
Expert.

improvement, integrating a PWM controller, output FETs,
and magnetic components into a single turnkey IC pack-
age.

The EN5330 is in a DFN TSSOP footprint package that

covers just over 100 mm

2

of board space. Including the

minimum of three external components, the entire DC-to-
DC converter can be placed in as little as 135 mm

2

of sin-

gle-sided, or 102 mm

2

of double-sided, board space.

Operation from common voltage rails of 2.5, 3.3, and 5 V

is achieved with a wide input voltage range from 2.375 to
6.5 V. With up to 3 A, or 10 W, of output power, the output
voltage is VID pin selectable with options for seven stan-
dard voltages (0.8 to 3.3 V) and a resistor divider setting
that enables a continuous set-point range from 0.8 V to
VIN. The EN5330 can be used in a sequenced start-up with
a programmable soft-start time and a separate enable func-
tion. Full protection functionality is offered with overcur-
rent, short-circuit, over-voltage, under-voltage, and ther-
mal shutdown features.

The EN5330 is available in standard and lead-free pack-

age options. Pricing is $4.95 each for orders in 1,000-unit
quantities. Product evaluation boards are available.

Enpirion, Inc.
www.enpirion.com

This new PI Expert Design Software version has under-

gone a major redesign and expansion. Enhancements
include a greatly improved user interface, a new Design

Wizard that guides you to the best
circuit topology, and the best
device family to fit the power sup-
ply requirements. It also adds an
interactive schematic diagram fea-
turing GUI circuit blocks for easy
user modification, a design naviga-
tion tree for simultaneously
browsing multiple designs, and
new design forms to determine
resistor values to implement over-
voltage and under-voltage protec-
tion and to set external current
limit.

The CD-ROM also contains a

complete library of the company’s
latest datasheets and application
notes, as well as a mirror copy of
the company’s web site.

PI Expert Suite V. 5.0 is offered

free of charge and may be downloaded from www.pow-
erint.com or through the company’s worldwide distributor
network.

Power Integrations
www.powerint.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

11

NEW PRODUCT NEWS

THYRISTOR SURGE-PROTECTIVE DEVICES

The new ThyZorb family of surface-mount thyristor

surge-protective devices provides excellent clamping per-
formance with bidirectional crowbar protection, maximum
break-over voltage values ranging from 70 to 395 V, and
surge capabilities up to 100 A. Surge capabilities of 50 A
(10/1000 µs) are available for devices in both the SMA and
SMB packages, with values up to 100 A (10/1000 µs) avail-
able in the larger SMB package. Used as direct replace-
ments for industry-standard devices with the same part

numbers, the new ThyZorb products offer clamping specifi-
cations as much as 10% better. Lower break-over voltages
and a fast turn-on time reduce “let-thru” voltages that may
damage sensitive telecom circuits. A low typical leakage
current of less than 50 nA is another advantage of ThyZorb
devices. The minimum holding current for the devices is
150 mA, with a stand-off voltage range from 55 to 320 V.

Although avalanche-type transient voltage suppressors

that share the same size and voltage rating will clamp at a
given breakdown voltage, the new ThyZorb thyristor surge-
protective devices feature a crowbar action that enables
switching from a high-impedance, high-voltage “off” state
to a low-impedance, low-voltage “on” state, which in turn
allows the devices to redirect current surges to ground.
Because the voltage across the ThyZorb device collapses
when the voltage and current exceed a predetermined
break-over level, the device can handle significantly higher
levels of surge current than an avalanche-type TVS.

Pricing for U.S. delivery in 10,000-piece quantities ranges

from $0.14 to $0.24 per piece.

Vishay Semiconductors
(631) 300-3816
www.vishay.com

background image

12

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

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

Test Y

Your E

EQ

Problem 2

In what sense does a noninverting

amplifier configuration put more strain on an op-amp
relative to an inverting amplifier configuration?

Problem 3

What is “endianness” (big endian

versus little endian)? Why might one be preferred
over the other?

Problem 4

What is a data scrambler and what is

it for?

Contributed by David Tweed

Edited by David Tweed

Problem 1

A two-layer mirror is designed to provide

total cancellation of reflected energy at a particular
wavelength. The front surface is partially reflecting. The
back surface is totally reflecting, and the thickness is
such that light from the back surface is out-of-phase with
respect to the light from the front at that wavelength (i.e.,
the mirror is an odd multiple of a quarter-wavelength
thick).

Keeping in mind that the front surface also reflects

internally, creating multiple reflections before all the light
escapes again (see the diagram), what is the reflection
coefficient (K) required to achieve total cancellation of the
light?

Fully

reflecting

Partially

reflecting

1–K

Incident wave

In phase

Out of phase

In of phase

Out of phase

Etc.

K

background image
background image

14

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

O

n a recent drive through several

western states, I took along a 2-meter
amateur (ham) transceiver to relieve
the monotony. I enjoyed chatting with
other hams along the route, and often
obtained useful information about
local attractions and road conditions.

Because 2-m communications (144

to 148 MHz) are normally line-of-
sight, the amateur radio community
has, over the years, built repeaters at
many strategic locations throughout
the U.S. and in some other countries.
These repeaters allow amateurs to com-
municate over much longer distances
than would otherwise be possible. The
repeaters receive transmissions and
simultaneously rebroadcast them on a
frequency 600 kHz away.

In order to program the radio

for the frequencies of the nearby
repeaters, I had to consult an
American Radio Relay League
(ARRL) book that gives repeater
locations and frequencies. After
driving some distance, I had to
reprogram the ham transceiver
for the new nearby repeater fre-
quencies. The repeater locations
are given as cities or mountain
names, and they have to be
found on a map to see which
ones are nearby. This is time-
consuming, difficult, and danger-
ous to do without stopping.

During one long stretch in

Montana, it occurred to me that
there must be a better way, and so
the Ham Radio Repeater Locator
(HRRL) was born. The HRRL
consists of a Zilog Z8 Encore!
microcomputer with the locations

which is presented here. If you’re
implementing the first version, I
encourage you to switch to this one
because I added several nice features.

DISPLAY AND OPERATION

The display’s top two lines show the

distances in miles to the nearest eight
repeaters (see Photo 1). The third line
shows detailed information for one of
the eight repeaters. The first digit
shows the number that corresponds to
one of the eight repeaters. Pressing the
station-select button results in the
next repeater being selected, cycling
back to the first after the eighth is
selected. The rest of the third line
shows the repeater frequency and the

tone information if the repeater
requires tone access.

The last line shows the cur-

rent time (UTC) on the left, the
call sign of the selected repeater,
and a counter on the right. The
counter increments each time
the GPS position changes by
enough to affect the distances. If
GPS information is lost, the UTC
is replaced by a “NO GPS” mes-
sage, alerting you that the infor-
mation is no longer current. A red
LED blinks once per second to
assure you that that the system is
still alive. This is an extremely
useful feature during debug!

A single character following

each of the distances in the first
two lines shows the approxi-
mate bearing to the correspon-
ding repeater. Bearings, which
are given as “n,” “s,” “e,” and
“w,” are only accurate to

±

45°.

Ham Radio Repeater Locator

FEATURE ARTICLE

by Glen Worstell

and frequencies of several thousand
repeaters stored in its flash memory, an
interface to a GPS receiver that gives
the current location of the car, and the
ubiquitous 4 × 16 alphanumeric LCD,
which shows the selected repeaters.

The system displays the distance to

the nearest eight repeaters, and a detail
line shows the frequency and tone for
the selected repeater. An interface to
my ham radio transceiver is used to
automatically program its scan memory
to scan the nearest repeaters, eliminat-
ing the need to change the tuning of the
radio as new repeaters come into range.

Winning the Z8 Encore! International

Design Contest inspired me to work
on a second version of the HRRL,

Ham radio enthusiasts no longer have to manually tune the radio as new repeaters come into
range. Glen’s Ham Radio Repeater Locator consists of a Zilog microcomputer with the loca-
tions and frequencies of several thousand repeaters stored in its flash memory. The system
displays the distance to the nearest eight repeaters and more.

Photo 1—

The display’s top two lines show the distances in miles to the

nearest eight repeaters. Pressing the station-select button (the red but-
ton on the left) selects the next repeater. The third line shows the
repeater frequency and the tone information for the selected repeater.
The forth line gives the UTC, the call sign of the selected repeater, and
an update counter that changes with each new GPS position.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

15

DATABASE

There are about 8,000 repeaters in

the U.S. and Canada, so it’s necessary
to carefully design the data storage in
order to fit all the repeater informa-
tion and the program into the 64 KB
of flash memory available in the
Z8F6401. Experience with the first
version of the program led me to add
the call letters of each repeater station
to the database. This made it impossi-
ble to fit all 8,000 repeaters in the
available memory. But, a substantial
fraction fit, enough to satisfy anyone
who is driving through 49 states
(Hawaii is not included) and Canada.

Table 1 shows the required database

information and the number of bits of
storage allocated. A change in latitude
of 1 gree is equal to slightly greater
than one mile, which is judged to be
sufficient resolution for the HRRL.

The database is stored sorted by fre-

quency in order to reduce the number
of bits required for frequency informa-
tion. Frequencies are in the range of
144 to 148 MHz, and all stations are
on 5-kHz increments.

REPEATER INFORMATION

I had hoped to find an Internet site

with repeater locations and frequen-
cies available for download, but no
such service is offered. There are some
localized databases for certain states,
and users in those locations may be
able to make use of them.

The printed ARRL repeater directo-

ry costs approximately $10, but manu-
ally entering the data is tedious. The
translation to latitude-longitude is
also tedious and inaccurate because

When listening to a repeater with an

interesting conversation, it’s annoying
to lose it when another repeater
comes closer. So, there is a “sticky
bit” for each of the eight repeaters
currently being scanned. To toggle the
bit for a particular repeater, first select
the repeater with the station-select
switch, and then toggle the bit with the
“sticky bit” switch. When the sticky
bit is on for a particular repeater, the
direction display changes to uppercase
letters (N, S, E, and W), and the station
will not be replaced even when anoth-
er station becomes closer.

ACCURACY AND MATH

Precise distances to repeaters are

not required, so to simplify calcula-
tions and make the code smaller, I
decided to shoot for an accuracy of
approximately plus or minus two
miles for repeaters that are within
approximately 100 miles.

Various factors affect accuracy:

repeater locations are stored to an accu-
racy of about one mile; the exact loca-
tions of the repeaters are unknown; the
algorithm for determining distances has
a small error under certain situations;
and the integer arithmetic used is sub-
ject to truncation and rounding errors.
Tests on the finished algorithms show
errors within the desired range.

Given two points on the surface of

the earth, a straightforward trigonom-
etry formula gives the distance
between the points. Although the
Zilog C compiler includes floating-
point libraries, I used integer arith-
metic throughout in order to avoid
the size of floating-point arithmetic

and transcendental rou-
tines. Speed is not really
an issue for this project,
but integer routines are
faster of course.

The distance between

two points on the same
longitude (a north-south
line) is about 69 miles per
degree of latitude. For
points on the same latitude
(an east-west line), the dis-
tance is 69 miles per
degree of longitude only at
the equator, shrinking to
zero at the poles. The for-
mula for the distance along a line of
constant latitude is 69 miles per
degree of longitude multiplied by the
cosine of the latitude.

The HRRL program calculates the

legs of a right triangle using the formu-
las in Figure 1. The correction factor for
the leg of constant latitude is taken to
be the cosine of the average latitude of
the two points, and the cosine is calcu-
lated with a look-up table. The error
caused by this approximation is negli-
gible for distances less than 100 miles.

Division is slow and takes notice-

able code space, even for integers. The
HRRL code does no division except by
powers of two, which can be imple-
mented by shifts. For example, to
convert delta latitude—which is
expressed in grees (a “gree” is defined
as one-fiftieth of a degree)—to miles,
it’s necessary to multiply by the ratio
69/50. The code uses the ratio 11/8 to
avoid an integer divide, with a result-
ing error of only approximately one-
third of a mile in 100 miles.

Variable

Bits

Comments

Station latitude

11

Stored as grees relative to 24°N

Station longitude

12

Stored as grees relative to 60°W

Tone

6

Index into a look-up table with a capacity of 63 tones (51 are used)

Frequency

7

Stored as a 5-kHz increment relative to the frequency of the previous
station

Offset direction (+ or –)

1

First letter of call

3

The first letter is always K, W, N, A, or V

Second letter

5

Stored as an offset from A

Digit of station call

4

Third, fourth, and fifth letters 15

Each letter is stored as an offset from A

Total

64

Stored as four 16-bit integers

Station

GPS position

b =

Longitude[cos(average latitude)]

a =

Latitude

c = (a

2

+ b

2

)

Figure 1—

Given two points on the surface of the earth, a spherical

trigonometry formula gives the distance between the points. In order to
avoid lengthy code, the familiar formula for the length of the hypotenuse
of a right triangle is used instead, with an accuracy that’s close enough
(within a mile or so) for any repeaters within range.

Table 1—

The data storage scheme is carefully designed in order to fit as much repeater information as is possible

into the Z8F6401’s flash memory along with the program. By using only as many bits as is necessary for each
parameter, it’s possible to have a database of more than 6,000 repeaters. (The total number of repeaters in the
U.S. is approximately 8,000.)

background image

16

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

the locations of the repeaters are
given as the names of cities and
geological features.

The ARRL sells a CD contain-

ing the locations, but it’s pricey
and the CD database has the
locations of the repeaters
encrypted for some strange rea-
son. It isn’t too difficult to extract the
necessary latitude-longitude informa-
tion, which I did for my project. Refer
to the LCC program listings on the
Circuit Cellar

ftp site for the details.

Because the information is copyright-
ed, I included only a small sample
database as part of the project files.

If you only need repeaters for a

small area, you can manually create a
text file with one line per repeater.
Tabs separate fields, and all fields
must be present (enter zero for the
tone field if no tone is required). The
fields, in order, are: latitude in
degrees, longitude, frequency in
megahertz, plus or minus for offset,
call, and tone in hertz. Figure 2 is an
example line.

Several programs have been written

to aid in the creation of the repeater
database. For example, the datagen
program converts a text file in the
aforementioned format to the C data
array used by the microcomputer. The
auxiliary programs were written with
the free Windows lcc-win32 compiler.

CONSTRUCTION

The circuit is straightforward (see

Figure 3). I built the system using a
single-sided breadboard with holes on
0.1

centers. The solder side of the

board has horizontal traces connecting
all the holes in a row. I find that using
this breadboard yields a much neater
layout than using one that just has
holes with no traces. Use a Dremel tool

to cut the traces when necessary.
A magnifying glass or microscope
makes the procedure easy. You can
purchase the blank board from
Radio Shack or other suppliers.

Surface-mount resistors, capaci-

tors, and transistors can be mount-
ed on the circuit side of the board.

Through-hole components can be
mounted on the other side. Components
and jumpers are aligned vertically.

An option for construction would be

to use the Zilog Z8F642 evaluation
kit, which includes a full C compiler,
a simulator, program/debug interface
hardware, and a board containing most
of the required circuitry. A breadboard
area could be used to add the few
remaining parts. At $40, this system
represents a real bargain. The Zilog
board includes a Z8F6421 microcom-
puter part, which is a pin-compatible
replacement for the Z8F6401 used in
the HRRL. No software changes should
be required to use the latter part.

Note the R2 resistor labeled near the

optical isolator. You may need to use a

30.344546 95.869632 145.150000 — N5RXL 203.500000

Figure 2—

The repeater database text file has one line per repeater.

Tabs separate the fields. All fields must be present. (Enter zero for the
tone field if no tone is required.) The fields, in order, are as follows: sta-
tion latitude in degrees, station longitude in degrees, frequency in
megahertz, plus or minus for offset, call, and tone in hertz. An auxiliary
program converts the data to the format needed by the microcomputer.

Figure 3—

There are two regulators, one for 5 V to run the LCD and another for 3.3 V to run the microcomputer. An optically isolated interface to the Icom CIV programming

bus is used to reduce receiver noise caused by ground loops. The ubiquitous MAX232 is used to interface to the PC serial ports. (The data line currently isn’t used.) The
microcomputer can be programmed with Zilog software by connecting the debug line to a serial port on your PC.

background image
background image

18

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

resistor here in order to speed
up the rise time of the isola-
tor. By experimenting, I found
that a 100-k

resistor was

needed with the particular
isolator I used.

GPS DATA

Most small GPS receivers

have an output in NMEA-
0183 format, which is an
asynchronous serial datas-
tream of ASCII characters
sent at 4,800 bps (start bit,
8 data bits, 1 stop bit). The
signal is nominally 0 V for a
mark condition and 5 V for a
space condition. Connecting a
terminal or terminal emulator
can monitor the GPS output.
Most computers with an RS-232 input
will work correctly even though these
levels are not RS-232 standard.

I used a Garmin GPSMAP 295 for

this project, but almost any GPS
receiver should work. It may be neces-
sary to look at the output format of
your receiver and modify the parsing
routines for different formats. The
routine to parse the GPS’s latitude
and longitude output was written for
easy modification.

CIRCUIT SPECIFICS

The system is intended for mobile

use, so power comes from your vehi-
cle’s 12-V battery. A 5-V regulator sup-
plies the LCD module, and a 3.3-V
regulator (driven by the output of the
5-V regulator) is used to drive the
Zilog microcomputer. Because the
microcomputer outputs are 5-V toler-
ant, they can be used to drive the
display directly.

A 10-MHz crystal supplies the sys-

tem clock. The crystal frequency is
not important, but if a different crys-
tal is used, the UART clock division
must be changed accordingly.

A single transistor interfaces the

GPS NMEA-0183 output, which varies
between 0 and 5 V, to the 3.3-V UART
input of the microcontroller. The tran-
sistor also provides the necessary
phase inversion.

A normally open switch is used to

signal the microcontroller to select the
next station for frequency and tone dis-

play. Another switch is used to toggle
the sticky bit for the selected station.

As an aid to debugging, and to let

you know that all is well, a red LED
is connected to one of the microcon-
troller’s I/O lines. It is often useful to
have such an indicator during the ini-
tial stages of hardware and software
development. As I said earlier, the
LED blinks once per second.

An interface circuit is provided so

the HRRL can automatically program
your ham radio transceiver. The one
shown in Figure 3 is designed for use
with the Icom 746-PRO “CIV” bus. A
different circuit may be needed for
other transceiver brands.

As you can see in Photo 2, there are

three ministereo audio connectors on
the back of the HRRL that are used
for serial interfaces: the Zilog debug
interface, the output to program the
2-m radio (CIV), and a connector for a
serial interface to a PC (not currently
used). A future version of the program
will use this interface for program-
ming the database. (The current ver-
sion requires a recompile of the soft-
ware to update the database followed
by a download of the new code
through the debug port.)

SOFTWARE OPERATION

The system is interrupt-driven

because it is necessary to be able to
take care of inputs that come asyn-
chronously. A background process
takes care of the major function—cal-

culating the distance to all the
stations in the database.

There are two interrupt rou-

tines: GPS character received
and timer 10-ms interrupt.
The background routine cycles
through the database of
repeaters and calculates the
distance to each one. A global
variable gives the current lati-
tude and longitude values.
Because this is can be changed
by the GPS receiver, the back-
ground disables interrupts
before copying the latitude and
longitude information to a local
variable, which is then used
throughout the main loop.

The GPS receiver sends

characters at 4,800 bps. A line

of characters giving latitude, longitude,
and time is sent twice per second.

A state machine guides the parsing

of the GPS data with a simple string
defining the parse operations. The
state of the parse is an index into the
parse string. When a new character
comes along, it is handled according
to the definition in the parse string.
This scheme makes it extremely easy
to change the parsing according to
your needs. For example, it’s easy to
add a checksum calculation.
Information about signal strength,
date, and altitude can be extracted
from the GPS datastream.

A timer interrupt occurs every 10 ms.

A number of different things happen
in response to a timer interrupt: a
counter is incremented to determine if
valid GPS information hasn’t arrived
for several seconds; the station-select
switch is polled to see if you want to
display information for a different sta-
tion, and switch debounce is also han-
dled; the sticky-bit switch is serviced;
the LED is turned on and off at a 1-s
rate; and a new character is sent to the
LCD if it needs service.

Commonly used LCD modules

don’t have a signal to indicate that
they’re ready for the next character to
be displayed. They will not accept
characters at the rate that the micro-
controller could send them. Therefore,
it’s necessary either to poll the display
to see if it’s ready for another charac-
ter or wait for a specified time (often

Photo 2—

Moving from left to right, the rear panel has wires to 12 VDC (to a

cigarette lighter socket), the power switch, three ministereo jacks that connect
to a PC serial port for programming, a PC serial port running a terminal emula-
tor (currently not used), and the Icom IC-746PRO programming bus. The wires
on the right go to the GPS receiver.

background image
background image

20

Issue 169 August 2004

CIRCUIT CELLAR

®

SOURCES

GPSMAP 295
Garmin International, Inc.
(913) 397-8200
www.garmin.com

IC-746PRO Programming bus
Icom America, Inc.
(425) 454-8155
www.icomamerica.com

lcc-win32 C compiler
www.cs.virginia.edu/~lcc-win32

Z8F6401 Microcontroller
Zilog, Inc.
(408) 558-8500
www.zilog.com

approximately 40 µs) before sending
the next character.

In order to avoid the loss of CPU

cycles required by the polling method,
the software uses the delay approach.
A new character is sent every 10 ms
to the LCD (if there are characters
remaining to be sent) in response to a
timer interrupt. This is much slower
than possible, but it’s faster than
what’s necessary for this application.

A buffer of the LCD characters is

kept in the

lcdBuf array. Although it

isn’t strictly necessary to buffer the
LCD information, the microcon-
troller is blessed with plenty of
RAM. This approach makes the code
clean and straightforward.

Whenever a routine finishes writing

to the buffer, it increments a line-to-
be-written byte (

ltbw) that indicates

to the interrupt routine that the corre-
sponding line of characters should be
written to the display.

MODULAR CODE

It’s possible to write modular code

in C language, even though not all the
capabilities of languages like Modula-II
are available. Much of the popularity of
object-oriented code comes from the
fact that it’s easy to write modular code
in object-oriented languages. For many
embedded applications, you don’t need
objects and won’t derive any benefits
by using them. However, understand-
ability and maintainability are benefits
derived by using modular code, even
for fairly small projects like this one.
One of my goals was to present the
code in an easy-to-understand format.

Listing 1 is an example of a module

used to calculate the distance between
a station and the current GPS posi-
tion. When a routine is in a module,
its name is prefixed by the module
name. The

funcs module contains

various functions, so the routine is
called

funcs_u16milesBetween().

In C language it’s extremely impor-

tant to keep track of the integer vari-
able sizes because the compiler some-
times performs conversions that you
don’t want. To emphasize the sizes of
variables, I often use definitions such
as

U8 for an 8-bit unsigned variable.

These definitions are collected in a
#include file for use by all modules.

Occasionally, when it’s important for

clarity, I use Hungarian notation, which
includes the type information in a
variable or function name. The
milesBetween() function returns an
unsigned 16-bit integer, so the function
name emphasizes that important fact. A
square-root function named

i32Sqrt()

is called and to make it clear that the
function returns a 32-bit integer.

Warning: there are bugs in the com-

piler that are likely to show up when
complicated expressions are used.
Hence the otherwise unnecessary
temporary variables like

index and

temp. The code would be harder to
read without the temporary variables,
so it’s probably better that it’s written
this way. The compiler bugs force
good coding practice!

IN OPERATION

The Ham Radio Repeater Locator

breadboard is now in use. It performs
just as I had envisioned.

If there is sufficient interest, a PCB

could be provided, perhaps with a pre-
programmed microcomputer. It would
be nice if you could obtain the
ARRL’s permission to include its
repeater database, or if you could find
another source of repeater informa-
tion. A switch-selectable interface to
various popular transceivers would be
a worthwhile addition.

I

Glen Worstell (M.S.E.E., M.B.A.) is a
consultant specializing in hardware

PROJECT FILES

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

RESOURCES

NMEA-0183 Information, www.xs4all.nl
/~erkooi/YL/nmea0183.html.

Spherical trigonometry formulas,
williams.best.vwh.net/avform.htm.

Listing 1

You can calculate the distance between a station and the current GPS position. Note that when a

routine is in a module, its name is prefixed by the module name.

U16 funcs_u16milesBetween()

// Returns 16-bit unsigned integer

{

I16 deltaLat;

// 16-bit integer

I16 deltaLon;

U8 index;

// 8-bit unsigned integer

I32 temp;

// 32-bit integer

deltaLat = stnLat-myLat;

deltaLon = stnLon-myLon;

// Index into cosine correction table.

// Cosine table gives ratio, assuming a divide by 256.

index = (stnLat+myLat) >> 7;

deltaLon = (I32)deltaLon*cosLookup[index] >> 8;

temp =

(I32)deltaLat*(I32)deltaLat+(I32)deltaLon*(I32)deltaLon;

// Convert degrees to miles by multiplying by 69/50. To avoid

// division, use 11/8, which is extremely close.

temp = (i32Sqrt(temp)*11) >> 3; // Distance in miles

return (U16)temp;

}

and software development for
embedded systems. He enjoys trav-
eling with his sweetheart, Sue
Worstell, and their too many ani-
mals in the “Zoomobile” (their
motor home). You can reach Glen at
worstell@copper.net.

background image
background image

tions whose theft could result in the
loss of millions of dollars.

When defining the security enve-

lope of your product, there are three
questions you should ask yourself (or
your design team). First, what needs
to be protected? Identify the critical
components in your circuit that need
to be protected before you start con-
struction. It’s extremely difficult to
implement proper security mechanisms
after the fact. Such components to pro-
tect may include specific algorithms,
device identifiers, digital media, bio-
metrics, cryptographic keys, or product
firmware. In addition to protecting dis-
crete data contents, you may be inter-
ested in implementing a secure product
boot sequence, secure field programma-
bility, or a secure remote-management
interface. Be aware that in some cases,
even noncritical portions of your design
can unknowingly compromise the secu-
rity of the system, especially if they
fail in an unanticipated way.

Second, why is it being protected?

In most situations, critical data is
being protected to prevent a specific
attack threat. Ignoring or overlooking
the possibility of attack can lead to a
vulnerable product. In some countries,
protecting certain content may be a leg-
islative requirement. For example, a
medical device containing confidential
patient information must be secured in
order to meet the U.S. Health Insurance
Portability and Accountability Act
(HIPAA) requirements.

Finally, whom are you protecting

against? The types of attackers vary,

22

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

P

rotecting products and intellectual

property (IP) from attackers is a fairly
new concept that many engineers have
not yet had to face. It is only a matter
of time, though, until products—which
are becoming more embedded and inte-
grated with the real world—become tar-
gets for attacks leading to theft of
service, loss of revenue, or a damaged
corporate reputation. Consumer elec-
tronics, financial and medical technolo-
gy, and network products are all at risk.

In this article, I’ll focus on the “why”

and the “what” of embedded security,
also known as secure hardware. Why
does it matter? Why is it important to
you, the designer? In what ways can
someone attack your product? Because
you can’t incorporate secure design
methods without understanding what
you are protecting and why, this arti-
cle is a fitting introduction to the
complexities of embedded security.

Reading this article won’t turn you

into a security expert overnight. Nor
will it provide all the answers to your
secure hardware design needs. But, it
will help you understand the major
classes of attack and the mindsets of
potential attackers. Actual secure
hardware mechanisms come in all
shapes and sizes, ranging from tamper-
resistant enclosures to embedded IC
dies in PCBs (to make them more dif-
ficult to probe). I’ll discuss these in a
future Circuit Cellar article.

What embedded security typically

comes down to is this: Is the cost of a
successful attack greater than the
value of what’s being protected? I’ll

The more literate you are on the subject of embedded security the better. But it’s a com-
plicated topic, so where should you begin? In this article, Joe shows you how to reduce
the number of vulnerabilities in your embedded designs and evaluate the threats against
your products. Designing offensively may be your best protection against attack.

present some guidelines to help you
make a determination.

UNDERSTAND YOUR RISK

As with everything in engineering,

embedded security is all about trade-
offs—risk management, as they say in
the business world. Are there compo-
nents or data in your system that need
to be protected? If so, how much is it
worth to protect them?

Forget what the glossy marketing

material says about security products.
There’s never a single answer and a
single product to solve everybody’s
product security needs. Every product
has its own threat risks and is suscepti-
ble to certain types of attacks. Before
being able to make an educated,
informed decision, you need to under-
stand the threat, the value of the con-
tents being protected, and the reason for
protecting such contents. Essentially,
weaker, more vulnerable devices
should contain less valuable secrets.

For example, a priceless family heir-

loom might be stored in a fireproof
and tool-resistant safe. However, it
wouldn’t make much financial sense
to purchase such a safe to store an eas-
ily replaceable, inexpensive piece of
jewelry. By the same token, it would-
n’t be feasible to implement an
extremely secure, multilayered hard-
ware solution just to protect a single
password that is used to access undoc-
umented features in a mobile phone;
but, it would be in order to protect a
financial institution’s cryptographic
keys used for encrypted communica-

FEATURE ARTICLE

by Joe Grand

Understanding Embedded Security

background image

cation token, smartcard, biometric read-
er, or one-time-password generator. The
attacker’s main goal is to gain access to
personalized data and systems by spoof-
ing the identity of the legitimate user.

Privilege escalation (or feature unlock-

ing) attacks are aimed at accessing the
hidden/undocumented features of a
product and increasing the amount of
control given to the user without having
legitimate credentials. For example,
using specialized circuitry to communi-
cate with a mobile phone to gain access
to phone diagnostics or acquiring admin-
istrator access on a network appliance.

Generally, an attack is achieved in

one of three ways. In a focused attack,
the adversary brings the target product
into a private location to analyze and
attack it on his or her own time with
little risk of being discovered. A focused
attack is probably the most familiar
type of attack. Consider a curious stu-
dent modifying a piece of hardware in
his dorm room or a more determined
criminal in a laboratory attempting to
crack encryption routines.

Lunchtime attacks often take place

during a small window of opportunity,
such as a lunch or coffee break.
Typically, the attack would need to be
completed in a short period of time,
ranging from a few minutes to a few
hours. Lunchtime attacks are risky
because they are easily detected if the
target product is missing or has visibly
been tampered with. For example, if you
check your coat at a restaurant, an
attacker could remove your PDA,
retrieve the desired data, and return the
PDA to your coat pocket within a mat-
ter of minutes and without being detect-
ed. Another example is an attacker copy-
ing data from a target’s authentication
token or USB thumb drive that they left
on their desk while attending a meeting.

Finally, there’s the insider attack,

which may come in the form of run-
on fraud by a manufacturer (producing
additional identical units of a product
to be sold on the gray market) or a dis-
gruntled employee willing to sabotage
the product or sell critical information
such as system firmware or encryption
keys. Many, but not all, insider threats
can be thwarted with strict compart-
mentalization of critical data, access
control, and chain-of-custody policies.

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

23

ranging from a curious, harmless hard-
ware hacker to an entire group of
researchers backed by a competitor,
organized crime, or government. As
such, it’s important to attempt to
properly identify the skill level and
theoretical goals of the primary
attackers against your product.

As a designer, you have the chal-

lenging task and responsibility of creat-
ing and ensuring your system’s security.
You must understand every possible
aspect of the design and are typically
constrained by technical, financial, and
political agendas. Attackers have an eas-
ier job, which is to exploit insecurities
in the system. They need only to discov-
er one vulnerable area of the design, and
they typically have few constraints on
their methods. They’ll likely choose
the attack that yields the best results in
the easiest and most repeatable fashion.

CLASSES OF ATTACK

No system will ever be 100%

secure. “Secure” simply can be
defined as when the time and money
required to break the product is
greater than the benefits to be derived
from the effort. Given enough deter-
mination, time, and resources, an
attacker can break any system.

At the highest level, four classes of

security threat exist, as described by
C.P. Pfleeger in Security in Computing.
Through interception (or eavesdropping)
an attacker can gain access to protect-
ed information without opening the
product. With embedded systems, this
can be achieved by monitoring the
external interfaces of the device and by
analyzing compromising signals within
electromagnetic radiation or current
fluctuations. On a computer network,
this can be done by illicitly copying
data or through promiscuous mode net-
work monitoring. Although a loss may
be discovered fairly quickly for certain
attacks, like credit card theft or
spoofed user authentication, a silent
interceptor might not leave any traces.

Interruption (or fault generation) is

a threat because an asset of a product
becomes unavailable, unusable, or
removed. An example is the malicious
destruction of a hardware device, the
intentional erasure of program or data
contents, or a denial-of-service net-

work attack. Fault generation consists
of intentionally provoking malfunc-
tions, such as operating the device
under abnormal environmental condi-
tions, which may lead to the bypass-
ing of certain security measures.

The third type of threat is modifica-

tion, which involves tampering with a
product’s asset. Modification is typi-
cally an invasive technique for both
hardware (e.g., circuit modifications or
microprobing) and software/firmware
(e.g., changing the values of data or
altering a program so that it performs
a different computation).

Lastly, fabrication creates counterfeit

assets in a product or system.
Fabrication can come in many forms,
including adding data to a device,
inserting spurious transactions into a
bus or interface, and a man-in-the-mid-
dle attack on a network. Sometimes
these additions can be detected as for-
geries, but if skillfully done, they may
be indistinguishable from the real thing.

TYPICAL ATTACK GOALS

When a product is targeted, the

attacker usually has a goal in mind.
This may be a simple goal, such as
reverse engineering the circuitry in
order to personalize or customize the
device, or a more dedicated one, such
as retrieving cryptographic keys or
sensitive product trade secrets.

The specific goal of an attack tends

to fit into one of four categories. The
first is competition (or cloning), which
is a scenario in which an attacker
(usually a competitor) reverse engi-
neers or copies specific IP in order to
gain an advantage in the marketplace.
The goal is to improve a product by
using the stolen technology or to sell
lower-priced knockoffs. Common tar-
get areas are circuit board features
and product firmware.

Theft-of-service attacks aim to

obtain a service for free that usually
requires payment. Examples include
mobile phone cloning, bypassing copy
protection schemes on video game
systems, and modifying cable boxes to
receive extra channels.

User authentication (or spoofing)

attacks are typically focused on prod-
ucts that are used to verify the
owner’s identity, such as an authenti-

background image

24

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

PRODUCT ACCESS

There are many ways an attacker can

gain access to your product, but it
often corresponds directly to the attack
goal and usually involves one of four
methods. In the first instance, the
attacker purchases the product through
a retail outlet, often with no means of
detection (e.g., paying with cash).
Multiple products could be purchased,
with the first few serving as disposable
units to aid in reverse engineering or to
discover any existing tamper mecha-
nisms. This scenario may be financially
prohibitive for low-budget attackers
but is typical for most focused attacks.

In the second instance, the attacker

rents or leases the product from a ven-
dor, distributor, or rental company, often
on a monthly basis. Most attack types
are possible in this instance, but because
there is a high risk of detection when
the product is returned, attackers will be
cautious not to tamper with it.

In some cases, the attacker does not

own the target product. The product is
in active operation and may belong to a
specific person (e.g., a mobile phone or
smartcard), but the attacker may have
physical access to the product. This is
the most difficult type of attack
because risk of detection is high.

In the final scenario, the attacker

does not have access to the product, so
all attacks are performed remotely
(e.g., through a wired or wireless net-
work). The attacker does not require
special hardware tools and can easily
mask his location. The risk of detec-
tion is low. Remote access attacks are
common against computer networking
equipment and appliances, such as
routers, firewalls, access points, web
servers, and storage area networks.

UNDERSTAND THE ATTACKER

“The only way to stop an attacker is

to think like one.” That’s a favorite say-
ing of mine. An FBI profiler tries to put
himself in the mind of his subject. You
must do the same when figuring out
what, if any, security features you need
to implement in our design. Today,
because of advances in technology, the
lower cost of products, and easy access
to once-specialized tools, attacks against
hardware are becoming more prevalent.

Attackers can be classified into

three groups depending on their expect-
ed abilities and strengths: class I (clever
outsiders), class II (knowledgeable insid-
ers), and class III (funded organizations).
This classification is essentially an
industry standard for describing
attackers in an academic fashion.

[1]

Class I attackers are often extremely

intelligent but might have insufficient
knowledge of the system. They might
have access to only moderately sophisti-
cated equipment. They often try to take
advantage of an existing weakness in
the system rather than try to create one.
Sometimes referred to as “script kid-
dies” in the computer security indus-
try, these attackers run preprogrammed
scripts to exploit known security vul-
nerabilities instead of finding their own.

Class II attackers have a substantial

amount of specialized technical educa-
tion and experience. They have a decent
knowledge of the product or system,
and often have highly sophisticated
tools and instruments for analysis.

Class III attackers are teams of spe-

cialists with related and complemen-
tary skills backed by great funding.
They are capable of performing in-
depth system analysis, designing
sophisticated attacks, and using the

most advanced analysis tools.
They may use Class II adver-
saries as part of the attack team.

Table 1 is comparison of each

attacker class against available
resources. The table may help to
visualize the capabilities of the
various attacker groups.

ADDING SECURITY

Security is a process, not a

product. Security must be
designed into your product during
the conceptual design phase, and

it should be considered for every por-
tion of the design. It must be continual-
ly monitored and updated in order to
have the maximum effect against
attacks. Security can’t be added to a
product and forgotten about. The
product won’t remain secure forever.

Many times, an engineering change

will be made to the product circuitry or
firmware without a reevaluation of sys-
tem security. Without a process in place
to analyze changes throughout the
design cycle, security that was properly
implemented at the beginning of the
design may become irrelevant by the
time the product goes into production.

The primary concern is to incorpo-

rate risk analysis and security consid-
erations into each step of your prod-
uct’s development life cycle. Five
principles, which are based on recom-
mendations from the National
Institute of Standards and Technology,
serve as a good checklist. For more
information, refer to “Engineering
Principles for Information Technology
Security (A Baseline for Achieving
Security)” by G. Stoneburner et al.
Let’s take a look at each one.

First, treat security as an integral

part of your overall product design. It’s
extremely difficult to implement secu-
rity measures properly and successful-
ly after a system has been developed.

Second, reduce risk to an acceptable

level. Elimination of all risk is not cost-
effective and likely impossible because
nothing is 100% secure. A cost-bene-
fit analysis should be conducted for
each proposed secure hardware mech-
anism to ensure that it is performing
its intended task at a desired cost.

Next, implement layered security.

(Ensure no single point of failure.)

Table 1—

Take a look at each attacker class compared to available resources. As you can see, each class has specific

capabilities that will play a part in determining your product’s risk of attack.

[2]

Resource

Class I

Class II

Class III

Class III

(curious hardware hacker) (academic)

(organized crime)

(government)

Time

Limited

Moderate

Large

Large

Budget

Less than $1,000

$10,000 to $100,000 Greater than $100,000 Unknown

Creativity Varies

High

Varies

Varies

Detectability

High

High

Low

Low

Goal

Challenge/prestige

Publicity

Money

Varies

Number

Many

Moderate

Few

Unknown

Organized

No

No

Yes

Yes

Releases information Yes

Yes

Varies No

about attack

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

25

Consider a layered approach of multi-
ple security mechanisms to protect
against a specific threat or to reduce
overall vulnerability.

Fourth, minimize the system ele-

ments you’re relying on. Security
measures include people, operations,
and technology. The system should be
designed so that a minimum number
of elements need to be trusted in order
to maintain protection. Put all your
eggs in one basket by isolating all crit-
ical content in one secure area (physi-
cal or virtual) instead of having multi-
ple secure areas throughout the
design. This way, you can focus on
properly securing and testing a single
critical area of the product instead of
numerous disparate areas.

Finally, don’t implement unneces-

sary security mechanisms. Every secu-
rity mechanism should support one or
more defined goals. Extra measures
should not be implemented if they do
not support a goal because they could
add unneeded complexity to the sys-
tem and are potential sources of addi-
tional vulnerabilities.

KEYS TO THE KINGDOM

Understanding and evaluating the

risks and threats against your product
is the first step toward a successful
secure hardware design. There are
many combinations of potential vul-
nerabilities, and it’s impossible to pre-
vent against all of them. The good
news is that vendors have recognized
the need for embedded security, and
we’re starting to see ICs and modules
that reflect that. The more you can
spread the word to your colleagues
about making secure products, the
safer all of us will be.

I’ve just started to scratch the sur-

face of the embedded security topic. In
a future article, I’ll take a no-nonsense
look at a wide variety of practical
secure hardware design solutions that
you can implement in your product.

I

Joe Grand is president of Grand Idea
Studio, Inc., a product development
and intellectual property licensing
firm, where he specializes in embed-
ded system design, computer security
research, and inventing new concepts
and technologies. Joe holds a B.S.C.E.

REFERENCES

[1] D.G. Abraham et al, “Transaction

Security System,” IBM Systems
Journal

, vol. 30, no. 2, 1991,

www.research.ibm.com/journal/sj/3
02/ibmsj3002G.pdf.

RESOURCES

C.P. Pfleeger, Security in Computing,
2nd ed., Prentice Hall, 2000.

G. Stoneburner et al., “Engineering
Principles for Information Technology
Security (A Baseline for Achieving
Security),” NIST Special Publication
800-27, June 2001, csrc.nist.gov/publi-
cations/nistpubs/800-27/sp800-27.pdf.

[2] P. Kocher, “Crypto Due Diligence,”

RSA Conference 2000.

from Boston University. His interests
include competitive running, collect-
ing classic video games, and banging
on drums. You may contact Joe at
joe@grandideastudio.com.

background image
background image
background image

nates at the frame rate. In the com-
mercial world this is a neat job for an
ASIC. Not having such technology
available, I wondered if I could build a
driver from a PIC microcontroller
rather than a bunch of TTL chips. (For
all I know, Steve Ciarcia’s favorite
programming language still might be
solder; I’d far rather change a line or
two of PIC code than tear out wiring
and move chips around.)

My first draft had a PIC16C57

microcontroller, an 8-KB static RAM
chip, an address latch, and five shift
registers. You’ll be relieved to know
that things had evolved considerably
by the final version; I got it down to a
PIC chip and two 16-pin RAM chips.
The result is a versatile graphics LCD
driver—my gateway to graphics termi-
nals, special-purpose computers, and
pocket oscilloscopes (see Photo 1).

PAINTING A PICTURE

The RAM and driver are kept

busy sending an image to the
display. How does that image
get there? At some point, new
addresses must be presented to
the RAM chip and new bytes
written, albeit to the page the
display isn’t currently using.

A large computer could easily

create a display image in its
own RAM and copy this to the
display RAM. I was planning
around a relatively simple
device with little memory of its

28

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

H

ad you seen me unsoldering 16-pin

memory chips from a 1983-vintage PC
motherboard, you might have wondered
what rational purpose I had in mind.
Let me sketch the circuitous (apt word)
path that brought me to this expedient.

I’ve always found the smaller PIC

microcontrollers difficult to expand to
do jobs their on-chip facilities can’t
handle. For example, even with an
external address latch, extra RAM ties
up virtually all the I/O ports. Coupling
32-KB RAM and EPROM chips to a
PIC16C57 is a real pain.

Interfacing to serial EEPROM is rela-

tively simple, if slow. A serial RAM chip
in the same eight-pin package would be
a handy part, but if anyone makes one, I
haven’t heard of it. But, when the neces-
sity arose, I found a close approximation.

DRIVE A GRAPHICS LCD

It all started when I took another

look at a project I’d abandoned
nearly 10 years ago. Back then,
I’d bought a surplus graphics
LCD and wired a hardware driv-
er for it. This was hard to
debug, and I never got it to
work. The display’s ambiguous
timing specification didn’t help.

Unlike character displays,

graphics displays have only a
one-line memory, so they
require constant refreshing from
external memory. Displays
come in various formats, but I’ll
use a 64 × 240 display as an

Sometimes you have to mix old and new technology to meet your specific design needs. Tom
knows this well. He recently followed this line of thought to build a multipurpose graphics LCD
driver, which he hopes to use for applications such as a graphics terminal and a pocket oscil-
loscope. The serial interface for the display includes a PIC16C57 and old RAM chips.

example. To drive its 15,360 pixels
you need at least 1,920 bytes of RAM.
Given twice as much, you can prepare
a new page while still displaying the
previous one. After the page is ready,
flipping one address bit swaps the dis-
play function to the newly written
page, leaving the other ready to be
cleared and reused.

Each input line requires 240 bits

sent to the display at approximately
1 Mbps. The onscreen line they go to
cycles automatically through the
32 lines comprising the upper half of
the screen. A second simultaneous
serial input drives the lower 32 screen
lines. Using byte-wide RAM, you need
two shift register chips to convert
each of 2 bytes to serial form.

As well as addressing memory, the

driving device has to supply a shift
clock, a line sync pulse, a frame sync
pulse and a square wave that alter-

FEATURE ARTICLE

by Tom Napier

Photo 1—

The final version of the graphics LCD driver used two fewer

chips than had been expected.

Build a Graphics LCD Driver

PICs, DRAMs, and Graphic Displays

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

29

Another plus is that the visible and

hidden display screens occupy 16 Kb
in each 64-Kb chip. If these are allo-
cated to the first and fifth eighths of a
chip, only 32 row addresses need to be
refreshed. Eight refresh cycles per dis-
play line are sufficient.

A PIC FOR THE JOB?

The maximum bit clock the display

can handle is 3.3 MHz. The minimum
for a flicker-free display is unspecified,
but I found 75 frames per second satis-
factory. This is a mean clock rate of
576 kHz; the peak rate is higher.

In a counted loop, a PIC with a 20-

MHz crystal can generate one pulse
per microsecond. The alternative,
straight-line code, can generate short
bursts of square clock pulses at 2.5 MHz.
In my original byte-wide concept, a
burst of eight such pulses sent the
contents of the two shift registers to
the display. The shift registers were
then reloaded from RAM.

It wasn’t until late in the design

process that I escaped this hardware-
oriented byte-wide mindset. I finally
solved a knotty time allocation prob-
lem by treating each 240-bit display
line as eight words of 30 bits rather
than 15 words of 16 bits.

To read each successive bit from

dynamic RAM, the PIC supplies a new
column address as well as CAS-
down/CAS-up instructions. Adding a
“port register increment” instruction
to each cycle supplies the column

own, such as another PIC. It would
rather create a picture from dot, line,
and character graphics primitives sent
via a serial interface.

What scuppered plan A was that

byte-wide RAM. Changing one pixel
meant reading a byte, modifying it,
and rewriting it. The external device
had to drive not only a 12-bit address
register, but also to read and write an
8-bit data register. This seemed dis-
tinctly inelegant.

LET’S BE DYNAMIC

The answer was 1-bit wide memory.

Not having designed dynamic RAM
into a commercial product for 20 years,
I didn’t immediately consider it as an
alternative to byte-wide static RAM.
But, after some reflection, I saw it
offers many advantages. I needed two
serial datastreams. Why serialize a
byte when I could use two bit-wide
RAM chips? Because they were the
same size (16-pin DIP) as my output
shift registers, the space used by the
28-pin static RAM chip essentially
vanished. After more, I plunged into
the jungle of RAS, CAS, and refresh.
(Refer to the “Dynamic RAM” sidebar
for more information.)

In this application, the dynamic

chip’s separate input and output pins
are a plus. That’s why I didn’t use 2 bits
of a 4-bit-wide dynamic RAM chip. (I
briefly considered another viable but
cumbersome solution, using 2 bits of
a 32K × 8 bit static RAM chip.)

Having to multiplex the address bits

is also an advantage. With a static RAM
I would need an address latch and a
latch-enable bit. I was still ahead with
half as many address pins, even after
adding RAS and CAS signals. Memory
refresh, the other bugaboo of dynamic
RAM, turned out to be not too difficult.

I settled on two NEC µPD4164

chips, hence my foray into PC arche-
ology. (Jameco sells similar 64K × 1 bit
chips for approximately $0.60.) These
chips predate the introduction of CAS-
before-RAS refresh; but, as you’ll see, I
couldn’t have used it anyway. Beware:
the power and ground pins on 16- and
18-pin dynamic RAM chips are the
opposite way around from TTL chips.

ADDRESSING THE RAM

Each page (256 bits) of a 64-KB RAM

chip can drive one line of the display.
At first glance, it seemed I could set the
row address once per line. The fine print
tells a different story. RAS mustn’t
remain low for more than 10 µs. At
the speed I’m running, that’s enough
time to read 13 bits.

To refresh dynamic memory, you

must cycle through 128 row addresses
within 2 ms. In this application, the
row address changes once per line (too
slowly for a proper refresh), so several
refresh cycles must be inserted into
each line. Because the refresh operation
constantly changes the row address
anyway, you can write several new bits
per line without further disruption.

DYNAMIC RAM

Although dynamic RAM by the gigabit is buried inside

all of your computers, you may be unfamiliar with its
peculiar operation. This is a quick primer.

Dynamic RAM is dense and inexpensive because it

takes only one FET and a microscopic capacitor to store a
bit. Its row and column address a specific bit in an array
of such cells. The row and column addresses are multi-
plexed on the same input pins, allowing smaller, and thus
cheaper, packaging to be used.

Each chip requires a row address strobe (RAS), whose

falling edge latches the row address on the input pins.
This input is then changed to the column address, which
is latched by the column address strobe (CAS). CAS also
acts as the output enable signal. After some tens of
nanoseconds, a valid data bit appears at the output. If the
write enable pin is low during the low CAS pulse, data

on the input pin is written to the selected memory cell.
Even slow chips can supply a new bit every 200 ns; mod-
ern ones run at three times that speed.

The 16-pin chips I used are 1 bit wide. They take 8-bit

row and column addresses, have separate input and output
pins, and no chip-select input. More modern chips may
have four common I/O pins, a separate chip select pin,
and much larger capacities.

Because bits are stored on capacitors that tend to discharge

(hence “dynamic” memory), every bit has to be read and
rewritten every few milliseconds. This refresh process takes
place internally, one row at a time. It suffices to access
128 row addresses, either by a read/write operation or by a
do-nothing RAS operation, once every 2 ms. Refresh has
to be taken into account in the system design and may, as
in this case, be a determining factor.

background image

30

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

address. Generating the display clock
takes one more instruction, so a bit-
send cycle now takes four instruc-
tions, or 0.8 µs.

As I mentioned, the limitation on

the RAS pulse length allowed me to
make a virtue of a necessity. The row
address is restored 16 times per line.
Each time, 15 data bits, each from a
different column address, are sent in a
burst. This takes about 13 µs, so you
see I’ve taken a liberty with the 10-µs
RAS low period.

The main program loop, which does

a RAM refresh and sends 30 bits to the
display, repeats every 256 instruction
periods. Everything else is squeezed
into the spare 80 or so instructions of
a loop. This involved writing some
neat multitasking code.

MEMORY MAPS

Each display line is allocated 256 con-

secutive bits of RAM, although 16 are
unused (64 × 256 pixel displays exist
and would use these bits). A half-
frame of data (8,192 bits) is stored at
physical addresses 0000H to 1FFFH in
one chip. The other half of the same
frame is stored at the same addresses in
the other chip. The alternate
page is stored at addresses
8000H to 9FFFH in both chips.

As far as the user is con-

cerned, physical location is
irrelevant. There is a hidden
screen and a visible screen, and
two control characters select
to which the input goes. Pixel
and text cursors determine
where the input appears on the
screen. (Because both screens
use the same cursors, it would
be impractical to write to more
than one screen at any given
time.) Clearing either screen
resets both cursors.

INPUT INTERFACE #1

I planned to use this display

driver in several projects, so I
tried to make its interface as
simple and universal as prac-
tical. My first draft had a
24-bit shift register contain-
ing an address and a data
byte. These drove the parallel
RAM chip directly.

As soon as I’d decided to use

dynamic RAM, it was obvious that
the PIC could read the input shift reg-
ister and output a RAM address and a
data bit. Involving the PIC in the
input process let me send text as
ASCII characters. The PIC translates
these into graphics, relieving the
source device of the burden of trans-
mitting 40 pixels per character.

It appeared that, with some ingenu-

ity, a 16-bit input shift register would
suffice, so I built a prototype. The
source device had to generate 16-bit
data, clock pulses, and a handshake.
That version got as far as displaying
text and test patterns sent by another
PIC so I knew I was heading in the
right direction.

Unfortunately, I’m a perfectionist.

Having to transmit 16 bits for each
text character bugged me. I worked
out a protocol that let me send bytes
or words with one shift register, and
then realized that an on-chip UART
would make a lot more sense.

INPUT INTERFACE #2

Being used to implementing bit-

banging serial interfaces on small

PICs, I asked myself the fateful ques-
tion, Could a PIC16C57 drive the dis-
play and simultaneously handle serial
input? A quick calculation showed
that the answer is yes. The firmware
was already time-multiplexing several
tasks. Adding one more would be
tough but not impossible. That’s why
my production version uses only a
PIC and two DRAMs. Its three-chip
schematic is shown in Figure 1.

I realized that driving the system

from a normal serial terminal would
make my life, and presumably yours,
much simpler. Getting there involved
an extensive rewrite of my original
firmware and several weeks of strug-
gling with code where everything
must happen in the right priority
order in a loop that is always 256
instructions long.

Here’s how it works now: Each dis-

play line is sent as eight segments each
occupying 256 instruction periods. The
crystal frequency is 19.6608 MHz, so a
segment occupies 52.083 µs. That,
you’ll notice, is half a bit period at
9,600 bps. Segments start with a
RAM refresh operation and two word-
transmit operations. A serial input

Figure 1—

This serial interface for a graphics display is built from a PIC16C57 and some old RAM chips.

background image
background image

32

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

sample is read on every second seg-
ment. What happens during the rest of
the segment depends on a series of
task-pending flags. Every eighth seg-
ment is allocated to the display’s line
sync and frame sync pulses. A complete
screen refresh takes 256 segments and
occurs 75 times per second.

READING INPUT

Serial input happens in quasi-syn-

chronism with the input characters. If
no character is being received, the
input is sampled for a start bit. When
one is found, the segment counter is
cleared. Bits are then sampled and
shifted into a register every time the
counter is even. An offset is added so
that all bits are sampled within a
quarter bit of their midpoints.

When the counter reaches 16, the shift

register content is transferred to a buffer
register. By the time the input stop bit
has arrived, the counter has reached 18.
The reading flag is cleared and the
search for another start bit commences.

Input bytes with their most signifi-

cant bits clear are either text or con-
trol characters. Setting the text or
pixel cursors takes a pair of bytes, the
first of which has its most significant
bit set. Note that it is stored until the
second byte arrives.

If a byte is a text character, the next

eight segments are allocated to copy-
ing 5-bit horizontal font segments

from the PIC’s ROM to the display
RAM at the current text cursor posi-
tion. Because characters cannot arrive
more often than once every 20 seg-
ments, there is no need to buffer them.

Many control characters can be

interpreted and executed in one seg-
ment. Others cause some long-term
process to be carried out. For example,
erasing a screen takes 960 segments at
16 RAM bits per segment. This may
seem slow, but if nothing more impor-
tant is going on, it takes only 50 ms.

Writing real-time code of this nature

is extremely time-consuming. It final-
ly worked, but I suggest that modify-
ing the published code should not be
undertaken lightly.

COMMAND SET

The controlling device sends a mix

of 1-byte text or control characters and
2-byte cursor commands. A byte with
its MSB set is the first byte of a cursor
set command. The next bit specifies
whether the graphics or text cursor is
set. In both cases, the remaining 6 bits
specify a display row. The following
byte specifies the column. Control
characters are provided to set or clear
the pixel at the cursor.

In addition to the absolute cursor

setting words, four control characters
step the cursor in one of four direc-
tions. Two more controls specify
whether it is the graphics or the text
cursor that moves. The graphics cur-
sor steps one pixel at a time. That
pixel then can be set or cleared, allow-
ing lines to be drawn step by step. A
text cursor step is six pixels horizon-
tally or eight vertically. The initial
text cursor can be placed anywhere on
the screen; it need not be aligned with
fixed rows and columns.

A byte with its MSB cleared is an

ASCII text character. Unless it’s a con-
trol character, it’s stored at the current
text cursor position. The cursor then
steps six pixels right and, after reaching
the end of the line, steps to the next one.

As you can see in Table 1, 15 con-

trol characters perform single opera-
tions; some are even related to their
ASCII function. That leaves 16 control
characters for future expansion.

You can direct inputs (and screen

clear commands) to either the visible

Command Action
1 ctrl-A Clear pixel
2 ctrl-B Enable text cursor
3 ctrl-C

Enable graphics cursor

4 ctrl-D Cursor right
5 ctrl-E

Cursor left

6 ctrl-F

Cursor up

7 ctrl-G Cursor down
8 ctrl-H Backspace
9 ctrl-I

Set pixel

10 ctrl-J New line
11 ctrl-K Swap hidden/visible screens
12 ctrl-L Clear input screen
13 ctrl-M New line
14 ctrl-N Write to visible screen
15 ctrl-O Write to hidden screen

Two-byte controls:
Set text cursor to X,Y 10YYYYYY XXXXXXXX
Set graphics cursor to X,Y 11YYYYYY XXXXXXXX

Table 1

Control characters and 2-byte cursor setting

words allow the input device to manipulate the display.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

33

screen or the hidden screen. One com-
mand swaps the visible and hidden
screens. Typically, input is directed to
the hidden screen. To update the dis-
play, the hidden screen is cleared and
then filled with new text or graphical
input. The swap command then dis-
plays this new material. Interactive
input can be achieved by setting the
visible screen as the input destination.

Four commands step either the graph-

ics or text cursors. Two other com-
mands select which is affected and the
step size, pixel or character. The 16-bit
cursor set instructions can place either
cursor anywhere on the screen. Two
further commands set and clear the
pixel at the current graphics cursor.

For maximum system compatibility,

the LF and CR controls perform the
same job, returning the text cursor to
its left-most position and adding one
line height. The horizontal position
remains compatible with any cursor
offset set by the user. The BS charac-
ter steps the cursor backwards but
does not delete the existing charac-
ter. This will be overwritten by any
new input.

HARDWARE INTERFACE

Because I anticipated making a

direct connection between this display
driver and the device performing the
actual work, the serial interface is a
PIC input pin. As RS-232 receiver
chips invert, I gave this input the
opposite polarity from a normal serial
interface (i.e., TTL-high represents
stop and data high; low is start and
data low). My prototype has a
MAX233 RS-232 driver chip on it to
suit the input device.

In my case this input device is a

Tandy model 100 portable computer.
Its extra shift keys let it send any 8-bit
ASCII signal. Although it’s now of
legal drinking age, I still use it almost
daily as a test terminal and portable
writing implement.

WHENCE THE DISPLAY?

Note that 64 × 240 is a common dis-

play size. Examples can be purchased
from surplus dealers for less than $25.
(They fetch over $100 new.) Mine hap-
pened to be a Supertex STK24064G, so
I’ve followed its protocol here. Other

Tom Napier is a writer and electron-
ics consultant who often applies his
past experience to improve his present
designs.

SOURCES

PIC16C57 Microcontroller
Microchip Technology, Inc.
(480) 792-7200
www.microchip.com

µPD4164
NEC Electronics Corp.
(408) 588-6000
www.necel.com

PROJECT FILES

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

displays may work the same way or
have more or less subtle differences
that, with luck, can be accommodated
in the firmware. For example, a 64 ×
256 LCD should require only minor
changes. I also have a 128 × 240 line
display. It takes 60 4-bit words per
line and cycles through all 128 lines
in turn. I’ll need two more RAM
chips to drive it.

Displays run from 5 V and a nega-

tive supply in the –9- to –20-V region.
Check the maker’s spec before apply-
ing power. Some work in reflective
mode, others have an electrolumines-
cent backlight that needs a 400-Hz,
600-VAC driver. I’ve left these messy
details off the schematic.

Less than 2 mA is needed from the

negative supply, so a rather trivial
DC-DC converter can generate it. If
you add a self-powered RS-232 I/O
chip, you can tap off enough –10 V
from it to power the display. The
contrast adjustment voltage comes
from a 100-k

trimmer between

ground and the negative supply. Even
using NMOS RAM and a MAX233,
the total power consumption was
only 24 mA at 5 V.

Meanwhile, having discovered that

small dynamic RAM chips aren’t hard
to interface to PICs, I’m going to sal-
vage some more. They’ll keep me
going until that hypothetical serial
RAM chip comes along.

I

background image

34

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

T

he mechanical components that

make up robots aren’t getting much
cheaper. That’s the bad news. The good
news, of course, is that electronics and
processors continue their steady march
toward higher performance and lower
cost. As an engineer, you have to figure
out how to use the extra resources and
capabilities most effectively. In some
cases, extra processing allows you to
use lower-cost mechanical compo-
nents, which can effectively reduce
the system’s overall cost.

With this idea in mind, I’ll tackle the

robot drive train armed with a modest
amount of computing power. When I’m
done, you’ll have two different closed-
loop drive train designs that would
make R2-D2’s head spin with envy. I’ll
show you how to accomplish this
using inexpensive permanent
magnet motors and a clever feed-
back scheme that requires no
mechanical overhead. Let’s begin
by addressing the topic of motors.

MOTOR OPTIONS

Clearly, selecting a motor is one

of the most important decisions to
make when designing the drive
train. If you’ve played with motors
and gears, you’ve certainly devel-
oped the following intuition: more
gear reduction results in less speed
and more torque, and less gear
reduction results in more speed and
less torque. Modified RC servomo-
tors, which are often used in robot
drive trains, have large gear reduc-
tions (typically 300:1) resulting in
high torques and low speeds. As a

to the motor, the robot takes much
longer to stop. With less gear reduc-
tion, the robot will coast!

Sometimes stopping quickly is impor-

tant (e.g., stairs ahead), or your robot
may do something hazardous to its
health. This brings up an important
point: motors with high gear reduc-
tions stop quickly when power is
removed. But this is a silly reason to use
these motors. It’s like telling a begin-
ning driver to drive only in first gear to
avoid getting into an accident. What the
driver really needs is better driving
skills. Similarly, what you need is a
better motor controller.

CLOSING THE LOOP

A motor controller that doesn’t receive

any feedback information from the

motor is an open-loop controller.
The main advantage of open-loop
controllers is simplicity. All that’s
required is a way to control the
voltage or current going to the
motor. The Lego Mindstorms RCX
controller, for example, uses an
open-loop motor controller that
allows you to select from several
voltages (by varying the pulse-
width modulator duty cycle)
depending on how much speed and
torque you want to deliver to your
robot’s wheels.

A disadvantage of open-loop con-

trol is inaccuracy. Others include
the inability to deal with uncon-
trollable variables such as bumps
in a floor, inclines, and low batter-
ies, which can create an undesir-
able situation by slowing or stop-

Closed-Loop Motion Control for Mobile Robotics

FEATURE ARTICLE

by Rich LeGrand

result, robots that use them are typically
slow. Large gear reductions make some
problems easier, as you’ll see, but no one
wants a slow robot if they can help it. If
you’ve used these motors, you might
have wanted to trade in some torque
for some speed.

The 9-V Lego motors shown in Photo 1

are readily available. They are part of
the Mindstorms kit, so you can build
the rest of your robot base out of
Legos, which is a good thing for the
mechanically challenged like me.

Fortunately, the Lego motor has

much less gear reduction (14:1) and is
well suited for attaching a wheel direct-
ly to the output shaft. If you’ve done
this, you know that you get a quick
robot, but it’s difficult to control.
Particularly, when you shut off power

Rich recently came up with two closed-loop drive train designs for mobile robots. All it took
were some inexpensive permanent magnet motors and a simple feedback scheme. In this
article, he covers everything from PID control and tuning to trajectory generation and opera-
tional space control for two robot bases. He also explains the software.

Photo 1—

Lego is an excellent medium for implementing robots such as

the four-wheeled HUMR. The Gameboy Advance acts as the controller

and

provides 32-bit RISC processing performance, a color LCD, and sound.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

35

taken literally. A control loop typically
entails a software loop that repeatedly
executes a control algorithm. Each rep-
etition of the control algorithm is
called a control cycle. The control algo-
rithm can be described simply with the
following expressions, which are eval-
uated once per control cycle:

Basically, there is a function, f, which
determines the value to send to your
controller (V

CONTROL

) as a function of the

error. V

MEASURED

is the measured (sensed)

value, and V

DESIRED

is the desired (com-

manded) value. The difference between
the values is the control error. Note
that one of the simplest control meth-
ods is the bang-bang controller, which
you can find in your thermostat.

My thermostat doesn’t automatical-

ly select between heating and cooling;
it would be nice if it did. Many robots
use bang-bang controllers for their
motors. However, PID control is a
much more effective technique:

V

k

k

CONTROL

( )

( )

( )

= V

+

V

+ V

PROPORTIONAL

INTEGRAL

DERIVATIVE

E

PROPORTIONAL

P

INTEGRAL

I

V

= K error

V

= K

k

k

k

k

( )

( )

×

( )

( )

×

error j

k

j

( )

( )

×

( )

= 0

k

DERIVATIVE

D

V

= K error k

error k

k

1

error k = V

k

V

k

DESIRED

MEASURED

(

)





( )

( )

( )

k

V

CONTROL

= Heat if error > 1

Cool if erro

°

rr < 1

Off otherwise

− °

error

V

CONTROL

= V

V

= f error

DESIRED

MEASURED

(

)

ping the motor. What’s required is a
way to sense the motion of the motor
and compensate by increasing or
reducing the power. Closed-loop con-
trollers can do both.

Closed-loop controllers are found in

all sorts of places: thermostats, cruise
control systems, and elevators just to
name a few. Almost without excep-
tion, commercial robots use closed-
loop motor control. Even the Roomba,
a $199 vacuuming robot, uses a
closed-loop motor controller.

Closed-loop control requires a method

for sensing the motor’s motion. Table 1
lists some popular methods. The method
that will work best for you depends as
much on project constraints as your pref-
erences. The majority of closed-loop
motor controllers use optical-mechanical
encoders for position feedback, but the
extra cabling and mechanical complexity
are usually worth avoiding. I chose back
EMF as a feedback method. The mechan-
ical simplicity (no mechanics) and lack
of cables make it an attractive option.

Back EMF exploits the fact that perma-

nent magnet motors are also generators.
When a motor spins, a voltage is gener-
ated across its terminals. The voltage,
referred to as the back EMF voltage, is
directly proportional to the motor’s veloci-
ty. Thus, when sensing the back EMF volt-

age with an A/D converter, for example,
you can infer the motor’s velocity. When
the voltage is integrated (summed) over
time, the position can be inferred as well.

The main disadvantage of back EMF

sensing is that the inferred position
drifts over time with respect to the
actual position because of noise in the
back EMF voltage. In practice, howev-
er, the error introduced by position
drift is small when compared to the
error introduced by wheel slippage
alone. This performance can be
obtained with a 9-V Lego motor and
robot controller from Charmed Labs,
which uses back EMF sensing.

PID CONTROL

Closed-loop motor control entails both

sensing and controlling the motor’s
motion. I have described different
sensing techniques. The general con-
sensus is that an H-Bridge with pulse-
width-modulation (PWM) is the best
method for controlling the motor. (For
more information, refer to L. Mays’s
article, “Muscle for High-Torque
Robotics,” Circuit Cellar, issue 153,
2003.) Here, a PWM signal switches an
H-Bridge to control the voltage going
into the motor and its speed. Note that
I will refer to this type of controller
throughout the rest article as a PWM

controller. Its
input will be
referred to as the
PWM value.

When combin-

ing sensing and
control in a
closed-loop con-
troller, the word
“loop” can be

Method

Description

Advantages

Disadvantages

Sources

Optical-mechanical A rotating slotted disk is placed

No drift. Digital output integrates

Typically expensive. Requires extra

Hewlett Packard,

encoders

between a light source and detector

easily with digital controllers. Long

cables.

computer mouse

to infer position.

lifetime.

Mechanical

Switches are triggered by the motor’s

No drift.

Typically expensive. Requires extra

Vishay, various

encoders

motion to infer position.

cables. Imposes drag. Output needs

industrial vendors

debouncing. Lower speed. Shorter
lifetime.

Hall effect sensors

When used with a magnet, they can

No drift. Uses existing gear in gear

Typically expensive. Requires extra

Allegro, various

sense metallic (ferrous) gear teeth to

train.

ables, extra magnet, and ferrous gear.

industrial vendors

infer position.

Back EMF

The back EMF voltage of a motor is

No extra mechanical components or

Drift. Requires A/D converter and

Acroname,

measured to infer velocity.

cables. Typically inexpensive.

extra computation to obtain position.

Charmed Labs

Table 1—

There are a few popular feedback methods for sensing motor motion. Back EMF sensing is often overlooked, but its advantages can be attractive to many robotics applications.

Tragectory

generator

Endpoint

Velocity

Acceleration

+

Position

DESIRED

Error

Motor

PID

controller

V

PWM

Position

MEASURED

Figure 1—

A PID controller is typically used to control the velocity and position of a

motor. I’ll focus on implementing a PID position controller, which is shown here with
the trajectory generator.

background image

36

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

The control value at time k is equal to
the sum of the proportional, integral,
and derivative terms (V

PROPORTIONAL

, V

INTE-

GRAL

, and V

DERIVATIVE

) at time k. K

P

, K

I

, and

K

D

are the PID gains, which are easily

determined through experimentation, a
process known as tuning. The PID con-
troller is popular because of its effective-
ness and relative simplicity. All that’s
required is a set of reasonable gain values.

Let’s consider the relevant problem

of controlling a motor’s position (see
Figure 1). V

CONTROL

becomes V

PWM

,

which is the PWM value sent to the
motor’s PWM controller. V

DESIRED

becomes Position

DESIRED

, which is the

desired position of the motor, and V

MEA-

SURED

becomes Position

MEASURED

, which

is the measured position of the motor.

To get a feel for how the PID con-

troller works, consider the proportion-
al term by itself. If the position error
is large, so is the proportional term
and hence the resultant PWM value,
V

PWM

. This causes the motor to move

quickly toward the desired position.
As the motor closes in on the desired
position (as the error decreases), the
proportional term decreases, which
slows the motor. Thus, the propor-
tional term does almost all of the work.
The other integral and derivative terms
correct for problems that the propor-
tional term cannot correct by itself.
You will better understand these
terms when I cover tuning a PID loop.

TRAJECTORY GENERATION

The PID controller is designed to

get to the desired position

(Position

DESIRED

) as fast as possible. If

your robot’s only speed is “as fast as
possible,” it may cause harm to you and
others. It’s often useful to specify the
speed and acceleration when command-
ing the motor controller. This is where
the trajectory generator comes in. It pro-
duces a continuous stream of positions,
or waypoints, for the PID controller to
use to regulate the motor’s motion. The
trajectory generator sits outside the
PID control loop as shown in Figure 1.

For example, a simple trajectory

generator provides constant accelera-
tion until the desired velocity is
reached. It holds this velocity until it
nears the desired endpoint position.
Next, it provides constant decelera-

tion until the endpoint is reached. This
trajectory results in the velocity profile
shown in Figure 2. It’s called a trape-
zoid trajectory because of its shape. For
simplicity, the acceleration and deceler-
ation are equal in magnitude. Figure 2

also shows the corresponding positions
associated with the velocity profile.
These positions are quickly fed into the
PID position controller, usually once
per control cycle. The idea is that the
trajectory generator provides positions
rapidly enough so the motor moves
smoothly along the desired trajectory.

Generating trapezoid trajectories is

relatively straightforward. Refer to the
Circuit Cellar

ftp site for a working

implementation.

WRITING CODE

Let’s write some real code! I’m a big

fan of C++. Its class and class inheri-
tance concepts mean that I don’t have
to write as much code. And writing less
code is right up there with watching
less TV and reducing my cholesterol.

This closed-loop motor controller

lends itself nicely to a class hierarchy.
CAxesOpen is the base class and an
easy starting point. It implements an

End position

Acceleration

Constant velocity

Deceleration

Time

Position

Velocity

Start position

Figure 2—

The trapezoid trajectory gets its name from

the shape of the velocity profile. It is used to move a
motor to a desired end-position in a controlled manner.

Listing 1—

CAxesOpen

and

CAxesClosed

form the first two classes in the motor controller class hier-

archy and a majority of the code. The complete implementation can be found on the Circuit Cellar ftp site.

#define AC_MAX_AXES 4

class CAxesOpen

{

public:

CAxesOpen(int servoAxes); // Constructor

virtual ~CAxesOpen(); // Destructor

virtual int GetPosition(int axis);

void SetPWM(int axis, int pwm);

//...

};

class CAxesClosed : public CAxesOpen

{

public:

CAxesClosed(int servoAxes, int operationalAxes=1);

// Constructor

virtual ~CAxesClosed(); // Destructor

void Periodic();

// Called once per control cycle

bool Done(int axis);

// Returns true if trajectory is finished

void SetPIDGains(int pGain, int iGain, int dGain);

void Stop(int axis); // Stop immediately

void Hold(int axis, bool val); // Hold current position

virtual void Move(int axis, // Perform trajectory move

int endPosition, int velocity, int acceleration);

virtual int GetPosition(int axis);

protected:

// Called by GetPosition()

virtual void ForwardKinematics(const int servoVal[], int

operVal[]);

// Called by Periodic()

virtual void InverseKinematics(const int operVal[], int

servoVal[]);

private:

void TrapezoidTrajectory();

void PIDControl();

(Continued)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

37

open-loop motor controller, which
allows you to set the PWM value and
get the position of each motor axis
within a set of axes. As Listing 1 shows,
CAxesOpen is extremely simple with
its two public functions. Note that
SetPWM() accepts a signed PWM value.
It is intended that the sign of this value
determine the direction of the motor.

CAxesOpen is an easy first step, but

it isn’t very useful by itself. You need
to implement another class that closes
the loop. The closed-loop controller
class is called (not surprisingly)
CAxesClosed, and inherits from
CAxesOpen. As shown in Listing 1,
CAxesClosed is a little more com-
plex. The complete source code is
posted on the Circuit Cellar ftp site.

CAxesClosed is bigger, but it’s doing

almost all of the work in the closed-loop
control system. It implements the PID
control algorithm and the trapezoid tra-
jectory generator, and ties it all together.

Using

CAxesClosed entails periodical-

ly calling

Periodic() for each control

cycle from an external source. Looking at
the contents of

Periodic() in Listing 2,

it makes a call to the trajectory generator
(

TrapezoidTrajectory()) and the PID

controller (

PIDControl()). It also makes

a call to

InverseKinematics(), which

contains the kinematics of your robot
base, if applicable

. CAxesClosed’s imple-

mentation of

InverseKinematics()

doesn’t do anything useful, but a
derived class can override this member
function if it wishes, as you will see.

Call the

Move() function when you

want your motor to move. It takes the
desired trajectory parameters as inputs
and initiates a trajectory, which will
hopefully result in the desired motion.
But, before you can move any motors,
you need to tune the PID control loop.

TUNING

You can use

CAxesClosed to help

tune the PID control loop. Listing 3
provides a simple program that you
can use for tuning purposes. You
instantiate

CAxesClosed with one

axis for tuning. The actual control
loop is the

while loop that calls

Periodic(). The ResetTimer() and
GetTimer() functions reset and read
the timer value, respectively. The
implementations of these functions are

Listing 2—

The code that implements the PID position controller (

PIDControl()

) is surprisingly simple.

It is called from

Periodic()

, which is called once per control cycle.

void CAxesClosed::Periodic()

{

TrapezoidTrajectory();

InverseKinematics(m_generatedTrajectoryPosition,

m_desiredPosition);

PIDControl();

}

void CAxesClosed::PIDControl()

{

int error, pwm;

for (int axis=0; axis<m_servoAxes; axis++)

{

if (m_trajectory || m_hold)

{

error = m_desiredPosition[axis] –

CAxesOpen::GetPosition(axis);

pwm = m_pGain*error +

m_iGain*m_errorIntegral[axis] +

m_dGain*(error – m_errorPrevious[axis]);

m_errorIntegral[axis] += error;

m_errorPrevious[axis] = error;

}

else

pwm = 0;

SetPWM(axis, pwm);

}

}

Listing 3—

A simple program for tuning the PID control loop entails holding the current position. Typically,

Periodic()

is called from a timer-generated interrupt service routine, which effectively makes the con-

trol loop a background process. But to simplify implementation and testing, I used a

while()

loop to call

Periodic()

here.

#define TIMER_PERIOD 5000 // Microseconds

main()

{

CAxesClosed cAxis(1); // One axis

cAxis.SetGains(100, 0, 0);

cAxis.Hold(0, true);

// Hold current position

while(1)

{

ResetTimer();

cAxis.Periodic();

while(GetTimer()<TIMER_PERIOD);

}

}

Listing 1—

Continued.

int m_servoAxes, m_operationalAxes;

// Trajectory input parameters

int m_trajectoryEndPosition[AC_MAX_AXES];

int m_trajectoryVelocity[AC_MAX_AXES];

int m_trajectoryAcceleration[AC_MAX_AXES];

unsigned int m_trajectory;

// True if trajectory is active

// Trajectory generator output

int m_generatedTrajectoryVelocity[AC_MAX_AXES];

int m_generatedTrajectoryPosition[AC_MAX_AXES];

// PID controller variables

int m_pGain, m_iGain, m_dGain;

int m_desiredPosition[AC_MAX_AXES];

int m_errorIntegral[AC_MAX_AXES];

int m_errorPrevious[AC_MAX_AXES];

unsigned int m_hold; // For maintaining the current position

};

background image

38

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

platform-specific and keep the calls to
Periodic() evenly spaced in time.

The control frequency is the number

of control cycles executed per second. In
general, the higher the control frequen-
cy, the better the control. Your proces-
sor’s available bandwidth typically deter-
mines the control frequency, however.
Choose a frequency that spares enough
bandwidth for the other computing tasks
you’ve slated for your processor. Note
that calling

Periodic() from within

a

while loop will consume all of your

processor’s bandwidth (see Listing 4).
Periodic() is intended to be called
from within an interrupt-driven timer
routine to prevent this from happening.
Calling

Periodic() from within a

while loop is much easier to imple-
ment and debug, so you can defer the
added complexity for now.

The call to

Hold() before the while

loop enables the PID loop but not the
trajectory generator. In other words, it
causes the motor to hold its position.
If you try to move the motor, it will
resist. And if you manage to turn the
motor and then let go, the motor zips
back to its original position and
resumes holding its position. At least
that’s what is supposed to happen. It
only happens when the PID loop is rea-
sonably well tuned.

There is plenty of literature avail-

able regarding how to tune a PID con-
trol loop. I tuned mine by hand, which
means I determined a set of PID gains
through experimentation.

Before you begin tuning by hand, it

is useful to attach a wheel to the
motor shaft, preferably the wheel you
will be using on your robot. This
makes it easier to turn the shaft and
witness the control loop’s response.
When I said “by hand,” I meant it lit-
erally! Also, make sure the position
feedback and PWM control have the
same sign. When providing the motor
with a positive PWM value, the position
feedback value should increase as the
motor moves under its own power.
Similarly, when providing negative PWM,
the position feedback should decrease.

As mentioned earlier, the proportion-

al gain does most of the work. Tuning
should begin by adjusting this value.
Start with a small value like, say, 10
(e.g.,

cAxis.SetGains(10, 0, 0)).

After recompiling and running, grab
the wheel, turn it a good half turn,
and then release it. (Do this with the
wheel off the ground!) This is called

perturbing the control system, which
is a simple way of determining the
response of the PID control loop.

After releasing the motor, it should

Listing 4—

CDiffBase

derives from

CAxesClosed

and allows operational space control of a differen-

tial base by substituting its own kinematics routines.

#define DIFF_AXES

2

#define TRANSLATE_AXIS

0

#define ROTATE_AXIS

1

CDiffBase : public CAxesClosed

{

public:

CDiffBase(int rotationScale, int translationScale, int controlFreq);

virtual ~CDiffBase();

virtual void Move(int axis,

int endPosition, int velocity, int acceleration);

virtual int GetPosition(int axis);

private:

virtual void ForwardKinematics(const int servoVal[], int

operVal[]);

virtual void InverseKinematics(const int operVal[], int

servoVal[]);

int m_convNumerator[DIFF_AXES];

int m_convDemonimator[DIFF_AXES];

};

CDiffBase::CDiffBase(int translationScale, int rotationScale, int

controlFreq)

: CAxesClosed(DIFF_AXES, DIFF_AXES)

{

// Initialize scaling constants

m_convDenominator[TRANSLATE_AXIS] = translationScale;

// (ticks/meter)

m_convNumerator[TRANSLATE_AXIS] = 1000; // (millimeter/meter)

m_convDenominator[ROTATE_AXIS] = rotationScale;

// (ticks/revolution)

m_convNumerator[ROTATE_AXIS] = 6283;

// 2 × pi × 1000

// (milliradians/revolution)

m_controlFreq = controlFreq;

SetGains(500, 0, 500);

}

void CDiffBase::ForwardKinematics(const int servoVal[], long

operVal[])

{ // “>> 1” is equivalent to dividing by 2

operVal[0] = (servoVal[0] + servoVal[1])>>1; // Translation

operVal[1] = (servoVal[1] – servoVal[0])>>1; // Rotation;

}

void CDiffBase::InverseKinematics(const int operVal[], int

servoVal[])

{

servoVal[0] = operVal[0] + operVal[1];

// Left wheel

servoVal[1] = operVal[0] – operVal[1];

// Right wheel

}

void CDiffBase::Move(int axis,

int endPosition, int velocity, int acceleration);

{

// Convert endPosition, velocity, and acceleration to “ticks”

endPosition = endPosition*m_convDenominator[axis]

/m_convNumerator[axis];

velocity = velocity*m_convDenominator[axis]*m_control

Freq/m_convNumerator[axis];

acceleration = acceleration*m_convDenominator[axis]*

m_controlFreq*m_controlFreq/m_convNumerator[axis];

// Execute move command

CAxesClosed::Move(axis, endPosition, velocity, acceleration);

}

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
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

41

at least attempt to return to its origi-
nal position. Increasing the propor-
tional gain causes the motor to return
to its original position more quickly
after being perturbed. Increasing the
gain further will eventually result in the
motor overshooting the original position
and then oscillating back and forth.
Continue to increase the proportional
gain until the motor starts to oscillate
in this manner after being perturbed.

Oscillation is more pronounced in

motors with low friction or drag.
Motors with large gear reduction tend
to have more friction and oscillate
less. The Lego motors have little fric-
tion, which makes them efficient but
more challenging to control. To reduce
the oscillation, you need to increase
the derivative gain. The derivative
gain adds velocity damping: the deriv-
ative of the error is equal in magni-
tude but opposite in sign to the motor
velocity. Thus, the derivative term
wants to slow down the motor in
direct proportion to the motor velocity.

What else slows things down in pro-

portion to velocity? Friction.
Increasing the derivative gain is like
adding friction to your motor, which
may sound like something you should
avoid. However, increasing the deriva-
tive gain does not adversely affect the
efficiency of your motor as friction
does. Go ahead and continue to
increase the derivative gain until the
oscillation is under control. If increas-
ing the derivative gain does not
remove the oscillation, the proportion-
al gain may be too high. Try reducing
the proportional gain, setting the deriva-
tive gain to zero, and starting over. We
are shooting for a motor that returns to
its original position as quickly as pos-
sible and then stops (not oscillates)
after being perturbed. It’s acceptable
for the motor to overshoot the original
position slightly before coming to rest.

After the oscillation is under con-

trol, you can choose to be satisfied and
stop here, or you may want to see how
far you can push things. If so, try
increasing the proportional gain again,
which will bring the oscillations back.
Again, you can quell the oscillations
by increasing the derivative gain. You
can proceed in this manner until you
reach a proportional gain that results

in oscillations that cannot be sufficient-
ly reduced by increasing the derivative
gain. At this point, you’ve pushed
things too far. Reduce the proportional
gain and find a suitable derivative gain
that produces the desired response
after perturbing the motor.

Sometimes, friction or another dis-

turbance prevents the motor from
reaching its desired position. That’s
where the integral term comes in. It
ensures that the error will always
reach zero in the steady state. For

example, if the motor comes to rest at
a position that is relatively close to its
desired position, the error is small.
And, if the error is small, the propor-
tional term may not provide enough
PWM to move the motor the extra dis-
tance to reach its desired position. This
is likely to happen if your motor has
static friction, or if your robot’s wheels
have external forces acting on them,
such as those from an incline or hill.

Because the integral term is inte-

grating the error over time, a nonzero

background image

42

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

error causes the integral term to grow
gradually over time. Eventually, the
integral term will become large
enough to overcome the external force
(e.g., friction or an incline). The larger
the integral gain, the faster it over-
comes the external force. But bear in
mind that a sufficiently large integral
gain can introduce oscillations to your
system. Because the Lego motors have
little static friction, I choose to set the

integral gain to zero. However, most
control systems can benefit from a
small amount of integral gain. It
depends on how much steady-state
error your motor typically experiences
and how much you are willing to tol-
erate in your system.

As I mentioned before, a higher con-

trol frequency results in better con-
trol. A higher control frequency allows
you to increase the PID gains (particu-

larly the proportional gain) for a bet-
ter, faster responding system. A con-
trol frequency of a few hundred hertz
is usually sufficient, however. When
changing the control frequency, be
sure to retune PID gains to achieve
the best response.

TESTING A SINGLE AXIS

After tuning your PID control loop,

you can fire up the trajectory genera-
tor and move your motor. This
entails calling

Move() with your

desired trajectory parameters.

Move()

starts the trajectory generator
TrapezoidTrajectory(). If every-
thing is working, the motor smoothly
accelerates to the desired velocity,
holds the desired velocity, and then
decelerates and stops exactly at the
desired position. Nice! You can play
with the trajectory parameters until
the motor moves to your satisfaction.
Note that it is possible to specify
velocity and acceleration values that
are beyond your motor’s capabilities.
The source code for performing the test
is posted on the Circuit Cellar ftp site.

Photo 2—

The differential robot base is popular because of its simplicity. Only two motors are required. It’s usually

more intuitive to specify motion in terms of translation and rotation instead of left and right wheel motion.

Left motor

Right motor

Translation

Left wheel

positive direction

Left wheel

Right wheel

positive direction

Rotation

Right wheel

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

43

You may have noticed that I have

completely ignored units so far,
which makes specifying reasonable
trajectory values difficult. (What does
a velocity of 1,000 actually mean?) I
will remedy this in the next few sec-
tions. The lack of recognizable units
in the lower levels of the control sys-
tem saves a significant amount of
computing bandwidth.

I’ve described how to implement a

complete closed-loop PID position
controller with trajectory generator
for a set of motor axes. This alone
gives you precise control of your
robot’s motors. I could stop here, but
this is where things start getting
interesting! The next sections will
integrate the kinematics of the robot
base into the control system.
Kinematics makes the robot base eas-
ier and more intuitive to control.

DIFFERENTIAL ROBOT BASE

The differential base is the classic

robot base and probably the most pop-
ular. It consists of two motors and
drive wheels, as shown in Photo 2.
Often, the base is circular and the
wheels are mounted colinearly with
the center of the base. This allows the
robot to rotate around the center of the
base, which simplifies path planning.

The differential base has two

motors and two degrees of freedom.
When thinking about its motion, you
usually think of it moving forward,
turning, moving backward, etc. In
other words, you imagine the robot
translating, rotating, or both. In gen-
eral, describing the robot’s motion in
terms of translation and rotation is
more intuitive than describing the
motion of each wheel (e.g., right
wheel clockwise, left wheel counter-
clockwise, etc.)

I call the degrees of freedom (or axes)

with which I prefer to describe motion
(translation and rotation) my operational
space. The motors themselves (left and
right wheels) make up the servo space,
or alternatively the joint space when it
applies to robot manipulators.

[1]

The mathematical expressions I use

when mapping from servo space to
operational space are called the for-
ward kinematics. The forward kine-
matics for the differential base are:

where r is the wheel radius of both
wheels, and b is the distance between
them. Note that the right_wheel,
left_wheel

, and rotation variables are

expressed in radians. The inverse of
these expressions, which map opera-
tional space to servo space, is called
the inverse kinematics:

Note that most robotics professionals
and scholars are accustomed to seeing
the kinematics expressions in matrix
form instead of the expanded form
shown here.

Now you’re ready to implement a

differential base controller class called
CDiffBase (see Listing 4). Most
importantly, note that

CDiffBase is

derived from

CAxesClosed and over-

rides

InverseKinematics() and

ForwardKinematics() with its own
versions. These versions contain the
simplified differential base kinemat-
ics, which allow

CAxesClosed to

convert operational space axis posi-
tions into servo space axis positions
and vice versa. As a result,
CDiffBase now accepts motion com-
mands (e.g.,

Move()) in terms of

translation (axis index 0) and rotation
(axis index 1), which make up its
operational space.

Let’s examine what is going on.

Assume a working implementation of
your base class

CAxesOpen such that

the left wheel is axis index 0 and the
right wheel is axis index 1. Next in
the hierarchy,

CAxesClosed calls

InverseKinematics() from within
Periodic() (see Listing 2).
InverseKinematics() takes opera-
tional space positions from the trajec-
tory generator as inputs and outputs
the corresponding servo space posi-
tions. The PID controller uses these
positions to control the position of
each motor. Note that almost all of the

left_wheel =

rotation

right_wheel

2

r

translation

b







=

r







×

tation

2

b

×

ro

+

translation

(

)

translation

r right_wheel

rotation

r

b

ig

=

+ left_wheel

=

2

h

ht wheel

_

left_wheel

(

)

r

work is done within

CAxesClosed.

CDiffBase is simple by comparison.

WHERE ARE THE UNITS?

When commanding your robot base,

specifying position, velocity, and
acceleration with recognizable units is
important. But what units should you
choose? In the interest of saving com-
putation, it’s a good idea to express
these units as integers instead of float-
ing point values. Thus, the units need
to provide reasonable resolution when
expressed as integers. Considering this,
I’ve chosen millimeters for translation
units and milliradians for rotation units.

To perform unit conversion,

CDiffBase overrides Move() and per-
forms conversion before passing the
arguments down to

CAxesClosed (see

Listing 4). Performing unit conversion
in this manner is efficient because it
occurs once per

Move() command

instead of once per control cycle.

Unit conversion for the differential

base relies on two scaling constants
(

translationScale and

rotationScale), which are passed
into the

CDiffBase constructor (see

Listing 4). These scaling constants are
specified in units that can be easily
determined through calibration. For
example,

translationScale is spec-

ified in ticks per meter. Here, “ticks”
are the units that are passed into
CAxesClosed::Move() after unit
conversion. What are ticks exactly?
For the translation axis, they are units
of distance; for the rotation axis, they
are units of angular displacement.
Calibrating your robot base will reveal
the sizes of these units.

CALIBRATION

Calibration accurately determines

the values of

translationScale and

rotationScale. Determining these
constants through calibration is usual-
ly the method that yields the most
accurate robot base.

There are lots of ways to calibrate

your base, but the freewheeling
method is probably the easiest. Run a
program that continuously prints the
positions of the operational space axes
(translation and rotation) by calling
CAxesClosed::GetPosition().
While running this program, record

background image

44

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

the translation value that is being
printed. Roll the robot in a straight
line for 1 m, and record the transla-
tion value again. Subtracting the two
values will yield the number of ticks
per meter of translation, which is
translationScale. Use the same
method to determine
rotationScale, except rotate the
robot one revolution (360

°

) to deter-

mine the number of rotation ticks per
revolution, which is

rotationScale.

You may download an implementa-
tion of the calibration program from
the Circuit Cellar ftp site.

You may be wondering why

ForwardKinematics() and
InverseKinematics() in Listing 4
ignore r and b. Note that r and b only
serve as scaling constants for transla-
tion and rotation, you can move them
out of your kinematics calculations
and into the scaling constants
(

translationScale and

rotationScale). Because you deter-
mine your scaling constants through
calibration, the values of r and b do
not need to be explicitly known. That
makes life easier!

AFFORDABLE HUMR

In the previous section, I covered

implementing an operational space
differential robot controller. Although
a differential base is simple, it only
has two degrees-of-freedom. This limi-
tation, for example, makes it impossi-
ble to translate in a particular direc-
tion unless the wheels are oriented in
that direction. In other words, a differen-
tial robot needs to turn or rotate before
it can head in a particular direction.

A robot that is confined to a plane

(e.g., the floor) has three degrees of
freedom at most. These are commonly
represented as two translation degrees
of freedom (x and y) and rotation, as
shown in Figure 3. In the field of
mobile robotics, a robot with three
degrees of freedom in a plane is consid-
ered holonomic. The differential base,
for example, is lacking a degree of free-
dom and is considered nonholonomic.

Why is a holonomic robot useful?

Holonomic robots can accelerate in
any direction at any time, which
makes them highly maneuverable and
surprisingly easy to control. Consider

a simple example of moving to a spe-
cific goal location. A differential robot
must first turn toward the goal before
it moves toward it. A holonomic robot
simply heads straight toward the goal
(no turning required), which is simpler
and typically faster.

There are many different holonomic

robot designs, but probably the sim-
plest consists of independently driven
omnidirectional wheels (see Photo 1).
Omnidirectional wheels, or “omni-
wheels,” have passive rollers evenly
distributed along the outside periphery
of the wheel. The rollers provide the
omniwheel with an extra degree of
freedom that permits the wheel to
move orthogonally (sideways) with
respect to the regular wheel motion.
I’ll refer to this extra degree of freedom
as the minor axis of the omniwheel.
The major axis is the degree of free-
dom regularly associated with wheels.
When a motor is attached to an omni-
wheel, the minor axis remains passive
and the major axis becomes powered.

It is often the case that a robot will

have as many motors as degrees of free-
dom. When the number of motor axes
exceeds the number of degrees of free-
dom, the system is underconstrained.
The Holonomic Underconstrained
Mobile Robot (HUMR) has four omni-
wheels, which is one more than is neces-
sary for holonomic motion (see Photo 1).
The four-wheeled HUMR has the
advantage of increased power and accu-
racy as well as simplified kinematics
and Lego construction.

As with the differential robot base,

the servo space of the HUMR provides
an unintuitive operational space. But,

more importantly, because the base is
underconstrained, it’s possible for the
wheels to fight each other in a sort of
tug-of-war. The operational space con-
troller prevents this while providing
intuitive control.

HUMR CLASS AND KINEMATICS

Figure 3 shows the four wheels and

motors of the HUMR base, which are
numbered zero through three. The
arrows indicate the positive motion
direction of each motor. The inverse
kinematics, which is fairly easy to
derive using vector math, provide the
motion constraints required for our

underconstrained system. Deriving the
forward kinematics may seem tricky
because there are four wheels
(knowns) and three operational axes
(unknowns), but the HUMR’s simple
right-angle geometry makes it possible
to derive these expressions by inspec-
tion. Forward kinematics are as fol-
lows:

Inverse kinematics are as follows:

where r is the wheel radius, and b is
the distance from any wheel to the
center of the robot.

The implementation of HUMR class

CHumrBase is similar to CDiffBase.
CHumrBase, like its sibling, only
requires two scaling constants: one for
the translation axes
(

translationScale) and one for the

rotation axis (

rotationScale). As

before, you can move the r and b
terms out of the kinematics expres-

wheel

r

wheel

r

0 =

+ b rotation

1 =

x

b

rotatio

×

(

)

×

n

n

2 =

b

rotation

3 =

x + b rot

(

)

×

(

)

×

wheel

r

wheel

r

a

ation

(

)

y

y

x

r wheel

y

r

wheel

rotatio

=

1 wheel 3

=

0 + wheel 2

2

2

(

)

(

)

n

n

r wheel

wheel

wheel

=

0 +

1 +

2 + wheel 3

(

)

4b

Wheel 0

Wheel 1

Wheel 2

Wheel 3

b

Rotation

y

x

Figure 3—

Only three omniwheels are required for

holonomic motion, but four omniwheels (shown here)
provide more power and accuracy. When equipped with
9-V Lego motors and 4-cm (diameter) omniwheels, the
HUMR has a top speed of 50 cm/s and a top accelera-
tion of 200 cm/s

2

.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

45

Listing 5—

The

InverseKinematics()

routine implements Frisbee mode by rotating the x- and y-

axes. By embedding different mathematical expressions in

InverseKinematics()

, all sorts of differ-

ent and interesting modes are possible.

void CHumrBase::ForwardKinematics(const int servoVal[], int

operVal[])

{

operVal[X_AXIS] = ( servoVal[1] - servoVal[3])>>1;

operVal[Y_AXIS] = (-servoVal[0] + servoVal[2])>>1;

operVal[ROTATE_AXIS] =

(-servoVal[0] - servoVal[1] - servoVal[2] - servoVal[3])>>2;

}

void CHumrBase::InverseKinematics(const int operVal[], int

servoVal[])

{

int cosRotation, sinRotation, rotation;

int diffRotOperVal[2], diffOperVal[2];

if (m_frisbee)

{

rotation = GetPosition(ROTATE_AXIS); // Get rotation angle

cosRotation = CosLut(rotation);

sinRotation = SinLut(rotation);

// Calculate velocity (compute difference)

diffOperVal[X_AXIS] = operVal[X_AXIS] -

m_prevOperVal[X_AXIS];

diffOperVal[Y_AXIS] = operVal[Y_AXIS] -

m_prevOperVal[Y_AXIS];

// Rotate x and y axes and scale down by shifting right by 10

diffRotOperVal[X_AXIS] = (diffOperVal[X_AXIS]*cosRotation +

diffOperVal[Y_AXIS]*sinRotation)>>10;

diffRotOperVal[Y_AXIS] = (-diffOperVal[X_AXIS]*sinRotation +

diffOperVal[Y_AXIS]*cosRotation)>>10;

// Add to new position

m_newOperVal[X_AXIS] += diffRotOperVal[X_AXIS];

m_newOperVal[Y_AXIS] += diffRotOperVal[Y_AXIS];

// Save for next iterration

m_prevOperVal[X_AXIS] = operVal[X_AXIS];

m_prevOperVal[Y_AXIS] = operVal[Y_AXIS];

}

else

{

m_newOperVal[X_AXIS] = operVal[0];

m_newOperVal[X_AXIS] = operVal[1];

}

servoVal[0] = -m_newOperVal[Y_AXIS] - operVal[ROTATE_AXIS];

// Wheel 0

servoVal[1] = m_newOperVal[X_AXIS] - operVal[ROTATE_AXIS];

// Wheel 1

servoVal[2] = m_newOperVal[Y_AXIS] - operVal[ROTATE_AXIS];

// Wheel 2

servoVal[3] = -m_newOperVal[X_AXIS] - operVal[ROTATE_AXIS];

// Wheel 3

}

sions and into the scaling constants to
minimize the computation (see Listing 5).
Furthermore, I recommend that the
scaling constants be determined through
the freewheeling calibration process.

EXPENSIVE FRISBEE

One of the more impressive results

of holonomic motion is the ability to
rotate while translating in a straight
line. I call this Frisbee motion because
it resembles the motion of, well, a
Frisbee. However, if your robot simply

translates along its x-axis while rotat-
ing, for example, it will go in a circle,
not in a straight line. This is because
the x- and y-axes are always pointing
in the same direction with respect to
the robot. When the robot rotates, so
do the axes. In order to move in a
straight line, you need to rotate the
translation axes in the opposite direc-
tion with respect to the robot’s rota-
tion. Rotating the x- and y-axes
entails a simple application of sine
and cosine with respect to the robot’s

background image

46

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

rotation angle:

Implementing this functionality can

be easily accomplished by embedding
these expressions in the
InverseKinematics() function (see
Listing 5). Note that
ForwardKinematics doesn't need to
be changed for now because it doesn't
affect the HUMR’s motion. I’ve intro-
duced a new variable called

m_fris-

bee into InverseKinematics,
which, when set, rotates the x- and y-
axes with respect to the rotation angle
and enables Frisbee motion. It
assumes that you have a reasonably
efficient means of obtaining the sine
and cosine of the rotation angle,
which is specified in milliradians. The
CosLut() and SinLut() functions
employ a look-up table of sine and
cosine values scaled (multiplied) by
1,024 to make integer multiplies accu-
rate. Scaling the results back down
(dividing by 1024) is accomplished by
right-shifting the results by 10 bits.
The implementations of

SinLut(),

CosLut(), the rest of CHumrBase, and
the video clips of Frisbee motion are
posted on the Circuit Cellar ftp site.

Your implementation of Frisbee

mode allows you to change the rota-
tion angle however you wish without
affecting the direction of motion. Aside
from being cool to look at, Frisbee
mode can be useful when a sensor on
top of the robot needs to pan back and
forth, for example. I’m sure you can
think of other modes that are useful for
whatever you want your robot to accom-
plish. Or, you may want to experiment
with a different operational space.
Implementing these ideas only requires
modifying the kinematics routines.

IMPROVED PERFORMANCE

I’ve covered quite a bit a ground in

this article: PID control, tuning, trajecto-
ry generation, and operational space con-
trol for two different robot bases. I have
implemented a class hierarchy that
makes constructing closed-loop opera-
tional space controllers straightforward
and applicable to practically any robot
base. And I have accomplished this
with software that consumes only a

(

)

×

(

)

×

′ −

x

rotation

rotation

rotatio

=

x +

y

y =

cos

sin

sin

n

n

rotation

(

)

×

(

)

×

x + cos

y

modest amount of computing power.
For your next robot or motion-control
project, keep these ideas and methods
in mind. Your robot will thank you
with greatly improved performance!

I

SOURCES

Omnidirectional wheels
Acroname, Inc.
(720) 564-0373
www.acroname.com

Xport 2.0 and Xport Robot Controller
Charmed Labs
(201) 444-7327
www.charmedlabs.com

Mindstorms Robotics Invention
System
Lego Co.
+45 79506070
www.lego.com

Gameboy Advance and Gameboy
Advance SP
Nintendo of America, Inc.
(800) 255-3700
www.nintendo.com

RESOURCE

Vector math, www-2.cs.cmu.edu/
~pprk/physics.html.

Rich LeGrand has 10 years of experi-
ence in robotics and multimedia sys-
tems. When he’s not tuning PID loops
by hand, he works at Charmed Labs,
which provides advanced embedded
technologies for consumer and educa-
tional use. He holds a B.S.E.E. and
B.A.C.S. from Rice University and an
M.S.E.E. from North Carolina State
University. Rich has authored domes-
tic and international patents for holo-
nomic robot control. You can reach
him at rich@charmedlabs.com.

PROJECT FILES

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

REFERENCE

[1] O. Khatib, “A Unified Approach to

Motion and Force Control of Robot
Manipulators: The Operational
Space Formulation,” IEEE Journal
Robotics and Automation

, RA3,

1987.

background image
background image

48

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

O

ur concept of robots has changed

more than once over the years since
Karel Capek coined the term for his
1921 play RUR (Rossum’s Universal
Robots

). Originating from the Czech

term robota, which means servitude,
or forced labor, today’s definition is a
little less menacing. A robot is a com-
puterized machine designed to
respond to input received manually or
from its surroundings. Put more sim-
ply, a robot is a device that responds
to sensory input.

Today’s warnings about the poten-

tial dangers of genetic research remind
me of the discussions we used to have
about the pros and cons of developing
robots. Could we end up enslaved by
the devices that we create to help us?
Isaac Asimov helped us cope with our
fears by defining the “three laws of
robotics”: “a robot may not injure a
human being or, through inaction,
allow a human being to come to harm;”
“a robot must obey orders given it by
human beings except where such orders
would conflict with the first law;” and
“a robot must protect its own existence
as long as such protection does not con-
flict with the first or second law.”

[1]

Some of you might envision a robot

as a galaxy peacekeeper, but for most
of us it’s just a humanoid helper.
Although some companies have proto-
type humanoid robots that can walk
up and down stairs, you are far from
having this type of companion helping
you at home. However, there are plen-
ty of robots already living there. Every
consumer product with a microcom-
puter, from cell phones to laundry

great strides in smartening up robotic
systems.

EMERGING ROBOT TECHNOLOGY

Last March I attended the Emerging

Robotics Technologies and
Applications Conference Robotic
Trends Conference in Cambridge,
Massachusetts. The event featured
new business and product opportuni-
ties in personal, service, and mobile
robotics. (You may have seen the ad in
the February 2004 issue.) For those of
you fortunate enough to have attend-
ed, I know you came away with a
strong sense of direction. It’s always a
pleasure to meet and talk with Circuit
Cellar

readers who are taking an

active role in the future of industry
(and not just the robotics industry).

Although some subjects were appli-

cable to everyone in attendance, the
session times sometimes overlapped,
separating the more than 300 atten-
dees by their specific interests. The
conference featured speakers on topics
ranging from adaptive, intelligent robot-
ics systems to commercial applications
for vision-guided autonomous flying
robots. Refer to the Circuit Cellar ftp
site for a more in-depth look at the
topics featured at the conference.

WIDEST VISION

My award for the broadest-reaching

session goes to Carnegie Mellon’s
Dr. Chuck Thorpe for his “What’s
Next in Mobile Robotics and
Automation?” presentation. With a
budget of $48 million and more than
250 individuals in 12 centers, his

Is There a Robot in Your Future?

FROM THE BENCH by Jeff

Bachiochi

irons, is a robot. Your car’s cruise con-
trol, a robot. Your microwave, a robot.
The motion sensor floodlight above
your driveway, a robot!

Up until now, robotics mainly has

been aimed at manufacturing. Picture
the lines of heavy robot arms assem-
bling, painting, welding, and perform-
ing similar monotonous tasks perfectly
over and over 24/7. Preprogramming
allows these behemoths to repeat
processes without any real knowledge
of whether or not the task is ever
accomplished. But times are changing.
Sophisticated vision systems and
other sensory inputs are making

A lover of all things robotic, Jeff was beaming when he returned from the recent Emerging
Robotics Technologies and Applications Conference in Cambridge, Massachusetts. This
month he discusses some of the most exciting innovations in the robotics industry.

Photo 1—

Stripping paint from the hulls of large vessels

in dry dock traditionally has taken numerous men end-
less days. Now this process can be completed quickly
and (environmentally) safely with a magnetic robot that’s
under development at Carnegie Mellon. The robot
attaches to the ship’s metal hull and follows its contours.

Emerging Robot Technologies

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

49

MICROSOFT

The presence of Microsoft at the

conference tells you something about
the event’s importance. But I’m afraid
I must give Microsoft my fluff award.
Pointing out the popularity of
Windows CE, .NET, and XP Embedded
for robotic applications leaves microc-
oders looking at their watches.

Speaking of watches, Microsoft’s

Smart Personal Objects Technology
(SPOT) platform may spark some cre-
ativity. A clever demonstration showed
how easily application programmers
could use .NET-managed code to speed
up development at the top level. All of
this is based on having hardware devel-
oped to the point of plug-and-play.

Microsoft wasn’t the only company

punching up that philosophy. Others
seem to be scrambling for packaged
platforms with APIs for all functions.
That’s where standards become impor-
tant to those wishing to take advantage
of the interconnectivity between basic
functions and upper-level applications.

GUTSY

The award for most gutsy goes to

VIA Technologies, which was the only
chipset company in attendance. The
Taiwan-based company has centered
itself on low power, advanced connec-
tivity, multimedia, and networking
silicon. It featured the Mini-ITX,
which is a 17 cm × 17 cm, small form
factor, all-in-one SBC (see Photo 2).
Enhanced multimedia performance is
delivered through the VIA Apollo
CLE266 chipset, featuring integrated
VIA UniChrome 2-D/3-D graphics, an
MPEG-2 accelerator with motion
compensation, and support for the

greater memory bandwidth of DDR266
SDRAM and the high transfer speeds
of ATA-133. An array of modern stor-
age and connectivity options are sup-
ported, including on-board CardBus,
CompactFlash, and a PCI slot. There
is support for IEEE 1394, USB 2.0,
S-Video and RCA TV-Out (NTSC and
PAL), and 10/100-mbps Fast Ethernet.
The VIA EPIA MII is fully compatible
with Windows and Linux operating
systems. Current demand is less than
10 W.

The company also introduced the

Nano-ITX, which is a new 12-cm
square SBC. It was good to see a chipset
manufacturer putting itself on the line
in support of the robotics community.

PLAYS WELL WITH OTHERS

The Centibots project featured at

the conference was produced by SRI
International in conjunction with
Stanford University. The project
explored the use of a computational
framework for coordinating large
numbers of robots and extending their
range of usefulness. The project’s goal
was to map a warehouse, find a treas-
ure, and guard it from burglars (a
“search and rescue mission” in mili-
tary speak). All of the equipment was
brought to an undisclosed location,
and the robots (ActiveMedia Robotics
platforms) were allowed to enter the
facility at a single point. No informa-
tion about the facility was given to the
teams, and only the robots could enter.

group at Carnegie Mellon is research-
ing several areas of robotics, including
factory automation, medical robotics,
robotic navigation, and artificial intel-
ligence. You might have seen some of
their projects on Tech TV. Their
mobile stripper improves the nasty
task of refinishing boat hulls while
preventing hazardous material from
contaminating the environment (see
Photo 1). With all the research hap-
pening at Carnegie Mellon, it’s no
wonder the school participated in the
Defense Advanced Research Projects
Agency (DARPA) Grand Challenge.

MOST ENTREPRENEURIAL

The “Technical, Social, and

Commercial Trends in the Era of Mass
Market Robotics Appliances” presen-
tation provided an honest look at the
failures and successes of robotic appli-
ances. The most important point
relayed in the presentation is that a
product must be able to earn income,
not just save money.

iRobot Corp., which takes the

award for most entrepreneurial, has
learned a few lessons and turned its fail-
ures into profitable learning experiences.
Its corporate mission statement has four
parts: “build cool stuff,” “make money,”
“have fun,” and “change the world.” By
the looks of things, it has been extreme-
ly successful in the commercial (with its
robotic vacuum, Roomba), governmen-
tal (with its portable robot, PackBot),
and industrial markets.

OLIVE DRAB AWARD

It’s obvious that the U.S. govern-

ment holds robotics in high esteem.
The use of robots is presently saving
lives in Iraq and Afghanistan. The mil-
itary understands the importance of
substituting replaceable technology for
humans, and it continues to adjust its
battle plans for the future of warfare.

Although each of the various branch-

es of the military has its own research
and development element, the private
sector, which seems to have more
expertise, is an important part of the
military’s plan of action. What better
place for the government to solicit ideas
than a room filled with eager robotics
experts? Government contracting was
a focal point at the conference.

Photo 3—

Although Evolution Robotics’s ER1 platform

requires a laptop, you can get started for about $300.
Have ER1 deliver your e-mail personally.

Photo 2—

VIA Technologies, which is a chipset

maker, also offers several full-blown multimedia x86
architecture SBCs.

background image

50

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

The robots employed simultaneous

location and mapping (SLAM) technol-
ogy and used sensor data and odome-
try to map stationary objects. Wireless
networking allowed the robots to go
beyond the normal communication
range as long as they remained in con-
tact with fellow robots. All of the
information was fed back to a central
computer, which coordinated the
robots’ activities. The finished area
map provided a means for a systemat-
ic search for a previously recognized
treasure. The robots in the swarm
then positioned themselves at key
vantage points to provide security
against invasion.

ENTERTAINMENT

Even engineers need time to

unwind. After a day of confinement,
many of us were looking for a chance
to wind down. Our hosts provided an
evening of networking at the rotating
pub atop the Hyatt. Although the
view of the Boston skyline was
breathtaking, the entertainment was,
eh, shall I say, an exhibition—an
exhibition of speech processing,
image recognition, and the wireless
capabilities of Sony’s new ERS –7
robots. Basically, we listened to
Mozart performed by a group of wire-
less-enabled AIBOs.

I tip my hat to the RoboTech

Center for the entertainment. The
Nashua, New Hampshire-based
RoboTech Center fosters community
awareness and support for robotics-
related technology. It specializes in
the application of emerging technolo-

gies for educational purposes.

ROBOTS ON PARADE

What would a robotics conference

be without a few robots? I know that
iRobot has quite an extensive line of
robots, so I was a bit surprised to see
so few of its products on display. One
of the largest displays concentrated
only on the Roomba and PackBot.

Evolution Robotics demonstrated its

vision-recognition system. Recognition
levels were high, even with object dis-
tortion from being nonperpendicular.
The ER1 robotic platform is a minimal
square frame unit that’s used with a
laptop (see Photo 3). You can configure
it quickly to handle a number of tasks.

GeckoSystems’s mobile service robot

(MSR) is designed to autonomously

navigate your home, office, or place of
business (see Photo 4). The MSR is a
PC-based platform currently used as a
CareBot, SecurityBot, and SuperVacBot.

White Box Robotics also uses a PC-

based platform for its line of multi-
media robots. The 912 robot reminds
me of a small PC on wheels (see
Photo 5). It wins the cute award. I
doubt you’d be scared if you met this
one in a dark alley.

DARPA

DARPA, which is the central

research and development organization
for the U.S. Department of Defense,
was mentioned in several sessions at
the conference. Although recently
overshadowed in the news by NASA’s
Mars rovers, Spirit and Opportunity,
DARPA got press for its $1 million

Photo 5—

Talk about rock and roll. You can have your

favorite tunes follow you around the house with this
traveling multimedia robot.

Photo 6a—

If the contest turned out to be a 50-yard dash, this could be a winner. Talk about complicating a task. Where is a Segway when you need it?

b—

Wheels are neither

mandatory nor necessary for the Grand Challenge. Vehicle designs can be of any configuration as long as they keep both feet, er, treads, on the ground.

c—

We’re talking big!

If you’ve got to cross unknown terrain, you might as well be able to crush anything in your way. Don’t worry, the rules of the Grand Challenge prevent this from becoming a
Robot Wars or allowing nature to be trampled.

a)

b)

c)

Photo 4—

CareBot moved around within the crowd at the

conference. A multitude of sensors keeps CareBot from
becoming too friendly and invading your personal space.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

51

Grand Challenge, which is a field test
for autonomous ground vehicles. Its
purpose is to encourage the accelerated
development of autonomous vehicle
technologies that could be applied to
military requirements.

The cash up for grabs in the most

recent challenge was for the first
group whose autonomous land vehi-
cle navigated a course mapped
between Los Angeles and Las Vegas.
(The actual course was a secret until
just before the race.) The 300-mile
course (on and off road) had to be com-
pleted without human intervention
(strictly hands off). As all of the groups
found out, it wasn’t an easy task. Even
NASA’s rovers have the advantage of a
human driver, albeit with serious reac-
tion lag. DARPA insisted that safety
was a priority. A manned control
vehicle equipped with an emergency
stop system attached followed each
vehicle competing on the course.

You’d think the basic vehicles

would have the same design, but there
was a vast array. They varied in size
and mode of locomotion (see Photo 6).

To qualify for the race, the robots

were required to navigate a short
course to demonstrate their intelligent
autonomous behavior and safety fea-
tures. This proved too much for many
entries. Of the more than 100 original
applicants, only 15 were allowed to
compete in the Grand Challenge.

Just hours prior to the race, partici-

pants were given the 142-mile course
consisting of 2,000 GPS waypoints. A
stagger start avoided competitive
jockeying for position. No vehicle fin-
ished the race. The farthest a vehicle
traveled before becoming disabled
was a mere 5% of the total distance.
Sadly, none of the teams won the $1
million. However, the same question
was on everyone’s mind, “When can
we try again?”

DARPA is busy making plans for the

next challenge. The prize is now $2 mil-
lion. Visit DARPA’s web site for informa-
tion (www.darpa.mil/grandchallenge/).

DIFFERENT PICTURE?

Does any of this change your defi-

nition of robotics? Even though it has
been a few generations since we were
first introduced to the concept, there is

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.

PROJECT FILES

For conference topic information, go
to ftp.circuitcellar.com/pub/Circuit_
Cellar/2004/169.

RESOURCES

Robotic Trends,
www.robotictrends.com.

The Defense Advanced Research
Projects Agency (DARPA),
www.darpa.mil.

SOURCES

ER1 Personal robot system
Evolution Robotics, Inc.
www.evolution.com

CareBot, SecurityBot, and
SuperVacBot
GeckoSystems, Inc.
www.geckosystems.com

Roomba and PackBot
iRobot Corp.
www.irobot.com

Apollo CLE266 chipset, Nano-ITX
VIA Technologies, Inc.
www.via.com.tw

912 Robot
White Box Robotics
www.whiteboxrobotics.com

still a long and winding road to travel.
Communication and coordination
seem to be the newest issues because
more hardware platforms are being
released. Although observation and
delivery tasks have been conquered,
grasping and manipulating items still
remains a fantasy. Many engineers are
now taking part in this exciting field.
Will you be one of those to take pres-
ent technology to the next level?

I

REFERENCE

[1] I. Asimov, I, Robot, Doubleday,

1950.

Advertising

Calendar

Contact: Sean

(860) 872-3064 Fax: (860) 871-0411

Advertising

Calendar

October Issue #171

Data Acquisition

Bonus Distribution:

CTIA Wireless I.T. & Entertainment,

PCB Design Conf. East,

RoboNexus

Space Close: Aug.10

background image

An e-field sensor is basically an

oscillator at approximately 120 kHz.
The signal is sent to the sensor elec-
trode through an internal resistor. The
signal at the sensor electrode is also
connected to a detector that converts
it to a DC value. The signal level at
the sensor electrode is determined by
the voltage drop across the internal
resistor caused by the capacitance (ref-
erenced to the ground) of the sensor
electrode. The DC level is amplified
internally and output to a level pin.
Thus, the sensor determines the
effective capacitive loading of the
sensor electrode.

Nine sensor electrodes can be con-

nected to the sensor IC. Only one
electrode is selected at a time by the
multiplexer, which is controlled by

the multiplexer input lines.
The level output pin is com-
mon to all of the electrodes.
There is also a shield driver
for driving electrodes through
a longer cable.

A closer examination of

the datasheet reveals that the
IC is optimized for automo-
tive applications. The IC
operates from a 12-V power
supply, and it supplies a regu-
lated 5 V for an MCU inter-
face and 8.5 V for analog cir-
cuits. The IC also provides an
interface for connecting an
MCU to the ISO-9141 (the
local interconnect network,
or LIN) found in automobiles.

SYSTEM SIMPLICITY

The first operation is to

52

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

H

aving a suitcase lost or stolen is a

common occurrence when traveling.
Most often, it’s the result of careless-
ness and someone taking advantage of
that carelessness to steal from you.
There is a certain art in the way
thieves lift suitcases, although they
sometimes use brute force or intimi-
dation. It recently happened to one of
our relatives at a tea shop in the
crowded Madras railway station,
which is located in southern India.
When he put down his briefcase to pay
for a cup of tea, it was stolen from
right beside his leg. It took the thief
only a few seconds.

Our e-field sensor-based monitoring

system is intended to prevent situa-
tions like this from happening. Even
in the worst sort of case, like getting
robbed at gunpoint, our
device will help attract
attention.

SENSOR SOLUTION

Years ago, we read about

how jewelers use suitcases
that have alarms and the
ability to shock potential
thieves with a high-voltage
jolt. More recently, we saw a
TV clip about a Chicago
mob-era suitcase that would
smoke and explode firecrack-
ers when someone grabbed it
from its owner. We liked the
idea, but thought that imple-
menting the required key-
board and sensors would be
too difficult. (It’s probably
why these devices are not
too common.) That’s why we

E-Field Sensor-Based Monitoring System

Whether you’re looking to build a simple suitcase alarm or a high-tech surveillance system
for your home, you’ll want to study Seenath and Sameer’s design before you begin. From a
description of the MC33794 e-field sensor to useful programming tips, this article will help
you get started on your own monitoring system.

built the Antitheft Suitcase when
Motorola announced its 2003 E-Field
Sensor Contest. We also built two
other devices: a water level indicator,
with each electrode determining the
water level in a plastic container, and
a door alarm that features sensors
under the doormat that produce a tone
as someone approaches. However,
when the time came to submit a
design, we only entered the Antitheft
Suitcase, thinking that the other two
designs were straightforward applica-
tions.

The e-field sensor takes away all the

difficulty in building an alarm. You
have multiple sensor availability and
can implement a keyboard. In fact, a
few of the sensor electrodes can act as
a keyboard.

FEATURE ARTICLE

by Seenath Punnakkal & Sameer Cholayil

Suitcase

Dummy key

E3 Key

Proximity electrode

Lift electrode

E5 E4

E1

E2

E3

MC33794

A

B

C

D LEVEL

E1

Key

E2

Key

MC68HC908QY4

PTB4

PTB5

PTB6

PTB7

AD3

V

CC

PTB1

Power
supply

V

CC

Figure 1—

The Motorola e-field development board contains the MC33794 e-field

sensor and MC86HC908QY4 microcontroller. All we had to do was wire the sen-
sors, a power supply, and a buzzer.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

53

CONSTRUCTION PHASES

We didn’t want to rip up a perfectly

good suitcase, so we built the alarm
in a small handbag. As a result, we
couldn’t hide the wiring and the
electrodes.

The e-field demonstration board had

all the hardware we needed for the
project. It’s also convenient to develop
firmware and perform testing with the
demonstration board. Motorola pro-
vides firmware and PC software that
allowed us to monitor the sensor lev-
els from the nine electrode pins. This
is also convenient during the develop-
ment and wiring.

A simple in-system firmware

upgrade through the serial port
allowed us to load the suitcase alarm
application. The KIT33794DWBEVM
demonstration board was modified to
suit our application. Figure 2 shows
the modified schematic diagram. For
more information, refer to the litera-
ture listed in the Resources section at
the end of this article.

You can stick aluminum or copper

tape to almost any surface and use it

turn the alarm on and off. A hidden
switch inside the suitcase accom-
plishes this. You’re the only person
with access to the switch. You have
the key.

The alarm is not activated at power-

up. When you’re ready put the suit-
case down, you activate the alarm by
entering the arming code. You can
enter the disarm code at any time
(even after the alarm has gone off).

After the alarm is activated, it will

only go off in the following three situ-
ations (prompted by either the owner
or a would-be thief): if the suitcase is
lifted, which is detected by contact
with the lift electrode; if the suitcase
moves away from your body, which is
detected by the removal of a touch
from the proximity electrodes; or if an
incorrect code (or unintentional
touch) is entered on the keypad elec-
trodes.

SYSTEM BASICS

The system is comprised of four

major components (see Figure 1). As
you can see, this design features the

MC33794 e-field sensor IC. A, B, C,
and D are the multiplexer input for
selecting one of the nine electrode
pins. LEVEL is the DC sensor output
pin. E1 through E5 are the sensor elec-
trode pins connected to the suitcase.

The suitcase’s keypad is comprised

of keys E1 through E3. A 3-2-1 code
means keys E3, E2, and E1 (connected
to electrode pins E3, E2, and E1,
respectively) are touched in that order.
A dummy keypad is provided on the
suitcase for evenly distributing two
keypads (electrodes) on two sides. The
lift electrode is connected to electrode
pin E4. The proximity electrode is
connected to pin E5.

The MC68HC908QY4 runs the sys-

tem. It gets its power from the sensor
IC. Pins PTB4 through PTB7 are used
as outputs for the sensor multiplexer
control. Pin AD3 is the analog input
to the 8-bit A/D converter. This is
used to read the sensor output level
from the e-field sensor. Pin PTB1 is
used to drive a simple buzzer. We
can’t send 40 kV to the case or
explode firecrackers (not yet at least).

Figure 2—

The MC33794 and MC86HC908QY4 are the main components, but we didn’t forget the 5-V regulator for the digital parts. The MC33794 provides the regulated sup-

ply. The RS-232 level converter and connector allow you to program and debug the circuit.

background image

nected. It just provides a reference per
the current environmental conditions.

We did not use the RefA and RefB

electrodes. They are intended for elec-
trode (E1–E9) capacitance measure-
ment by comparing them with capaci-
tors connected to the RefA and RefB
pins. Unlike pins E1 through E9, they
are not grounded if they are not in the
selected state. It should be interesting
to see if these two pins also can be
used as e-field sensors.

The device requires a minimum of 9 V

for operation, so we provided a 12-V
power supply to the V

PWR

pin. This

allows us to better utilize the batter-
ies. An on/off switch, S3, is connected
between the battery and the V

PWR

pin.

A diode is connected between the sup-
ply and V

PWR

pin to prevent the dam-

age caused by the reversal of the
power supply polarity.

There are two internal voltage regu-

lators. One provides regulated 5-V,
75-mA output for driving the external
devices and for some internal opera-
tions. The second provides analog reg-
ulated voltage (8.5 V) for interfacing to

as the electrodes (see Photo 1a).
Copper tape is easy to solder to.
Aluminum tape will require some
form of crimping for a reliable connec-
tion. Photo 1b shows how we stuck
the keypad electrodes to the sides of
the bag, and Photo 1c shows the com-
pleted project.

HARDWARE

In addition to the MC33794 and low-

cost flash memory MC68HC908QY4
microcontroller, the system includes a
UART level converter MAX232 for
the RS-232 interface. Note that all of
these components are included in the
evaluation board. We only needed to
add the buzzer and a power supply to
this board. The simple power supply is
a 12-V battery pack comprised of eight
AA batteries.

The MC33794 supports up to nine

electrodes, but it senses only one elec-
trode at a time. We used six: electrode
pins E1 through E5 and E9, which is
used as the reference electrode for
comparing the alarm condition detec-
tion threshold. Note that it is not con-

the external analog devices and for
some internal operations. The regulat-
ed 5-V output at the V

CC

pin is taken

as the power supply for the microcon-
troller and the RS-232 level converter.

The MC33794 is used to detect

objects in an electric field. Its self-con-
tained internal oscillator generates a
low-distortion 5-V

PP

sine wave. The

normal operating frequency is set to
120 kHz and controlled by an external
resistor connected to the R_Osc pin.
The sine wave passes through an
internal 22-k

resistor into an inter-

nal multiplexer, which delivers the
signal to one of the selected electrode
output pins (E1–E9) or the two refer-
ence pins (REFA and REFB).

The electrode is selected by the

ABCD input, which is controlled by
the microcontroller. For each elec-
trode, there is a particular ABCD
input logic. Unselected electrodes are
automatically grounded. The current
through the internal resistor is deter-
mined by the effective capacitance of
the object in the electric field of the
selected sensor electrode. This effec-

54

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

55

IDE, this provides a powerful program-
ming and debug environment at lit-
tle or no cost at all. Only one pin is
used. All of these features make
MC68HC908QY4-based development
a pleasant experience.

The MAX232 level converter IC is

used for the RS-232 interface. The
PTB4, PTB5, PTB6, and PTB7 pins con-
trol the MC33794 inputs A, B, C, and
D. PTB3 is connected to the MC33794’s
DIS_SHIELD pin for controlling the

tive capacitance determines the signal
level at the selected electrode and the
DC output level.

There is also an internal receiver

multiplexer that passes the signal at
the selected electrode pin to a detec-
tor. The detector converts the sine
wave to a DC level. This DC level
voltage is filtered by a low-pass filter
formed by the external capacitor C3 at
the LP_CAP pin and the internal
resistance from the detector to this
pin. The DC level is amplified, offset,
and output at the LEVEL pin.

The sensor is intended to operate in

the 10- to 100-pF capacitance range. A
higher effective capacitance value
means a lower signal (120 kHz) level
at the selected electrode pin and con-
sequently a lower DC output level.
Thus, the DC output level is inversely
proportional to the effective capaci-
tance of the object in the sensor’s elec-
tric field.

The square waveform of the 120-kHz

internal sine wave output is available
at the CLK pin. This clock is connected
to the unused WD_IN watchdog pin to
prevent a reset condition.

The output at the LEVEL pin is then

connected to the MC68HC908QY4’s
A/D converter via JP1. Note that it’s
an 8-bit, four-channel A/D converter.
We used channel 3 for converting the
LEVEL voltage.

The S2 push button switch is con-

nected to the PTA2 pin. S2 is used to
enter the MC68HC908QY4’s User
Monitor mode, which facilitates the
programming of its flash memory and
in-circuit debugging. Holding down S2
while turning on the power enters this

mode. The PTA0 pin is dedicated for
half-duplex RS-232 communication
(the user monitor uses PTA0 both as a
RX and a TX pin via bit-banging) for
programming and debugging in User
Monitor mode.

The SV1 connector on the board is

for programming the user monitor pro-
gram into the microcontroller if the
user program is accidentally erased and
for programming a blank microcon-
troller. Along with the CodeWarrior

Photo 1a—

The electrode is soldered to the tape, battery pack, and buzzer. The three small strips are for the keypad electrodes. The next largest form the lift electrode, and the

largest is for one side of the proximity electrode.

b—

The keypad electrodes are stuck to the sides of the bag. The tape in square formation is the internal part of the proximity

electrode. The battery pack and the board go inside a bag compartment.

c—

Here you can see the wired bag from the outside. The lift electrode is stuck under the handle. The

two tabs on both sides of the bag are the three keypad electrodes and one dummy electrode. The long strip is the outside portion of the proximity electrode.

a)

b)

c)

background image

56

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

in Figure 3, a few simple states
describe the system’s behavior.

After initialization, the system

checks the keypad for an arming code.
The alarm is off in this state and can
be armed with the keypad (electrodes).
The electrode connected to pin E1 rep-
resents the code “1”; E2 represents the
code “2”; and pin E3 represents the
code “3.” A “231” arming code is used
here. This is equivalent to touching
electrodes E2, E3, and E1 in order

within a 3.2-s window for each key.
This takes the system to the protect
state, during which it monitors the
lift and proximity electrodes for alarm
conditions and the keypad electrodes
for key presses.

After a key is pressed in the protect

state, the system goes to a state
checking for the disarming code. Here
the code must be entered within the
3.2-s window for each key. A “321”
disarming code is used here. Entering
a wrong code causes the buzzer to pro-
duce a short burst of sound. This will

require some practice. However, the
3.2-s window can be easily removed
(as will be explained later).

Alarm conditions are detected in

the protect state. This turns on the
timer and causes the buzzer to sound
until the disarming code is entered.
Figures 4 and 5 show the firmware
operations in detail.

INITIALIZATION

The internal oscillator is selected as

the microcontroller’s clock source by
clearing the OSCOPT0 and OSCOPT1

shield signal. PTB2 is connected to
LAMP_CTRL for controlling the lamp
driver circuit. A buzzer is connected
to PTB1 for sounding the alarm.
Switch S1 resets the MC33794 inde-
pendently. All of the aforementioned
components, along with a few decou-
pling capacitors, complete the design.

FIRMWARE

The firmware for the project is rela-

tively straightforward. As you can see

Check for

arming code

Initialize

Check for

disarming Code

Set timer off

Disarm code

Protect

(monitor electrodes E4 and E5)

Arm code

entered

Detected alarm

condition

Key pad
activated

Wrong

code

Set timer on

Main

Buzzer

on

Buzzer

off

Timer

off

Timer

on

Timer

Figure 3—

The design is fairly simple. Note that it has only three states: arm, disarm, and protect. The buzzer is

either on or off.

background image
background image
background image

pressed. The MCU reads the MC33794’s
DC level OUT pin using the 8-bit A/D
converter. Testing has shown that the
A/D converter count for an untouched
key is around 150. If the key electrode
is touched, the A/D converter count
for the electrode is usually zero. If the
count is less than 20, that particular
key is being pressed. Selecting the
same electrode and sampling the A/D
converter 20 times achieve key
debouncing.

The MCU’s auto-wake-up interrupt

is a 3.2-s delay between each key
scan. A count of 200 auto-wake-up
interrupts (16 ms each) creates the
3.2-s delay. This means you have 3.2 s
to enter each key. If this doesn’t hap-
pen, you must reenter the code.

Listing 1 shows the code section that

scans the keypad for the arming
code. The 3.2-s window for each key
during the arming (and disarming)
process is achieved using 200 loops
(

Sleep_Count) of the 16-ms auto-wake-

up interrupt (shared with the keyboard
interrupt). The interrupt service routine
merely sets the keyboard acknowledge
bit flag to clear the interrupt request.

STATE OF PROTECTION

If the suitcase is armed, the

firmware checks for the alarm condi-

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

59

bits in the CONFIG2 register. The
internal oscillator generates a clock of
12.8 MHz, which is internally divided by
four, resulting in a bus speed of 3.2 MHz.
Setting the stop bit in the CONFIG1
register enables Stop mode. Setting the
SSREC bit in CONFIG1 sets the stop
recovery time to 32 clock cycles.

The LVI and COP modules, which

are also in the CONFIG1 register, are
disabled because they are not used.
The 16-ms auto-wake-up interrupt
request period is set by setting the
COPRS bit to one in the CONFIG1
register. In the Keyboard Interrupt
Enable register, the AWUIE bit is set
to enable the auto-wake-up interrupt.
The A/D converter clock is set to
approximately 1 MHz, and channel 3
is selected for the DC-level sensing of
the electrodes. PTB1, PTB2, PTB3,
PTB4, PTB5, PTB6, and PTB7 are con-
figured as outputs, and they are initial-
ized to zero. PTB0 and PortA bits are
configured as inputs.

The timer interface module (TIM)

clock source is selected by writing to
the TSC register, where the timer
clock is set to the internal bus clock

divided by two, and the TIM counter
is cleared. The modulo value for the
TIM counter is set in the TIM count-
er modulo register to overflow every
528 bus cycles. Setting the
TOIE bit in TSC register
enables the TIM overflow
interrupt. The TIM is used
to produce the 1.5-kHz
buzzer tones.

READING THE KEYPAD

Touching the correspon-

ding electrodes in order
enters the code. Because
we used electrodes for the
keypad, the firmware
scans for the arming and
disarming code by select-
ing the appropriate elec-
trode. The appropriate
electrode (key) is selected
for scanning by setting the
corresponding A, B, C, and
D logic pins through MCU
ports PTB4, PTB5, PTB6,
and PTB7, respectively.

Next, you need to deter-

mine if the selected key is

Start

Initialize the alarm output and electrode selector pins

Read the ADC value of reference electrode (E9)

Enable automatic wake-up and timer overflow interrupts

Is any key pressed?

Is arming

code correct?

Is lift electrode

(E4) activated?

Enables timer for producing

the alarm sound

Is any key pressed?

Is disarming

code correct?

Disables timer

Is proximity

electrode (E5)

activated?

Alarm()

N

Y

Y

Y

Y

Y

Alarm()

N

N

N

Y

N

N

Figure 4—

The firmware works well. This flow chart shows how we handle the arm, disarm, and protect states.

Alarm ()

Count = 0

Start timer with interrupt

request disabled

Is count

less than 10,000

Timer interrupt

flag set?

Clear interrupt flag

Increment count

Toggle buzzer pin

Y

Y

N

Timer overflow

interrupt

Clears timer overflow

interrupt flag

Toggle buzzer pin

Stops timer

Exit function

N

Short buzzer burst

Normal buzzer sound

Figure 5—

There are two different buzzer sounds. This chart shows

how each one is produced. The buzzer produces a short burst to indi-
cate an incorrect code entry during arming or disarming operation. The
regular buzzer sound is used under alarm conditions.

background image

60

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

tions. It also checks for the disarming
code on the keypad.

The first alarm condition is when

the lift electrode in the suitcase han-

dle is activated. To detect such a con-
dition, the MCU selects the lift elec-
trode E4. The DC level is read by the
MCU. As with the keypad elec-
trodes, an A/D converter count of
less than 20 means that the electrode
is being touched. This will activate
the alarm that is stopped only if the
disarming code is entered or the bat-
tery runs out.

The second alarm condition is when

the proximity electrode (on the out-
side of the suitcase) is moved away
from your body. A larger area elec-
trode is used for the proximity elec-
trode. This assures a low A/D convert-
er count when it’s placed near your
body. If the count is greater than half
the reference A/D converter count,
the alarm is activated. The count is
obtained by enabling the E9 electrode.
(Although not connected anywhere, it
provides a reference A/D converter
count suitable for the ambient condi-
tions.) It is taken as a reference count
for detecting the suitcase moving
away from your body.

BUZZER OPERATION

The TIM produces alarm output.

Figure 5 shows the details.

When the timer overflow interrupt

request is enabled, it produces a 1.5-kHz
waveform output at the PTB1 pin for
the normal buzzer sound under alarm
conditions. During arming or disarm-
ing, a wrong code entry produces a
short buzzer burst. Polling the timer
overflow interrupt flag produces this
1.5-kHz waveform burst. (The timer
interrupt request is disabled here.)
Thus, you can distinguish the two
sounds.

Now that you’re familiar with the

firmware operation, let’s move on to
programming and debugging.

PROGRAMMING & DEBUGGING

We used the CodeWarrior develop-

ment environment to write, compile,
download, and debug the firmware
(see Figure 6). The MC68HC908QY4
in the KIT33794DWBEVM is prepro-
grammed and contains the user-mode
monitor program in the block-protect-
ed area of the MCU. This allows you
to program (and debug) your applica-
tion from the CodeWarrior IDE

Listing 1—

This code section scans for the arming code and the keyboard interrupt service routine. The 3.2-

s window for each of the keys in the arming code is achieved using 200 loops (

Sleep_Count

) of the

16-ms autowake-up interrupt (shared with the keyboard interrupt). The interrupt service routine merely sets
the keyboard acknowledge bit flag to clear the interrupt request. To remove the 3.2-s window, just comment
out

Cpu_SetStopMode()

.

const unsigned char code[3] = { 2, 3, 1 };

const unsigned char DisArm_Code[3] = {3, 1, 2 } ;

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

Function

:

Arm_Code_Func

Inputs

:

None

Outputs

:

The device disarmed or not

Date

:

08/17/2003

Description

:

Checks for the disarming code

Changes

:

None

Status:

:

Tested OK

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

bool Arm_Code_Func(void)

{

unsigned char i;

unsigned char Sleep_Count;

bool Armed;

for (i=0; i<3; i++)

{

for (Sleep_Count=0 ; Sleep_Count< 20; Sleep_Count++)

{

EField_Measure_Init(code[i]);

AD1_OutV = AD1_MainMeasure();

if (AD1_OutV < Touch_Ref)

{

Armed = TRUE; // Arm code checking

}

else

{

Armed = FALSE;

break;

}

}

if (Armed == FALSE )

{

if (i >1)

Alarm();

// This alarm indicates wrong code

break;

}

else

{

for (Sleep_Count = 0; Sleep_Count < 200

; Sleep_Count++)

{

Cpu_SetStopMode();

}

}

}

return Armed;

}

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

Function

:

KBD_Interrupt

Inputs

:

None

Outputs

:

None

Date

:

08/17/2003

Description

:

Keyboard wake-up interrupt

Changes

:

None

Status:

:

Tested OK

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

#pragma TRAP_PROC

void _KBD_Interrupt(void)

{

KBSCR_ACKK = 1;

}

background image

output, you could use transistors in a
H-Bridge configuration to drive it.

Other ideas include using a

rechargeable power pack and adding
an LED indicator to show that the
system is armed. A variable poten-
tiometer could provide an adjustable
threshold for proximity alarm condi-
tion detection when connected to one
of the A/D converters. Finally, consid-
er programming the arming and dis-
arming code for more flexibility.

I

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

61

Seenath Punnakkal is an electronics
and telecommunications engineer.
Her technical interests include micro-
processors and DSP. You may contact
her at seenat@hotmail.com.

Sameer Cholayil designs test equip-
ment at Tempo Research Corp. He is
interested in MCUs, FPGAs, develop-
ment tools, and fiber optics. You may
reach him at sameer_c@hotmail.com.

RESOURCES

Motorola, “MC33794 Fact Sheet,”
MC33794FS/D.

———“MC68HC08 Microcontrollers,”
rev. 3.0, 2004.

KIT33794DWBEVM documentation,
www.motorola.com.

J. Sibigroth, “User mode monitor
access for MC68HC908QT/QY series
MCU,” AN2305, Motorola, 2003.

J. Suchyta, “Low cost Programming
and Debugging Options for M68HC08
MCUs,” Motorola, 2002.

———“Reprogramming the
M68DEMO908QT4,” Motorola, 2002.

PROJECT FILES

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

SOURCE

KIT33794DWBEVM, MC33794 E-field
sensor, MC68HC908QY4 microcon-
troller
Motorola, Inc.
(800) 521-6274
www.motorola.com

through the RS-232 port without an
external oscillator and high voltage.

The user-mode monitor program

loads in an unused discontinuous
memory area around the user vector.
So, you can utilize the full 4 KB of
flash memory for your application
program. Because the user monitor
area (FFB0 to FFFF in Figure 6) is
block-protected, you cannot program
the interrupt vectors to point to their
own interrupt service routines. So,
there is a vector redirection mechanism
to point the actual vector to a pseudo-
vector area (FDEB to FDFF in Figure 6).

For more information, refer to the

pseudo vector table defined in file vec-
tors.c, which you may download from
the Circuit Cellar ftp site. This user-
mode monitor program provides ini-
tialization, vector redirection, and
entry into the monitor program locat-
ed in the monitor ROM. The code in
the monitor ROM allows for in-circuit
debugging and programming through a
single-wire interface.

After power-on reset, the reset vec-

tor points to the start of the user
monitor program. Then, the
IRQ(PTA2) pin level determines the
mode of operation—Execution mode
or Debug mode. The S2 switch is con-
nected to the PTA2 pin. If the pin is
high and the user reset pseudo vector
has been programmed, the application
program is executed. If the pin is low

(S2 held down at
power-up), the user-
mode monitor pro-
gram jumps to the
monitor program in
the monitor ROM. At
this point, you may
program the device
and start debugging
the application from
the CodeWarrior IDE.

PROGRAM A
BLANK DEVICE

If the user-mode

monitor program is
accidentally erased,
you can easily repro-
gram it. To ensure a
9,600-bps data rate for
user-mode operations
(program/debug), you

need the oscillator trim value from
the FFC0 value. Therefore, it’s highly
recommended that you get the FFC0
address (using CodeWarrior IDE)
before programming anything the
MCU.

At the end of the user-mode moni-

tor program assembly file, write the
trim value reading into FFC0.
Connect JP1 pins 2 and 3. Then, con-
nect a 9.8304-MHz oscillator to con-
nector (SV1) pin 13 (OSC1). Connect
the MAX232’s V+ pin to connector
pin 6 for programming high voltage.
Connect connector pins 15 and 1.

Now you are ready to download

the user-mode monitor program.
After doing so, disconnect the con-
nector and then connect jumper JP1
pins 1 and 2. The MCU is now ready
for programming and debugging in
User Monitor mode.

POSSIBLE IMPROVEMENTS

We have several design improve-

ments in mind. In its present configu-
ration, the Antitheft Suitcase doesn’t
provide a snatch-while-carrying detec-
tion condition. Actually, holding the
armed suitcase by its side while carry-
ing it will provide snatch detection.
However, we have four free sensor elec-
trodes that may be used in various con-
figurations to detect a such condition.

Also note that the buzzer sound is

not loud. For better sound and more

Flash

memory

EE00

FDFF
FE10

FFAF

FFB0

FFCF

FFD0

FFFF

Flash

memory

Monitor ROM

User vectors

Memory map of blank

MC68HC908QY4

Flash

memory

free

Flash memory

application program

Pseudo vectors

Monitor ROM

User monitor and

user vectors

EE00

FDE9

FDEA

FDFF

FE10

FFAF

FFB0

FFFF

Memory map of

MC68HC908QY4

with user monitor

program

Figure 6—

The user monitor program is located in the unused discontinuous

area of flash memory. Because the interrupt vector resides in a block-protected
area of memory, a vector redirection mechanism is provided in the source
code to point to the pseudo vector locations when an actual interrupt occurs.

background image

whine is typical of pulse-width modu-
lated stepper drives, perhaps I could
quiet it down a bit. In the finest engi-
neering tradition, I popped the box
open and started tearing things apart.

Remember this: Sherline’s controller

box works correctly, and the company
has have many satisfied customers. I
was interested in making it work better.

INSIDE THE BOX

The milling machine has three step-

per motors, one for each of the x-, y-,
and z-axes. I also bought a rotary table
driven by an identical motor. The con-
trol box shown in Photo 1b has four
channels, each using a PIC16F627
microcontroller and an Allegro
SLA7044M unipolar stepper motor driv-

ABOVE THE GROUND PLANE

by Ed Nisley

62

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Y

ou’ve read many articles describ-

ing stepper motors, most likely as part
of their application in everything from
printers and scanners to robotic
manipulators and headlight levelers. A
stepper’s key attribute is that its rotor
moves in discrete steps that make
positioning a simple matter of count-
ing pulses. DC and AC motors, while
seemingly simpler, require relatively
complex feedback mechanisms to
achieve the same functions.

Unfortunately, while stepper motors

are easy to get working, they can be
surprisingly difficult to get working
correctly. Although rotor positions
may be nearly digital and drive cir-
cuitry may use on-off switching, the
actual voltages and currents remain
ruthlessly analog. Abruptly switching
the motor’s high currents can trigger
tremendous transients that may dis-
rupt other circuits, damage compo-
nents, or create radio-frequency inter-
ference throughout an entire building.

What brings this up is that I recent-

ly bought a Sherline CNC milling
machine to drill circuit boards and
machine small parts (see Photo 1a).
The control program runs on a stan-
dard PC under Red Hat Linux with the
RTLinux hard real-time extensions. It
controls the milling machine’s stepper
motors through a standard parallel port,
using a driver box to convert logic-level,
step-and-direction signals into high-
power pulses for the stepper motors.

The overall system worked fine, but

the motors gave off an annoying high-
pitched whine. I did some investigat-
ing and discovered that, although a

er. The PIC16F627 converts the step-
and-direction signals from the printer
port into the datastream required to
configure the driver chip, which han-
dles the high-current switching.

The ’7044 has two identical sec-

tions, each with the functions shown in
Figure 1. A unipolar stepper motor has
two separate center-tapped windings,
known as A and B, with the tap connect-
ed to the motor drive voltage. Only one
driver transistor for each winding will be
on at any time, directing current through
that winding to the SENSE output pin.

The two halves of each winding are

the + and – signs, although the + is
usually omitted and the – may be an
overbar rather than a minus sign.
Thus, the A winding has A and –A

Stepper Drive (Part 1)

The motors in Ed’s milling machine were whining, so he opened the controller box and
started working on the problem. In this two-part series, Ed explains how he reworked the
controller box to run a bit quieter.

+

V

DD

–1

3 14

D/A

V

REF

Latches

Shift reg

5 16

6 17

2 13

*Strobe

Data

Clock

Phase

Ref/*Enable

+

Programmable

PWM off timer

noise filter

Enable

V

DD

10

9

12

7

Sense

Ground

15

4

1

11

8

18

Control supply

Out

A/B

Out*

A/B

Channel A pin numbers

Channel B pin numbers

Figure 1—

The SLA7044M

contains two identical sections that drive the two center-tapped windings of a unipolar stepper

motor. The controller limits the coil current using pulse-width modulation, so the MOSFET transistors are either fully on or fully
off and dissipate relatively low power. The Zener diode across each

MOSFET conducts when the transistor switches off.

Analog

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

63

halves, and the B winding
has B and –B.

The mill’s motors rotate

1.8

°

for each full step:

200 steps per revolution. The
step sequence is straight-
forward, with current flow-
ing through A, B, –A, –B,
and A again, in that order.
Reversing the step sequence
reverses the motor: –B, –A,
B, and A brings the rotor
back to the starting point.

Each motor drives a 20-

turn-per-inch lead screw
that moves the carriage
0.050

per revolution,

which is 0.00025

per

motor step. Because that’s
not enough resolution for
machining operations, the
Sherline control box runs
the motors in quarter-step
mode by simultaneously
activating two windings. A
complete rotation thus
requires 800 quarter-steps
of 62.5 microinches.

When the A winding is

energized, it aligns the

rotor directly under its poles.
Similarly, the B winding pulls the
rotor underneath its poles. Energizing
both windings positions the rotor
halfway between them, but the dou-
bled current also causes higher field
strength and more torque. To maintain
the same torque, the current in each
winding must be reduced to 0.71 =
sin(45°) of the “single-step” value.

Positioning the rotor one-quarter of

the way from the A poles to the B
poles requires fractional currents of
0.92 = cos(22.5°) and 0.38 = sin(22.5°)
in the A and B windings, respectively.
Driving A with 0.38 and B with 0.92 of
the nominal current puts the rotor one
quarter-step from the B poles.

The SLA7044M can set the winding

current to those values, but the PIC must
send four configuration bits for each
quarter-step to each half of the driver
chip. That process requires about 45 µs,
roughly 10 µs per bit. The ’7044 has a
data rate spec slightly faster than 1 Mbps,
but the PIC doesn’t produce bits that fast.

PWM PULSES

The Sherline motors are rated at 3.2 V

and 2 A, with a DC resistance of 1.6

in each winding. The datasheet speci-
fies a winding inductance of 3.6 mH.

Under DC conditions, a 3.2-V supply

would drive the motor at its rated 1.6 A,
with the side effect of dog-slow response.

The torque developed by a
motor is proportional to its
current, but that current is
limited by the circuit’s L/R
time constant. Assuming an
external resistance of 1

,

the time constant is approx-
imately 1.4 ms (3.6 mH/
2.6

). Allowing three time

constants per step for the
current to reach 95% of its
final value, the motor could
turn at only 240 steps per
second—18 rpm or 0.9

per

minute in quarter-step
mode. That’s obviously
inadequate!

The schematic in

Figure 2 reduces one half
of the SLA7044M driver to
its simplest form: a MOS-
FET power transistor with
a pulse generator for the
gate drive. The center-
tapped motor windings, A
and –A, use the spec-sheet
values for their equivalent
components. The 0.33-

current-sensing resistor,

R

SENSE

, is surrounded by

parasitic elements with
estimated values.

Photo 1a—

I mounted my mill next to my full-size lathe.

The keyboard and mouse hide under the reinforced kitchen
countertop base when the mill is making chips. The motor
driver box is just to the left of the monitor.

b—

The Sherline

8760 CNC driver box controls four unipolar stepping
motors. Each axis uses a Microchip PIC16F627 microcon-
troller

and an Allegro SLA7044M PWM motor driver.

Standard PC keyboard cables connect the box to the
motors. This is the board after I added two brown

capaci-

tors, but before I commenced the major modifications.

Figure 2—

A Spice model of one winding’s circuitry

includes both measured and datasheet values for the
main components. The parasitic elements are, at best,
guesstimates.

Figure 3—

Although the model does not duplicate the observed oscillations, it does

reveal the switching transients that excite them. The green trace is X1’s VDS divided by
100. The transistor’s drain hits 100 V!

a)

b)

background image

64

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Figure 3 shows the cir-

cuit in action. The current
rises to nearly 2 A in 300 µs
when the PWM pulses
begin regulating it. The cur-
rent would rise to 8 A
(24 V/3

) without PWM,

so the current hits 2 A
much more quickly than it
would with a 3.2-V supply.
Because this is not a closed-
loop simulation, I simply
fiddled with the pulse tim-
ings to get approximately
2 A average current.

The winding current

cannot stop abruptly when the MOSFET
switches off. Instead, the drain-source
voltage rises from nearly zero to the
breakdown voltage of the Zener diode,
approximately 100 V, as the diode begins
to carry the current around the MOSFET.
The parasitic elements translate that sud-
den voltage jump into spikes that show
up at the drain and source terminals.
Whenever a simple simulation shows
spikes like that, you can be sure the real
circuit will be even more interesting!

FINDING TRACES

Photo 2 shows the voltage at the

two MOSFET switch drains and the
top of R

SENSE

. The drain voltages peak

at well over 100 V, as you’d expect
from the simulation, and the hash on
the resistor is nearly 1 V. This is a
somewhat different situation from the
simulation in Figure 3, which details
the PWM current-limiting action dur-
ing a single step. Note the different
time scales.

The MOSFET’s drain

voltage is close to zero
when it’s on and snaps
far above the 24-V supply
when it’s turned off. The
relatively slow drop
while the winding is off
occurs because the PWM
regulator only runs for
the active winding.

I replaced the motor

with a pair of 10-k

resistors to produce
Photo 3. With extremely
low currents and no
winding inductance, the

drain and current-sense voltages look
like textbook illustrations of transis-
tor switching. Note how the hash in
Photo 2 occurs when each MOSFET
switches off. You can see the timings
much more clearly in Photo 3.

You must get a closer look at the actu-

al board layout to understand what’s
going on here, because the relevant com-
ponents are largely invisible. In fact, they
don’t show up in schematics and aren’t
identified by the board’s silkscreen.

Photo 2—

The voltage at the SLA7044M motor winding terminals shows the expected greater

than 100-V spikes, which appear as hash on the current-sense voltage in the lower trace.
The lower-amplitude noise between the main switching bursts comes from the other winding.

background image

winding paths, while the green ovals
indicate digital logic ground connections.

The red trace near the bottom of the

picture is the motor and logic ground
bus with conductors on both circuit
board layers. Just above it is the 24-V
motor power supply trace on the sol-
der side. The purple 5-V logic supply
runs down the left side of the ’7044
from the PIC16F627 above the 0.33-

current-sensing resistors.

A circuit that switches high cur-

rents through large inductors, while
simultaneously using low-voltage digi-
tal logic, presents difficult board lay-

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

65

Photo 4 shows an X-ray view of the

components and traces for one axis of
the Sherline control box. I laid the
board on my scanner to capture both
component- and solder-side views at
300 dpi. I reversed the solder-side
view left-to-right, and then applied a
free transform to get a nearly perfect
overlay atop the component-side view.
I also erased the green solder mask,
inverted the trace color, and made the
solder-side layer about 50% transpar-
ent to allow the components to show

through the traces.

I used the GNU

Image Manipulation
Program (The GIMP)
under Mandrake
Linux, but you prob-
ably have a photo-
editing program that
can do similar
things. Putting dif-
ferent views and

markups on separate
layers simplifies cor-
rections and lets you
examine combina-

tions of elements.
Sometimes the
best tool isn’t a sol-
dering iron!

Identifying the

traces was a simple
matter of marking
up a printed copy
with reference to
the SLA7044M
datasheet. The yel-
low and cyan lines
show the A and B

Photo 3—

Replacing the motor windings with a pair of 10-k

resistors demon-

strates that the noise arises from high currents, not the driver itself. Note that
the two halves of the winding are never active at the same time.

Photo 4—

This view of the Sherline board’s x-axis driver superimposes the bottom

traces in red. Green ovals highlight connections between digital and high-current
grounds. The cyan and yellow lines show the A and B winding conductors, respectively.

background image

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

67

make it match the reality
of Photo 3. In fact, there’s a
key component missing
from the model. I decided
to start improving the
board layout, rather than
fiddling with the model.

CONTACT RELEASE

In my next column, I’ll

go into more detail about
the PWM current regula-

tion, with a dash of PIC
microstepping code, and
explore how the modifica-
tions affected the wave-

forms. Your homework is to examine
Figure 2 and Photo 4, and then decide
which components to relocate, which
traces to cut, and what additional connec-
tions are needed. The object is to have a
controller box that works just as well as
it did before my changes, only quieter!

I

PROJECT FILES

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

SOURCES

SLA7044M Motor driver
Allegro MicroSystems, Inc.
(508) 853-5000
www.allegromicro.com

B2 Spice simulator
Beige Bag Software, Inc.
(734) 332-0487
www.beigebag.com

GNU Image Manipulation Program
(The GIMP)
www.gimp.org

PIC16F267 Microcontroller
Microchip Technology, Inc.
(480) 792-7200
www.microchip.com

Milling machine
Sherline Products, Inc.
(800) 541-0735
www.sherline.com

Ed Nisley is an E.E., P.E., and author
living in Poughkeepsie, NY. You may
contact him at ed.nisley@ieee.org. Put
“Circuit Cellar” in the message’s
subject line to clear the spam filters.

out challenges. The sim-
ple zero-resistance lines in
the schematic beguile you
into thinking that physi-
cal wires and traces
behave the same way
when, in fact, they can
prevent the circuit from
working at all. In this case,
the circuit works, but
Photo 2 shows that it’s not
behaving as you’d expect.

GROUND TRUTH

The single most impor-

tant voltage in any circuit
is zero, which is the “ground” or
“common” connection. Because all
other voltages are measured against
that reference, any variation in the
common voltage across the board is
cause for concern. The ideal common
connection is an uninterrupted ground
plane that covers the entire surface of
the circuit board. Reality often pre-
vents that, particularly on two-sided
circuit boards like the one in the
Sherline control box.

The board is covered with “1-ounce”

copper, which means the copper sheet
weighs 1 oz./ft

2

, and is about 0.0014

thick. The 24 V and ground traces
along the bottom of Photo 2 are 0.12

wide, and the ground traces to the
current-sensing resistors are 0.06

,

with cross-sectional areas of 170 ×
10

–6

in

2

and 84 × 10

–6

in

2

, respectively.

Copper’s room-temperature resistiv-

ity is about

ρ

= 680 × 10

–9

·in. The

resistance of a conductor is:

L

and A are the length and cross-sec-

tional area. The 0.06

ground trace has

a DC resistance of 16 m

, but it

includes vias and component pads
that tend to increase the resistance.

However, a conductor’s inductance

begins to dominate its resistance as
the signal frequency increases. The
classic formula for the inductance of a
round, straight wire is:

where L is in microhenries and the
radius (r) and length (a) are in inches.

L

a

r

= 0.005 a 2.3log

0.75

×













2

R

L

A

=

ρ

Because real wires aren’t isolated in

free space and the skin effect modifies
their electrical radius at higher fre-
quencies, the formula isn’t particularly
good. Printed circuit conductors are
flat, attached to a slab of dielectric
material, and close to other conduc-
tors, which makes the approximation
even worse.

With that in mind, the 2

trace from

the current-sensing resistors to the
ground bus has an inductance of
approximately 40 nH. The reactance of
an inductance at a frequency F is:

The 2-A winding current should

drop about 30 mV across 16 m

,

which agrees reasonably well with
Photo 5. The reactance seen by the
2-MHz ringing at each transition is
0.5

, a factor of 60 higher than the

DC resistance, so a 300-mV peak
requires approximately 600 mA. That
ringing has some energy behind it!

The frequency of an LC oscillator is:

The current through the motor

winding is continuous during the
switching transitions, so the induc-
tance is contributed entirely by para-
sitic elements in the circuit. If the
ringing occurs between the capacitance
at the SLA7044’s motor terminal and
the trace inductances, the total induc-
tance might be 70 nH. That makes the
stray capacitance approximately 90 nF,
which seems somewhat high.

It turns out that feeding those values

into the model shown in Figure 2 doesn’t

f

LC

=

1

2

π

X

L

= 2 FL

π

Photo 5—

The ground trace from the sense resistors to the ground bus shows a definite

voltage drop with a 2-A current. The trace’s inductance contributes to the peaks when the
transistors switch. The circuit rings at approximately 2 MHz.

background image

68

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

t seems like everything that used to

be built as a pure analog function is
becoming digitized. But there are still
some things that just don’t work as
well in the digital domain as they do
in the analog domain.

The music industry is a good exam-

ple of a place where analog things
have gone digital for better or worse.
All sorts of digital gadgets are used
in recording studios. I have a guitar
gadget that actually slows down the
guitar licks on a CD-ROM track so
you can pick them apart and learn
them note-by-note. Yeah, right. You
see my picture. Do I look like the
next Eddie Van Halen? There are even
a couple of high-end digital guitars
out there. I recently read a story
about Aerosmith’s mixed feelings
about putting down recording ses-
sions on a hard drive instead of mag-
netic tape. The upside of the musical
hard drive is that the band
can now mix and record
whenever and wherever they
want. Lead singer Steve Tyler
has talked about how great it
is to be able to pack up the
golden hard drive and take it
over to another band mem-
ber’s home studio for some
off-the-wall recording and
mixing sessions.

When asked about the use

of digital techniques in the
music recording industry,
George Harrison said that he
actually liked to hear a bit of
natural tape hiss in his record-
ings. George is an analog kind
of guy. Some musicians
(including Paul McCartney)

digital input pins. So, you use either
the microcontroller’s internal A/D
converter or hang an external A/D
converter on the microcontroller’s I/O
pins. That’s usually good enough for
simple applications processing rudi-
mentary analog voltages.

What if you need to amplify the

incoming analog signal? No problem.
Add an op-amp to the circuit. Need to
filter that incoming signal? No prob-
lem. Just add another op-amp.

OK. You’ve got the analog signal

digitized and into the bowels of your
microcontroller. Most of the time
that’s good enough, and you can act
on the incoming analog signal without
having to push it back out of the
microcontroller. But what if you had
to do some stuff with the digitized
analog signal and send the processed
analog signal back out to the real
world? No problem. You simply add

an D/A converter to your cir-
cuit. Yeah, right.

If you’ve ever put anything

electronic together from
scratch, you know that I lied
big time in the previous para-
graph. There’s no such thing
as “no problem” when you
start adding analog things to a
design. In addition to adding
op-amps, capacitors, resistors,
and who knows what else to
condition the incoming and
outgoing analog signals, you
now have the added burden of
tweaking and debugging all of
that analog stuff you added to
the circuit as well as the code
in the microcontroller.

To get the best sound possi-

PSoC 101

APPLIED PCs

by Fred Eady

say that George invented controlled
feedback on record with the release of
the Beatles’s song, “I Feel Fine.” I
won’t argue that point here.

I’ve gotten rid of all of my transis-

torized guitar amps and digital effects
stomp boxes in favor of all-tube
amplifiers and analog floor pedals. I
like the digital technology, but the all-
tube pure analog amplifiers just sound
better. Consider this: Aerosmith may
digitally record the songs you buy on
CD-ROM, but they use an abundance
of analog equipment to deliver that
music to you live from stage.

Now that you’ve pulled out those

old Beatles recordings and listened to
see if you can hear the tape hiss, let’s
talk about how you handle analog sig-
nals with a microcontroller. It’s pretty
much a given that you cannot do a
good job of capturing a series of ana-
log events using a microcontroller’s

Analog design doesn’t have to be complicated, especially if you use a PSoC. In this column,
Fred describes his PSoC development system, which is geared toward the CY8C27443.

Photo 1—

Note that a 16-bit PSoC counter requires two PSoC digital function

blocks. I tied the counter enable lines high to make them active. The lines also
can be controlled by outputs from the comparators, input I/O pins, or output I/O
pins. Each of the little blue output and red input muxes covers four of the 16
green vertical global interconnect lines.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

69

ble, you can use digital mod-
eling music amplifiers that
process the incoming analog
signals digitally and repro-
duce those digitally altered
tones to your ears with old-
fashioned tube-based analog
technology. Fortunately, you
can manipulate analog and
digital signals in a similar
manner using a Cypress pro-
grammable System-on-Chip
(PSoC), which is mixed-signal
microcontroller-based device.
“No problem” takes on its
real meaning when you
employ a programmable PSoC
in your mixed-signal design.
You can build and debug ana-
log and digital subsystems
that are contained within a single
PSoC device.

PSoC BASICS

There are numerous PSoC variants

that contain differing combinations of
internal resources and I/O pin counts.
Because my PSoC development sys-
tem is geared toward the 28-pin
CY8C27443, that’s the part I’ll con-
centrate on in this column. After you
have the CY8C27443 fundamentals
down, you can use the same concepts
to design with the other members of
the CY8C27xxx family.

The CY8C27443 is composed of an

8-bit microcontroller core, eight 8-bit
digital PSoC function blocks, and 12
analog PSoC function blocks. The

eight 8-bit digital PSoC function
blocks are divided into a group of four
digital basic blocks (DBBXX) and a
group of four digital communications
blocks (DCBXX). Each PSoC function
block, analog and digital, is pro-
grammed at the functional level. That
means that any of the eight 8-bit PSoC
digital function blocks can be defined
as timers, counters, PWM generators,
or random sequence generators.

The PSoC digital basic blocks can-

not be used to implement UART, I

2

C,

SPI, IR, or CRC functions. PSoC digi-
tal communications blocks only per-
form the aforementioned digital com-
munications functions. These prede-
fined and precharacterized functions
that transform the PSoC function
blocks into digital and analog subsys-
tems are called user modules.

Don’t worry about trying to remem-

ber what does what and what goes
where as far as the PSoC function
blocks and user modules are con-
cerned. The PSoC Designer IDE won’t
let you place a user module in the
incorrect PSoC function block. In
addition, you don’t have to worry
about coding at low levels to get the
PSoC function block and user module
to interoperate. The base driver code
for the predefined PSoC user module
is automatically generated when you
place a user module into a PSoC
function block. An API supports each
user module. The API gives you
access to the PSoC register set and

functions that are associated
with the user module.

As you might imagine, digi-

tal function blocks can be
attached to PSoC I/O pins,
other PSoC digital function
blocks, PSoC clock sources,
and PSoC analog function
blocks. The interconnections
are defined by using the PSoC
Designer IDE. I placed an 8-bit
counter in DBB00 and a 16-bit
counter in PSoC digital basic
blocks DBB10 and DBB11 (see
Photo 1). PSoC Designer auto-
matically places a selected
user module in the next avail-
able function block, so I pur-
posely overrode the PSoC
Designer’s placement automa-

tion and placed the 16-bit counter at
DBB10 and DBB11 to preserve the
DCB02 communications block for use
by communications-oriented user
modules. Refer to the Circuit Cellar
ftp site for additional photos.

After a user module is placed in a

function block, the logical connec-
tions and parameters are defined
(clocking, interrupts, gain, references,
etc.), and any desired inter-function
block data paths and I/O pin connec-
tions are established. Photo 1 looks
pretty busy, but the PSoC user module
placement and connection process is
extremely intuitive. You can click on
the objects to select connections, or
you can make connections by choos-
ing from choices offered in the user
module Parameters window.

The PSoC analog function block

area of the CY8C27443 is composed of
12 PSoC analog blocks arranged in
four columns. Each PSoC analog block
column includes a continuous time
analog block (ACBXX), a switched
capacitor C analog block (ASCXX),
and a switched capacitor D analog
block (ASDXX).

ACBXX PSoC analog blocks are

made up of a rail-to-rail, low
offset/low noise op-amp and include a
register-bit-setting controlled preci-
sion resistor network in the op-amp’s
feedback path. A couple of obvious
uses for the ACBXX analog blocks
include the realization of the program-
mable gain amplifier (PGA) user mod-

Photo 2—

This is where you want to click to your heart’s content. Although it

isn’t shown in this shot, the PSoC Designer IDE provides a list of connect
points and optionally can physically point them out to you. This shot looks busy,
but in reality, it’s all extremely logical. After you click on the muxes and see the
paths change before your eyes you’ll know what I mean.

Photo 3—

The large board with the ZIF socket is called

the YProgrammer board. My YProgrammer is set up for
28-pin DIP packages. There are lands for all of the
PSoC package variants. Directly to the right of the
YProgrammer is the PSoC Pup. The PSoC Pup attach-
es to the ICE Pod, which is directly to the right of the
PSoC Pup, with the bed-of-nails connector.

background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

71

ule and the programmable threshold
comparator user module. Adding a
classic op-amp configuration to a PSoC
design is absolutely “no problem.”

DACs, filters, and ADCs are built

from the switched capacitor analog
blocks, ASCXX and ASDXX. Like the
ACBXX PSoC analog blocks, the
ASCXX and ASDXX analog function
blocks are built around a rail-to-rail,
low-offset, low-noise op-amp. They also
depend on register values to determine
the relative weights of the switched
capacitor arrays that are muxed to the
op-amp’s input and output.

There are four switched capacitor

arrays in each respective set of ASCXX
and ASDXX switched capacitor analog
function blocks. Arrays A, B, and C are
input arrays. Switched
capacitor array F is in the
op-amp feedback path.
The difference in the two
switched capacitor analog
blocks is in how the C
array is configured and
the extended amount of
switching control offered
on the B input array of
the ASDXX analog block.

I placed a quad of PGA

user modules in the
CY8C27443’s analog
block space (see Photo 2).
You can’t click on Photo
2 to see the multiplexer
names and choices, so
let’s work the PSoC ana-
log subsystem from the
top muxes down.

The two topmost eight-

input multiplexers above

the four analog
function block
columns are analog
clock select muxes.
The clock sources
for these muxes
encompass clock
outputs from all
eight of the DBBXX
and DCBXX digital
function blocks.
The next row of
four-input muxes
selects the PSoC
device input I/O
pin that will feed

the PSoC analog
column that the
column’s input
mux’s output is
connected to. From
left to right, the
first and third four-input muxes tie in
odd numbered Port_0 I/O pins. The
second and fourth four-input muxes
bring in the even numbered Port_0
I/O pins. The two center column
inputs have an additional pair of two-
input muxes, which allow the
columns to be connected either to
even or odd numbered Port_0 I/O
pins. The lowest set of four-input
muxes selects a clock source for the
PSoC analog block column it supports.
All of the configuring is done simply by

clicking on the mux and selecting a
PSoC pin, connection, or clock source.

In the Photo 2 example, I connected

the PGA outputs to PSoC Port_0 I/O
pins using the four output buffers.
However, I can also connect the PGA
outputs to other PSoC analog block
inputs instead if my application
demands it. Each column’s analog
blocks have access to the analog out
bus that feeds the column buffers.

Each PSoC analog block column

also has access to a comparator bus

whose outputs can feed
user module inputs in
the digital function block
space. I connected the
first PGA user module
output to the input of
the 12-bit A/D converter
user module below it in
the ASC10 position. The
A/D converter is con-
nected to Comparator0,
which can feed a timer
or counter input in the
digital area if required.

The PGA user mod-

ule’s gain can be set in
the user module
Parameters window or
via the PGA user module
API. The A/D converter
is also controlled by an
API, which allows for
starting, stopping, and

Photo 5—

This configuration (Dawg) is loaded at power-up. I eliminated the

Global Resources and user module Parameter windows so you can get a better
view of the graphical design windows. I named the CY8C27443 pins using a win-
dow in the PSoC Designer IDE. Using that same window, I can select the pin
drive and enable or disable the pin’s interrupt. Clicking on the pin also allows the
global in/out connection of the pin to be set (green vertical bus lines to PSoC I/O
pins), and you can set the pin’s drive and interrupt status.

Photo 6—

This is the analog configuration. Note that the PSoC I/O pin connections to the

global in/out bus did not change. However, because I had to fit some 16-bit counter user
modules into different digital function blocks, I was forced to rely on the other output muxes
(small blue boxes) to attach the new user module configuration to the PSoC I/O pins that are
already attached to the LEDs.

Photo 4—

At this point, I wasn’t really ready to commit

to having a Dawg PCB fabricated. I figured that by
using a solderless breadboard, I could add any periph-
eral stuff I needed as I learned more about the PSoC
system. This was a good idea because I learned that I
could place the PSoC pins in places that allowed me to
keep the wire runs pretty.

background image

72

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

gathering data from the A/D
converter user module.

I think you’ve got the gener-

al idea of how things work
inside a PSoC device and the
role the PSoC Designer plays
in the development process. So,
let’s move on and look at the
actual hardware and firmware
behind the pretty pictures.

DESIGN WITH PSoC

Take my advice, if you want

to learn to use PSoC devices
quickly, buy a PSoC developer
kit. The CY3205-DK PSoC
developer kit I used comes
complete with a PSoC ICE-
4000 and CY8C27xxx pod, a
PSoC programmer board, an
ImageCraft PSoC C compiler,
a PSoC Pup demonstration board, and
everything else necessary to jumpstart
a PSoC application, including a couple
of CY8C27443 samples. My PSoC
development rig, including the USB
dongle for the PSoC ICE-4000, is
shown in Photo 3.

ing through the PSoC exam-
ple applications using the
PSoC ICE and the PSoC Pup.
I’ve done some of both, but I
prefer the hands-on method,
so let’s execute plan B.

The PSoC Pup is the module

with the rectangular 10-LED
module you see in Photo 3.
There’s nothing fancy about
the PSoC Pup circuitry. Its
purpose in life is to attach to
the PSoC emulator pod and
provide the visual results of
your PSoC programming
efforts. The first eight seg-

ments of the LED array are
connected directly to the
CY8C27443’s Port_2 I/O pins.
The remaining segments are
on a couple of pins of the

CY8C27443’s Port_0. The “PSoC Pup
Example Projects” application note
(AN2011) describes the PSoC Pup
hardware and includes a schematic of
the PSoC Pup. The PSoC Pup also
supports a 32-kHz crystal for external-
ly clocking the PSoC emulator pod

There are a couple ways to get

familiar with PSoC design techniques.
You can read through all of the ’Net-
based PSoC information in addition to
the PSoC documentation that comes
with the PSoC development kit. Or,
you can get your hands dirty by work-

Photo 7—

In this shot of the counter configuration, note that the analog stuff is

gone. I simply cranked up the pair of 16-bit counters and used the PSoC’s
microcontroller to kill some time while the counters were agitating the LEDs.
Notice again the different interconnect points between the small blue muxes
and the LED I/O pins.

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

75

and three pins for simple I/O opera-
tions that are called out in the PSoC
programming examples.

I worked the heck out of my PSoC

Pup. I translated the PSoC example
assembler code to PSoC C and success-
fully executed all of the newly convert-
ed code against the PSoC Pup. After I
got the hang of how to do things with
the PSoC, I moved on and worked
through the PSoC Tele-Training cours-
es on Cypress’s web site.

The Tele-Training modules are

prescheduled hands-on teleconference
events that cover PSoC Designer 4.1
and the CY8C27xxx family of devices.
All of the Tele-Training modules are
available for download, so I opted to
fast-track my way into the world of
PSoC design. Basically, I walked
myself through the PSoC Tele-
Training modules in the Florida room.
My goal was to learn enough about
the PSoC architecture to convert all
the Tele-Training module PSoC
assembler code into PSoC C code and
then choose, configure, place, and
interconnect the PSoC user modules
without peeking ahead in the Tele-
Training modules. After I got my fill
of PSoC Pup-py chow, I was placing
user modules, interconnecting PSoC
I/O pins to user modules, flashing
LEDs, and creating DACs and PWMs
like nobody’s business.

There is a wealth of PSoC user mod-

ule information contained within the
PSoC Designer IDE. All of the user
module datasheets, which are just a
click away, include everything you
need to know to deploy the module
and a sample code snippet that you
can cut and paste into your PSoC proj-
ect. I could go on and on about the
features of the PSoC Designer IDE and
how it seamlessly integrates with the
PSoC ICE-4000, but the way to really
learn about the PSoC Designer IDE and
PSoC devices themselves is to click on
everything and assess your options.

I took the time to read the well-

written PSoC Designer IDE user guide
that comes with the PSoC develop-
ment kit. However, I learned just as
much about how to make the PSoC
sing by clicking on the muxes, buses,
I/O pins, function blocks, and inter-
connects in the PSoC Designer IDE.

Listing 1—

All of the function prototypes are generated after you place your user modules and begin the build

process. To use PSoC dynamic reconfiguration, all you have to do is lay down your placements in separate
modules and write the code to load and unload your configurations. In my opinion, the dynamic reconfigura-
tion feature is the PSoC’s strongest point.

#include <m8c.h> // Part-specific constants and macros

#include “PSoCAPI.h” // PSoC API definitions for all user modules

#include “psocdynamic.h”

char counter_msg1[] = “Counter Mode”;

char pwm_msg1[] = “PWM Mode”;

char analog_msg1[] = “Analog Mode”;

void main()

{

int counter_data,analog_counter_data,pwm_counter_data;

char x,y;

while(1)

{

M8C_EnableGInt;

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

// PWM LED driver module dawg

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

PWM_PGA_SetGain(PWM_PGA_G1_00);

PWM_PGA_Start(PWM_PGA_HIGHPOWER);

LCD_Init();

LCD_Start();

LCD_Position(0,1);

LCD_PrString(pwm_msg1);

PWM_GREEN_WritePeriod(255);

PWM_GREEN_WritePulseWidth(128);

PWM_RED_WritePeriod(255);

PWM_RED_WritePulseWidth(10);

PWM_GREEN_Start();

PWM_RED_Start();

PWM_ADC_Start(PWM_ADC_HIGHPOWER);

PWM_ADC_GetSamples(0);

do{

while(PWM_ADC_fIsDataAvailable() == 0);

PWM_ADC_ClearFlag();

pwm_counter_data=PWM_ADC_iGetData();

PWM_RED_WritePulseWidth(pwm_counter_data & 0x00FF);

PWM_GREEN_WritePulseWidth(pwm_counter_data & 0x00FF /2);

}while(pwm_counter_data < 0);

UnloadConfig_dawg();

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

// Counter-driven LED driver module counter

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

LoadConfig_counter();

LCD_Init();

LCD_Start();

LCD_Position(0,1);

LCD_PrString(counter_msg1);

Counter_Grn_WritePeriod(65535);

Counter_Grn_WriteCompareValue(32768);

Counter_Red_WritePeriod(65535);

Counter_Red_WriteCompareValue(16384);

Counter_Grn_Start();

Counter_Red_Start();

counter_data = 0x7FF;

y = 0xFF;

do{

for(x=0;x<0xFF;++x)

—y;

—counter_data;

}while(counter_data);

UnloadConfig_counter();

(Continued)

background image

76

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Experimentation on the firmware

side was just as revealing. After you
place your user modules, all of the C
prototype code is generated and
offered up in the IDE as well. I found
that the user module datasheets and C
prototype code played hand in hand.
I never had to consult the PSoC C
documentation. I decided that it was
time to pack the PSoC Pup away and
create my own PSoC Dawg demon-
stration board.

APPLYING PSoC SKILLS

My PSoC Dawg demo board is really

just a larger version of the PSoC Pup
that is assembled on a large solderless
breadboard. As you can see in Photo 4,
my Dawg has a couple of LEDs, a poten-
tiometer, and a 2 × 16 LCD module.

The CY8C27xxx emulator pod is

attached to the Dawg using a 28-pin
DIP foot, which is keyed to the emu-
lator pod using a 28-pin mask. The
mask is just a guide that allows the
right number of pins to be exposed to
the foot, which in this case is a spe-
cial 28-pin DIP header.

Differing masks allow the CY8C27xxx

emulator pod to support special feet that
emulate TQFP, SOIC, SSOP, and DIP
PSoC packages. If the Dawg were a PCB,
I would have plugged my CY8C27443
emulator pod/mask/foot assembly into
a standard 28-pin DIP socket.

Let’s put together a simple PSoC

device. Using an input voltage, it deter-
mines whether to blink the Dawg’s
LEDs with a couple of 16-bit counter
user modules that get their blink rates

from the incoming voltage or to buzz
the LEDs from the output of a couple of
PWM user modules that also get their
LED blink duty cycle from an A/D con-
verter digital result. In addition, the
mode will be displayed on the Dawg’s
LCD. Just for fun, let’s add another set
of preset 16-bit counters/LED blinkers
that get kicked off between the transi-
tion from 16-bit counter blink mode
and PWM blink mode.

We’ll begin our little PSoC odyssey

by defining and connecting the LED

I/O pins, placing the PGA, placing the
12-bit A/D converter, and placing the
pair of PWM user modules in Photo 5.
The LCD is not a placeable user mod-
ule like the PWM and PGA user mod-
ules. Instead, the LCD user module is
selected and enabled on the port of
your choice using the LCD user mod-
ule Parameters window. As you can
see in Photo 5, I’ve chosen Port_2 as
the LCD I/O port.

Notice that the 12-bit A/D convert-

er user module takes two PSoC digital
function blocks as well as an analog
one. If you refer back to Photo 1,
you’ll see that a 16-bit counter
requires two PSoC digital function
blocks. From the looks of Photo 5,
you can squeeze two more 16-bit
counters into the PSoC mix, but you
still have the PWM/counter transition
16-bit counter to place, and you’re flat
out of digital function blocks. Even if
you could add three 16-bit counters to
the Photo 5 configuration, how would
you multiplex the modules so that they
all use the common set of LED I/O pins
and the output of the PGA/analog-to-
digital converter combination?

No problem. Really. The PSoC can

be dynamically reconfigured. That

Figure 1—

This is almost unnecessary because you can look at the PSoC CY8C27443 layout in the PSoC

Designer IDE and make all of your connections. The LCD circuit you see here can be found in the LCD user mod-
ule datasheet that’s available within the PSoC Designer IDE.

Listing 1—

Continued.

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

// 16-bit Counter LED driver module analog

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

LoadConfig_analog();

PGA_Analog_SetGain(PGA_Analog_G1_00);

PGA_Analog_Start(PGA_Analog_HIGHPOWER);

LCD_Init();

LCD_Start();

LCD_Position(0,1);

LCD_PrString(analog_msg1);

Counter_Analog_WritePeriod(65535);

Counter_Analog_Start();

Counter2_Analog_WritePeriod(65535);

Counter2_Analog_Start();

ADC_Analog_Start(ADC_Analog_HIGHPOWER);

ADC_Analog_GetSamples(0);

do{

while(ADC_Analog_fIsDataAvailable() == 0);

ADC_Analog_ClearFlag();

analog_counter_data=ADC_Analog_iGetData();

Counter_Analog_WriteCompareValue(analog_counter_data);

Counter2_Analog_WriteCompareValue(analog_counter_data / 2);

}while(analog_counter_data > 0);

UnloadConfig_analog();

LoadConfig_dawg();

}

background image

means you can chop your project up
into reconfigurable modules that you
can load and unload on the fly.

Photo 5 is the PWM LED driver

module called Dawg. In Photo 6, the
song remains the same in the PSoC
analog function block area, but I’ve
moved things around in the PSoC digi-
tal block area to accommodate a pair
of 16-bit counters.

Photo 6 is the 16-bit counter/LED

flasher PSoC module called analog.
The preset pair of 16-bit transition
counters is placed in Photo 7 sans the
PGA and 12-bit A/D converter; it’s
called “counter.” Note that in all of
the configurations, the LED I/O
assignments, the PGA 12-bit A/D
converter I/O assignments, and the
LCD I/O assignments are common
across each of the configurations that
employ them.

I’ve been wrapped up in PSoC user

modules for most of this column.
Don’t forget that the PSoC has a
pretty good microcontroller embed-
ded with all of the analog and digital
user module stuff. I used its services

in this application.

The code for my PSoC project is

shown in Listing 1. I used the Global
Resources window in the PSoC
Designer IDE to set the 12-bit A/D
converter to output 0x000 with 2.5 V
(V

CC

/2) in. The PSoC 12-bit A/D con-

verter provides digital results in two’s
complement form. So, all A/D con-
verter inputs above V

CC

/2 provide pos-

itive numbers as A/D converter out-
puts. All A/D converter inputs below
V

CC

/2 result in negative numbers

being output by the A/D converter. By
simply turning the potentiometer
attached to the PSoC PGA_IN pin to
either side of 2.5 V, I can move
between the Dawg configuration and
the analog configuration by way of the
counter configuration.

UNLOADCONFIG_FRED();

Now that you know what a PSoC

device is and how to use it, you may
download the code and project materi-
al for Dawg from the Circuit Cellar
ftp site. Make your PSoC device drive
an LCD and blink LEDS using PSoC

dynamic reconfiguration techniques.
I’ll leave you with the Dawg schemat-
ic and the comfort of knowing that
with PSoC analog stuff isn’t compli-
cated, it’s embedded (see Figure 1).

I

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.

SOURCE

PSoC CY8C27443 Developer kit
Cypress Semiconductor Corp.
(800) 669-0557
www.cypress.com

PROJECT FILES

To download the code and photos, go to
ftp.circuitcellar.com/pub/Circuit_Cellar
/2004/169.

background image

78

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

T

he topic of motor control is like

an onion. No, it isn’t smelly—at least
if you wire things up right. Rather, the
more layers you peel, the more you
find. I originally had planned to cover
the subject in a single column. In retro-
spect, that was a ludicrous goal, consid-
ering it took all of last month’s column
just to describe, and briefly at that,
the various types of electric motors.

Think I’m exaggerating the onion

analogy? I just searched the ’Net for
“motor control” and got 5,480,000
hits! Let’s see, if I click one link per
minute, I can wade through them all
in…hmm…divide by 60, then 24,
then… Oh, let’s just call it an even
10 years! Clearly, a little trimming is
called for.

OK, how about “motor control IC”?

Oh boy, a mere 268,000 hits. That’ll
just take six months. “Motor control
MCU”? That narrows it down nicely to
14,400 hits, or just a week or two.
Better yet, “motor control MCU 8-
bit” comes back with 5000 hits. Guess
what I’m focusing on this month?

cations call for forward and reverse
capability. What’s needed is a way to
dynamically switch the direction of
current flowing through the motor by
switching the polarity of the power
supply connection.

A popular solution uses four transis-

tors—two high-side (12 V) and two
low-side (ground). Both a high- and
low-side transistor are connected to
each of the motor’s terminals, a topol-
ogy known as an H-Bridge. By
enabling diagonally opposing pairs, the
direction of current flow through the
motor can be switched for forward and
reverse operation. Of course, you’ve
got to be careful not to turn on both
high- and low-side transistors to the
same motor terminal at the same
time. That causes a state some tech-
savvy comedians refer to as a fuse test
(i.e., a dead short).

BRIDGE OVER TROUBLED WATTS

One key trend in motor control is

integration, which involves combining
some of, and ultimately all, the func-
tions in a single package. It’s no sur-
prise then to find variations on the
monolithic H-Bridge theme in the
market. Let’s get under the hood with
one of them, Texas Instruments’s
L293 (see Figure 2).

The part combines the driver, gate,

and protection functions (diodes are
included on the L293D) for two full H-
Bridges. For flexibility, it’s organized
as four Half-Bridges, which accommo-
dates various motor types (including
single-directional, bidirectional, and
stepper) and multiple motor connec-
tions. There are two power supply

Motoring (Part 2)

SILICON UPDATE

by Tom Cantrell

BITS TO REVS

The only hope for finishing up is to

keep it simple. And the only hope to
keep it simple is to start that way.

No matter the type of motor, a

motor control subsystem includes cer-
tain basic functions. At the highest
level, a controller is responsible for
generating the voltage level or wave-
forms that determine the motor’s
instantaneous direction, speed, and
torque. On the motor side are the
gates (e.g., power transistors for DC
and triacs for AC) that switch the
power supply on and off, along with
protection devices that isolate the
fragile upstream circuits from the
vagaries of the real world. In between,
you’ll often find another component, a
driver, buffering the connection
between the controller and gate.

Even the simplest example, a single-

direction brush DC motor controller,
has all three parts. Figure 1 shows a
circuit I used long ago to control the
speed of a 12-V DC fan (“PID-Pong
Challenge,” Circuit Cellar, issue 42,
1994). The controller (an MCU) gener-
ates a TTL PWM output with duty
cycle corresponding to the desired
motor voltage. A 50% duty cycle
PWM with a 12-V supply delivers 6 V
to the motor. The 7406 open-collector
driver buffers and level shifts the con-
troller connection to the base of the
2N3055 transistor gate, which carries
power for the fan. A freewheeling diode
offers protection from inductive flyback
and back EMF from the coasting fan.

A fan typically runs only in one

direction, and this circuit works fine
for that. But many, if not most, appli-

Last month, Tom covered the types of electric motors you have at your disposal. Now he
switches gears to the topic of silicon and software.

Motor Control Chips and Software

1N5822

2N3055

GND

FAN-Black

100

FAN-Red

12 V

4

3

7406

1 k

Figure 1—

Even this simple circuit to drive a small 12-V

fan incorporates the basic functions found in all motor
controllers with a driver (7406 inverter with open collec-
tor output), gate (2N3055 power transistor), and protec-
tion (1N5822 diode).

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

79

pins, 5 V for the TTL-compatible
inputs and a higher voltage (up to 36 V)
for the motor.

Read the specs carefully to make

sure you don’t bite off more motor
than the chip can chew. The front
page of the datasheet touts peak out-
put current of up to 2 A per channel,
but that doesn’t mean you can crank
200 W (e.g., 2 A × four channels ×
24 V = 192 W) through a 16-pin DIP.
The fine print later points out that the
continuous rating is only 1 A, and the
peak 2-A output is only tolerable for a
few milliseconds.

In fact, the silicon’s raw power han-

dling capability is further limited by
thermal concerns. Along with the fancy
CPU chips in PCs, I imagine motor-
control applications are right upfront in
the heatsink rep’s Rolodex. As a practi-
cal matter, the L293’s total power dissi-
pation capability is a few watts, and
heatsinking is practically a given. I’m
talking about motors you might find
in a toy train, not the real thing.

I have been experimenting with an

L293, courtesy of a kit from Imagine
Tools, that’s based on a RabbitCore
module and the venerable Z-World C
compiler (see Photo 1). The kit
includes a socket for an L293 H-Bridge
chip along with tutorial instructions
and code examples. One of the demos
controls the direction and speed of a
12-V DC motor using the built-in
push buttons on the evaluation board.
Thanks to the Rabbit chip’s built-in
PWM controller, the software is prac-
tically trivial, although in the real
world, it typically would be upgraded
with enhancements such as ramping

smoothly between speed and
direction changes.

EASY TO BE HARD

Part of the reason you’ll find

268,000 hits for “Motor Control
IC” is that there are zillions of
hard-wired control chips that are
tailored to serve the highest-vol-
ume applications. A good exam-
ple of the breed is ON
Semiconductor’s MC33035,
which comprises a nearly com-
plete motor control subsystem for
brush and brushless DC motors.
As you can see in Figure 3, it

includes a rotor position (i.e., Hall sen-
sor) decoder and three-phase PWM that
handles the details of commutation
along with output drivers for connect-
ing to an external three-phase (BLDC)
or H-Bridge (brush DC).

The part also includes a variety of

protection and safety features called for

by most real-world applications. Cycle-
by-cycle current limiting measures the
motor current (via a sense resistor) each
PWM cycle and turns off the output if
the limit is exceeded. Similarly, under-
voltage lockout shuts down the chip
should any of the power supply or refer-
ence voltages fall below a safe threshold.
The chip can even catch a faulty Hall

M

V

C

1
0

1
0

1

2

7

1
0

4

3

9

8

1
2

3

4

5

6

16

15

14

13
12

10

11

M

1

0

M

V

CC1

Note: The output diodes are internal in L293D.

Figure 2—

The L293 quad H-Bridge from Texas Instruments

does the heavy lifting to allow an MCU to drive one or more
small 12- to 36-V DC motors.

Photo 1—

Controlling a small brush DC or stepper

motor is easy enough with an 8-bit MCU and L293
bridge chip, as the Rabbit-based starter kit from
Imagine Tools demonstrates.

+

20 k

+

20 k

+

20 k

+

40 k

+

40 k

+

25 µA

Rotor

position

decoder

S

A

S

B

S

C

Sensor

Inputs

Forward/

reverse

60°/*120° Select

Output
enable

7

22

3

V

IN

17

V

CC

18

V

C

Reference

regulator

14

V

M

*FAULT

output

2

A

T

Top

drive

outputs

1

B

T

24

C

T

+

Undervoltage

lockout

+

+

Reference

output

8

+

9.1 V

4.5 V

Thermal

shutdown

+

+

Error

amp

11

Noninverted

input

Faster

Error amp out

PWM input

R

T

12

13

PWM

Oscillator

C

T

+

Sink only positive true

logic with hysteresis

10

R

S

Q

Latch

R

S

Q

Latch

+

+

+

+

16

Gnd

BRAKE input

100 mV

15

9

Current sense input
Current sense
Reference input

40 k

Bottom

drive

outputs

21A

B

19 C

B

20 B

B

4

5

6

23

Figure 3—

Dedicated motor control chips like the MC33035 from ON Semiconductor can do it all for simple open-

loop applications, but getting fancier requires adding circuits.

background image

80

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

effect sensor or connection by detecting
flaky encoder output because only six
of the eight possible codes for the three
sensor inputs are valid. There’s also
built-in thermal shutdown for when
the chip gets too hot. A FAULT output
drives an LED or otherwise sounds
the alert should something go awry.

The BRAKE input is an important

safety feature that has unconditional
priority over chip operation. Typically
connected to a kill switch, an internal
pull-up resistor defaults the brake on.
This provides a measure of hardening
against switch or connection problems
(better safe than sorry). When asserted,
the chip not only shuts off the motor,
but also provides active braking by
activating the low-side power transis-
tors, shorting out the back EMF gen-
erated by the coasting motor.

As a generic solution, the specific

control capabilities are limited to direc-
tion and speed. An analog voltage on a
pin connected to the on-chip error
amplifier sets the latter. Simple open-
loop speed control is as easy as connect-
ing a speed dial (i.e., a potentiometer).

Delay manager or speed measure unit (not represented)

Delay
weight

Delay = weight × Zn

Capture Zn

MTIM
Timer

=?

Commute [C]

+

BEMF=0

[Z]

BEMF Zero-crossing detector

TACHO

Int/Ext

Encoder unit

Input detection

MCIA

MCIB

MCIC

MCVREF

Measurement

window

generator

(I)
Current

Voltage
(V)

(I)

(V)

Mode

PWM manager

Phase

U

Phase

MCO5
MCO4

MCO3
MCO2
MCO1

MCO0

U, V, W

Phases

NMCES

OAON bit

+

OAP

OAN

OAZ

MCCFI

ADC

V

DD

R

1

R

2

(V)

(I)

C

R

3

MCPWMV

MCPWMW

12-bit counter

Phase U

Phase V

Phase W

Channel manager

PCN bit

12-bit Three-phase

PWM generator

1

(V)

[Z] : Back EMF zero-crossing event

Z

n

: Time elapsed between two consecutive Z events

[C] : Commutation event

C

n

: Time delayed after Z event to generate C event

(I) : Current mode

(V): Voltage mode

CFAV bit

MCPWMU

MCCREF

Figure 4—

The ST7MC incorporates a motor control subsystem that handles the details of electronic commutation,

including rotor position sensing (via back EMF detection, Hall effect sensors, or a shaft encoder) in hardware.

background image
background image

82

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

However, to enable more sophisticat-

ed closed-loop control, the on-chip error
amp output (which controls the PWM
duty cycle) is brought to a pin that
allows inserting external circuits into
the error amp input and output loop. For
instance, an external frequency-to-volt-
age circuit can turn the Hall effect sen-
sor inputs (i.e., rotor speed) into a
tachometer to generate a speed control
voltage. Similarly, the transition rate on
the error-amp input can be externally
damped to smooth speed changes.

MOTOR MICROS

It’s apparent that a chip like the

MC33035 is fine by itself for simple
open-loop and fixed-speed applica-
tions. But adding more features like
closed-loop control nonlinear accelera-
tion and deceleration profiles, not to
mention a user interface beyond a
couple of switches and LEDs, quickly
boosts the chip count and design com-
plexity. In fact, a likely solution is to
throw in a small MCU to be the brain
to complement the MC33035 brawn.

The other way to approach the prob-

lem is to start adding motor control
features to MCUs. Indeed, judging by
the rash of activity by major MCU
suppliers, that’s where the action is.

What are some of the key features to

look for? Probably most important is a
high-performance multichannel PWM
subsystem that has the frequency, res-
olution, and motor-centric tweaks to

accommodate a range of single-phase
and multiphase (including stepper
motor) applications. Next up is a good
timer subsystem with enough speed
and interrupt smarts to detect rotor
position and perform electronic com-
mutation. You might find input-cap-
ture pins for the typical trio of Hall
effect sensors or specialized logic to
handle an optical shaft encoder.

A multichannel A/D converter is

practically a must for tasks like indi-
vidual phase current measurement,
back EMF detection, temperature
monitoring, analog tachometer or
positioning inputs, and so on. As you
might have guessed, conversion speed
is a key performance parameter con-
sidering the need for multiple sam-

ples per revolution for a fast motor
(10,000-plus rpm).

Reflecting the blue-collar aspects of

the application, high-current I/O (e.g.,
gate driver), extended temperature opera-
tion, and high reliability are things to
look for. Clever programming can go a
long way, but it’s helpful if the MCU
supplier offers plenty of hardware and
software examples to get you started.

On the surface, Microchip’s

PIC18Fxx31 looks little different than
other members of the PIC lineup:
40-MHz (10 MIPS) operation, 8 to 16 KB
of flash memory, 28- to 44-pin pack-
ages, and a seemingly usual collection
of peripherals. But a closer look under
the hood reveals a number of features
that are specifically tailored for
motor control applications.

Everyone knows how a simple PWM

works by outputting a waveform with
a programmable high/low duty cycle.
The main specs are simply the frequen-
cy (how fast the waveform repeats)
and resolution (how finely the duty
cycle can be controlled). Note that
there’s invariably a trade-off between
the two. Higher frequencies have
lower resolution, and the PIC18Fxx31
is no exception. For example, at the
highest possible resolution (14 bits),
frequency tops out at a couple of kilo-
hertz but quickly scales up to tens
and hundreds of kilohertz at lower
resolution (e.g., 312.5 kHz with 7-bit
resolution).

Photo 3—

The latest generation of development tools makes experimenting with various motor settings—Microchip PICDEM MC (

a

)—and even thermal analysis—ST

PractiSPIN (

b

)—an easy point-and-click affair.

Photo 2—

The PICDEM MC evaluation board com-

bines the MCU controller and high-voltage power sec-
tion (notice the clear plastic shield) on a single board.
The two sections are optoisolated, allowing for the safe
connection of a PC and emulator.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

83

Beyond that, the power control PWM

module lives up to its name in many
ways. First, there are four independent
duty cycle generators and up to 8 PWM
pins (depending on package) that can
operate independently or in comple-
mentary pairs. The independent mode
serves multiple motor configurations
and stepper motors while the comple-
mentary mode is ideal for direct connec-
tion to three-phase or H-Bridge circuits.

You might think complementary

mode would be easy to achieve with a
regular PWM by hanging some inverters
externally. But actually it’s not as sim-
ple as that because real-world bridge cir-
cuits prefer a bit of so-called deadband
(i.e., delay) between turning off one side
of the bridge and turning on the other,
which the ’31 accommodates with a
programmable deadband generator.

Another common PWM gotcha is

characterized by glitches that occur
when parameters (e.g., duty cycle) are
updated asynchronously, possibly gen-
erating abnormally long or short
pulses. Not only is each channel of
the ’31 PWM double-buffered, but in
fact the entire PWM has an update
lockout capability that allows for syn-
chronizing multichannel timebase and
duty-cycle changes.

For flexibility, safety, and debug, the

PWM supports a combination of soft-
ware and automatic output override.

As for the timebase and duty cycle,
override outputs can be independent
or synchronized across all channels.
Two generic fault inputs can be
mapped to pins or driven by software
to shut down the PWM. Each fault can
be configured as permanent or cycle-
by-cycle. The former would be suitable
for a catastrophic failure (e.g., panic
stop switch, over-temperature alarm)
because it leaves the PWM disabled
until the software says it’s OK to
restart. By contrast, in cycle-by-cycle

mode (e.g., high current during startup),
the PWM automatically restarts after
the fault signal is removed. There’s also
the option of automatically shutting off
the PWM when a breakpoint is encoun-
tered during software debugging,
which sounds like a wise idea.

Next on the checklist is the motion

feedback module. It enhances the typi-
cal timer subsystem with special
input capture modes using three pins
to detect rotor position using the typi-
cal triad of Hall effect sensors.

Photo 4—

The UQM Technologies SMG15 42-V BLDC

motor has the brains and brawn (notably 500-plus-pound-
feet peak torque) to do it all: forward and reverse propul-
sion, starter motor, and regenerative braking. According to
UQM, sophisticated control electronics and algorithms
alone improve power and efficiency by nearly 10%.

background image

84

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

SOURCES

Rabbit-based starter kit
Imagine Tools
www.imaginetools.com

PIC18Fxx31 motor control MCU
Microchip Technology, Inc.
www.microchip.com

MC33035 BLDC control IC
ON Semiconductor
www.onsemi.com

SMG15 42-V BLDC motor
UQM Technologies, Inc.
www.uqm.com

ST7MC motor control MCU and
development tools
STMicroelctronics
www.st.com

L293 Quad H-Bridge
Texas Instruments
www.ti.com

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.

relatively low speed. After back EMF
zero crossing is detected, the delay man-
ager triggers the next commutation
event. It also schedules a blanking win-
dow to allow the deenergized winding to
demagnetize and the voltage to settle
before back EMF sampling is reenabled.

STUDENT DRIVER

The chips are great, but I’m espe-

cially impressed by the final piece of
the puzzle, the development tools and
support, that come with them. Both
Microchip and STMicroelctronics offer
powerful evaluation setups at relatively
low prices. Yes, they cost more than
the typical mini-me 8-bit MCU demo
board, but they’re a bargain compared
to the alternative of home-brewing a
motor control design from scratch.

The ST7MC-KIT/BLDC is a bit

expensive ($695), likely because it
comprises multiple boards. A USB
emulator connects to the PC while an
ST7MC reference design board drives
a variety of motors (i.e., AC induc-
tion, brushed, and brushless DC) from
12 to 300 V at up to 1,000 W. Fooling
around with a 12-V toy motor is one
thing, but dealing with 100-plus-V big
iron can be scary, so a third board iso-
lates the PC and emulator from the
high-voltage stuff. Meanwhile, the PIC-
DEM MC development board is similar
in its overall capabilities, although
the packaging is a little different, with
the motor control, high voltage, and
isolation circuits combined on a sin-
gle board (see Photo 2). It costs less,
but doesn’t come with an emulator.

The hardware tools are helpful, but

it’s really the software that makes get-
ting up to speed, literally, easier than
ever. Both kits come with plenty of
examples and software libraries easily
adapted to a particular motor and appli-
cation. Better yet, the packages also
come with fancy GUIs. Besides deliver-
ing instant gratification (connect a
motor and go), they ease the entire
development process with, for exam-
ple, point and click settings for various
motor and system parameters and
even thermal analysis (see Photo 3).

MOTOR VOTER

Sign me up as one of the true believers.

Look how far we’ve come in 200 years,

Alternatively, the module can be con-
figured as a quadrature encoder inter-
face to keep track of rotor position,
velocity, and direction using a three-
output (index, phase A, phase B) shaft
encoder. In either mode, optional
front-end filtering suppresses noise
glitches by multisampling the inputs.

Similarly, the nine-channel A/D con-

verter is not only fast at 200 kHz, but
it’s upgraded with motor-control
specifics. For instance, it can handle the
simultaneous sampling of two channels
as called for by power factor correction
and certain motor control algorithms
that must measure voltage and current
at exactly the same time. Furthermore,
the A/D converter is able to work close-
ly in concert with both the PWM and
motion feedback module thanks to mod-
ule-specific conversion trigger options.

Motor control can be a harsh, unfor-

giving environment, so the ’31’s
extended temperature operation (–40°
to 85°C), watchdog timer, failsafe dual
(internal/external) oscillator, and long-
life flash memory (100 years data
retention) are more than just frills.

BACK EMF STABBER

The ST7MC is another chip that

caught my eye. It’s a midrange, 8-bit
flash memory MCU with motor-centric
features similar to the PIC18F33xx in
most respects. However, the ST7 goes
somewhat further with a complete on-
chip motor controller (MTC) subsystem
that handles a lot of the low-level
details independently, cutting develop-
ment time and preserving MCU MIPS
and flash memory for the application
software (see Figure 4).

In particular, the MTC integrates

function blocks (input detection, delay
manager, channel control, and PWMs)
that work together to completely han-
dle electronic commutation for AC
induction and brushless DC motors.
Along with the expected Hall effect sen-
sor and shaft encoder inputs for rotor
position sensing, the MTC is especially
suitable for sensorless designs thanks
to built-in back EMF detection.

An on-chip analog comparator mon-

itors back EMF from the unenergized
winding. Filtering and sensitivity are
optimized to detect low back EMF,
allowing for sensorless operation at a

from the experiments of Ampere and
Faraday to shipping millions of electric
motors per day. But I think the fun is
just beginning. Interest in conservation
and the smarts provided by silicon are
coming together in a whirlwind
romance and the sparks are going to fly.

But maybe there will be less sparks

than ever thanks to the growth in
brushless motor applications that the
ever smarter and lower-cost motor con-
trol chips will enable. Notably, hybrid
vehicles are really going to drive brush-
less DC motor technology onto Main
Street (see Photo 4). And don’t think
it’ll just be greens behind the wheel. I
wonder how long will it be before hot
rodders catch on to the ramifications
of a DC motors flat torque curve.

When racing for pinks, the question

to ask may be “How many watts (or
for that matter, bits and MIPS) you got
under the hood of that thing?” Who
needs turbos, nitrous, headers, and all
the rest? Just buy some real big capaci-
tors and a super-smart chip! Besides,
it’s a lot easier to fix a blown fuse
than a blown head gasket. May the
electromotive force be with you!

I

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

85

IDEA BOX

THE

DIRECTORY

OF

PRODUCTS AND

SERVICES

AD FORMAT

: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.

ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2

″″ ××

3

″″

FORMAT

. Call for current rate and deadline information. Send your disk and digital submis-

sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail kc@circuitcellar.com. For more information call Sean Donnelly at (860) 872-3064.

The Suppliers Directory at www.circuitcellar.com/suppliers_dir/

is your guide to a variety of engineering products and services.

background image

86

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

87

background image

88

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

89

background image

90

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

91

background image

92

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 169 August 2004

93

background image

Single-Board Logic Analyzer

Supervisory Control and Data Acquisition (Part 1): CANPipe Basics

Pseudo-Random Noise Generator: Theory and Applications

DMX-512 Control: Build a USB-to-DMX512 Converter

The Engineer’s Alarm Clock: Design a PIC-Based Lamp Controller

Multilab: A Z8 Encore!-Based Multipurpose Test Instrument

SPWM Calculator

APPLIED PCs

Uncomplicated Wireless Networking

FROM THE BENCH

Create a USB Hybrid Hub

SILICON UPDATE

A Simple Plan

94

Issue 169 August 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

89

Abacom Technologies

93

All Electronics Corp.

92

Amazon Electronics

51

AP Circuits

72

APEC

89

Ash Ware, Inc.

7

Atmel

91

Bagotronix, Inc.

51

Bellin Dynamic Systems, Inc.

42

Belsoft

73

Beta Layout Ltd.

47

Bitscope Designs

41

CadSoft Computer, Inc.

87

Carl’s Electronics

31, 88

CCS-Custom Computer Services

92

Conitec

85

Cyberpak Co.

9

Cypress Contest

1

Cypress MicroSystems

65

CWAV

91

DataRescue

85

Decade Engineering

85

Digital Creation Labs Inc.

85

DLP Design

56

Earth Computer Technologies

90

EE Tools

(Electronic Engineering Tools)

89

eMicros

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page

54

EMAC, Inc.

91

Embedded Creations

45

Entrelogic Corporation

81

ESC Boston

25

ExpressPCB

85

FDI-Future Designs, Inc.

87

Fitzhugh & Waggoner, Inc.

92

Front Panel Express

86

Hagstrom Electronics

40

HI-TECH Software, LLC

13

Holmate Semiconductor, Inc.

80

ICOP Technology, Inc.

89

IMAGEcraft

58

Imagine Tools

86

Intec Automation, Inc

93

Integrated Knowledge Systems

91

Intrepid Control Systems

90

Intronics, Inc.

57

Jameco

64, 86

JK microsystems, Inc.

46

JR Kerr Automation & Engineering

12

Kg Systems, Inc.

46

LabJack Corp.

46

Lakeview Research

89

Lawicel HB

55

Lemos International

2

Link Instruments

83

Linx Technologies

33

MaxStream

88

MCC (Micro Computer Control)

89

Megatel Computer Corp.

90

Microcontroller Services

66

Micromint

93

Micro Digital

92

microEngineering Labs, Inc.

88

MJS Consulting

90

Mosaic Industries, Inc.

17

Mouser Electronics

95

MVS

86

Mylydia, Inc.

C2

NetBurner

88

OKW Electronics, Inc.

92

Ontrak Control Systems

64

PCB123

74

PCB Design Conf. East

12

PCBexpress

87

PCB Fab Express

C4, 32 Parallax, Inc.

85

Phytec America LLC

87

Phyton, Inc.

90

Picofab, Inc.

93

Pulsar, Inc.

88

Quality Kits & Devices

86

Quantum Composers, Inc.

Page

Page

Page

87

R2 Controls

39

R4 Systems, Inc.

21

Rabbit Semiconductor

89

Radiotronix

56

Remote Processing

93

Rogue Robotics Corp.

77

Saelig

3

Scott Edwards Electronics, Inc.

88

Sealevel Systems

5

Sierra Proto Express

19

Silicon Laboraties, Inc.

91

Softools

90

TAL Technologies

C3

Tech Tools

26, 27

Technologic Systems

87

Technological Arts

90

Tern, Inc.

86

Trace Systems, Inc.

91

Triangle Research Int’l, Inc.

54

Trilogy Design

93

Weeder Technologies

91

Zanthic Technologies, Inc.

11

Z-World

October Issue 171

Deadlines

Space Close: August 10

Material Due Date: August 18

Theme:

Data Acquisition

Bonus Distribution:

CTIA Wireless I.T. & Entertainment

PCB Design Conf. East

RoboNexus

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 September Issue 170

Theme: Signal Processing

background image
background image

steve.ciarcia@circuitcellar.com

CIRCUIT CELLAR

®

www.circuitcellar.com

by Steve Ciarcia, Founder and Editorial Director

PRIORITY INTERRUPT

P

rivacy laws in the U.S. border on being a joke. They are a piecemeal collection of individual laws that generally cover only things like credit

reports and some medical and financial records. The joke is that the lack of comprehensive national laws results in situations that keep your video
rentals secret but make every roadway toll you go through, every meal you charge, and every cell tower you pass available in some unprotected
database for the entire world to view. Life in the U.S. is virtually an open book, and most of it is online.

Recently, I was at a party and this subject came up. I related the story about how I had just bought a car and how an insurance quote was con-

ducted. Interestingly, the insurance agent (whom I had never met before) had asked me absolutely no questions while determining my insurance
qualifications. Within the few seconds it took to call up a data-mining information service, she had a complete cyber dossier on me. The speeding
ticket I got three years ago (and what guy who owns a Porsche and a BMW doesn’t have one?) didn’t result in any points, so it wouldn’t hurt me.
My credit rating is so good that they would give me a 20% discount. I own my home and have no children under 25, so that was good. I have three
other cars (with a different insurance carrier), and she said I was eligible for a multi-car discount if I transferred the other three to them. And, because
they determined I was still eligible for life insurance, and that my medical insurance premium payments weren’t out of whack with the norm, I was
not considered an “inordinate risk” customer. They found all this in just a couple minutes. Well, at least they didn’t know I had just rented Pirates of
the Caribbean
. That would remain a secret.

My experience wasn’t convincing enough for one rather loud individual at the party, so I decided to demonstrate a more personal example for

him. Without using any of the paid data-mining services, I simply signed on to a web site where I knew his hometown tax department posts their
property grand list. I entered his residential address and up popped a picture of his house, all the financial details of what he paid for it, and the cur-
rent assessment and taxes, along with a complete list of all the building permits, violations, and property changes for the life of his house. He turned
absolutely white when the next page showed a floor plan of his 3,700-square-foot Dutch colonial with a notation that he still had an outstanding over-
due tax bill. I smiled and said, “Hey, George, I thought you always told us your house was over 4,000 square feet?”

It’s been suggested that every American is in at least 50 databases and that together they describe an entire lifetime of activity. Worse yet, if doc-

umented past deeds don’t indicate enough despotic jeopardy for you, then consider what happens in the future when all your real-time activities are
logged into more databases. Presently, there are no laws that cover the plethora of location-tracking devices like cell phones, RFID tags, traffic cams,
etc. The old joke about your life being an open book has suddenly taken on new meaning.

If I have a fear, it isn’t that we are in a database, it’s that the information it contains isn’t accurate. Present databases are primarily records of

past financial and transactional activities. People generally have paper records of these events, and, if disputed, the database can be corrected by
showing alternate evidence. Today’s massive computer systems make collecting the GPS location for every person with a cell phone, every car with
an EZ Pass, and every sweater with an RFID tag a potential reality. When you check in at the airport and they run your ID, they can easily see that
you haven’t been to any embargoed locations or bought any suspect items. But, what if one of those records has a few bad bits? Or what if your
stolen cell phone went someplace you didn’t? Do you get put on a transport to Guantanamo Bay?

Let’s face it, the technology is slick and its applications are intriguing. The ability to monitor if your son is actually following house rules when he

borrows the family car seems to easily justify GPS tracking. However, do you really want to have high-priced clothing ads blasted in your face when
you walk into a department store that has just scanned your clothing RFID tags to determine your spending profile? Or, do you want to be completely
ignored by a car dealer who can see you’ve been to six other dealerships and are obviously “just looking around”?

Regardless of how slick the applications, people openly admit that they are concerned about privacy. Product design engineers should be aware

that revelations like the hidden “spyware” that doomed many software products can happen to hardware products as well. For example, the sudden
publicity that the one million RFID tags just shipped to Wal-Mart also login at every ATM and gas pump in the country despite claims they were
erased at the checkout register would be a product kiss of death. The potential applications and associated glitches could be infinite. Until there are
rules on how this information is collected, verified, and used, I think engineers have an obligation to design location and ID-tracking technology to
include a genuine off switch.

Cyber Dossiers

PPRRIIOORRIITTYY IINNTTEERRRRUUPPTT

96

Issue 169 August 2004

background image
background image

Wyszukiwarka

Podobne podstrony:

więcej podobnych podstron