circuit cellar2003 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)

#157 August 2003

WIRELESS COMMUNICATIONS

WiFi SniFi

Palm-Controlled Telescope

Wireless Outdoor Light Control

USB-CAN Interface

background image
background image

Use the Cypress PSoC

instead of an MCU for

more flexibility, fewer parts and lower cost.

The versatile PSoC

Programmable System-on-Chip

is

the world’s first mixed signal array that lets you custom
configure the exact functions you need. And it has an
on-chip controller to manage your application and run
the configuration process.

Graphically select, place, and interconnect
the peripherals you want and adapt the
architecture with PSoC Designer

software

Dynamically reconfigure a single PSoC
chip multiple times—changing functionality
on the fly in any application

Reduce BOM cost by reducing the number
of external components

MCU

later.

Cypress,

PSoC,

Programmable-System-on-Chip

and

PSoC

Designer

are

trademarks

of

Cypress

Semiconductor

Corporation.

©2002

Cypress

Semiconductor

Corporation.

All

other

Trademarks

are

the

property

of

their

respective

owners.

There are many more blocks to work with—

and thousands of configurations to choose from.

PSoC Designer

software is free for download, with

full-featured emulation hardware starting at $248.

Option #8926

8-bit PWM

Inverting Amplifier

IrDA

Transmitter

11-bit

Delta Sigma A/D

Band Pass Filter

Analog

Comparator

8-bit Counter

8-bit DAC

24-bit Timer

Low Pass Filter

Option #1530

Analog

Comparator

Instrumentation

Amplifier

12-bit

Incremental A/D

Notch Filter

16-bit CRC

Option #625

Analog

Comparator

16-bit PWM

Programmable

Gain Amplifier

Instrumentation

Amplifier

IrDA

Transmitter

11-bit

Delta Sigma A/D

8-bit DAC

12-bit

Incremental A/D

Band Pass Filter

8-bit Counter

Option #4237

CPU

Analog

Comparator

Your Customized Mixed Signal

platform in 60 minutes or less

Build your custom PSoC

with programmable analog

and digital functions from our extensive library.

To learn more about our innovative PSoC solutions

and to enter a drawing to win a PSoC Development

Kit, visit www.cypress.com/ad/mcu

.

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

ireless technology has become such a part of our lives that it’s diffi-

cult to remember what life was like without it. As I was walking into a movie
theater last weekend, I noticed a group of teenagers—each girl on her own
phone (personalized by different colors and ring tones). Remarkable
designs, innovative low-power devices, and, of course, savvy marketing
have helped make wireless technology accessible to nearly everyone.

For the Wireless issue, we found some projects that are sure to pique

the interest of the more sophisticated consumers. But, what’s fun about
simply buying the next gadget? We hope these projects inspire you to want
to build your own.

You’ll want to get started on your own wireless outdoor lighting system

before summer’s over. John Dammeyer combined CAN, RF, and a
PIC12C509 to develop an impressive outdoor lighting scheme (p. 12).
John’s design makes a sensible alternative to bulky wires or solar lamps
that are often dim or unusable after cloudy days.

For those of you who prefer looking to the sky rather than the ground,

we also have an interesting project to enhance your telescope. Steven
Pope devised a way to link his Palm device to his Meade ETX-105 tele-
scope using the Zilog eZ80 microcontroller and Webserver module (p. 20).
The ETX-105 has Meade’s Autostar controller, which enables it to locate
celestial coordinates by compensating for the Earth’s rotation. The only
trouble is that the telescope’s two-line display makes it difficult to use the
system. Although he could attach a laptop, he figured adding bulky wires to
a nighttime activity might be a bad idea. Plus, he had a more inventive solu-
tion: use the Palm device as an interface to a GPS receiver. There was one
last hurdle; he needed a wireless infrared IrDA port for the telescope. That
problem, too, was solved easily enough with the Zilog IrDA development
system.

We also found a project to suit the interests of WiFi fans. When stories

about WiFi started showing up on CNN’s web site last year, it was a sure
sign that the technology has gained mainstream popularity. If you want to
know the literal ins and outs of WiFi, turn to page 50 for Roy Franz’s arti-
cle. Using an 8-bit microcontroller (NEC’s µPD78F9418), Roy designed an
application to find and monitor 802.11b wireless networks. The compact,
low-power WiFi SniFi (pronounced “wiffy sniffy”) serves as a network node.
Aside from sniffing out wireless networks, the WiFi SniFi also displays
frames and responds to pings and ARPs.

These projects are so interesting that I don’t even need savvy market-

ing to draw your attention. From a consumer’s perspective, the next thing I
would like to see wireless is television, so I can get rid of the rat’s nest of
TV, cable box, and VCR (that’s right, despite the rental industry’s insidious
efforts to get me to buy a DVD player by dwindling the VHS selection, I still
use my VCR) cords in my living room. Sanyo and Magis Networks have
developed a wireless TV prototype that sounds promising. Something tells
me that that TV would sell itself without any fancy marketing ploys, too.

4

Issue 157 August 2003

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 © 2001 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks
of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

CHIEF FINANCIAL OFFICER

Jeannette Ciarcia

CUSTOMER SERVICE

Elaine Johnston

ACCOUNTANT

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

Bulk Be Gone

jennifer.huber@circuitcellar.com

TASK MANAGER

background image
background image

6

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

August 2003: Wireless Communications

12

Wireless CAN Yard Lamp Control

John Dammeyer

20

Palm-Enabled Telescope

Steven Pope

28

Build Your Own Four-Function Calculator

Daniel Ramirez
Mad Dash for Flash Cash Contest Entry

44

Flexible USB-CAN Bridge

Craig Beiferman
Mad Dash for Flash Cash First Prize Winner

50

The WiFi SniFi

Sniffing In and Out of Wireless Networks
Roy Franz

40

ABOVE THE GROUND PLANE

IR Sensing

Ed Nisley

60

FROM THE BENCH

Spotlight on the Renesas H8 Family

Hitachi and Mitsubishi Market MCUs for Embedded Systems
Jeff Bachiochi

4

TASK MANAGER
Bulk Be Gone

Jennifer Huber

8

NEW PRODUCT NEWS

edited by

John Gorsky

11

TEST YOUR EQ

edited by

David Tweed

94

INDEX OF ADVERTISERS

September Preview

96

PRIORITY INTERRUPT
Contest Zest

Steve Ciarcia

70

APPLIED PCs

Mission Possible: Achieve Cheap USB Connectivity

Fred Eady

78

SILICON UPDATE

Switch Hitter

Tom Cantrell

FEATURES

COLUMNS

DEPARTMENTS

background image

Check out AVR today at www.atmel.com/ad/fastavr

Introducing the Atmel AVR

®

. An 8-bit MCU that

can help you beat the pants off your competition.

AVR is a RISC CPU running single cycle instructions.

With its rich, CISC-like instruction set and 32 working registers,

it has very high code density and searingly fast execution–up to
16 MIPS. That’s 12 times faster than conventional 8-bit micros.
We like to think of it as 16-bit performance at an 8-bit price.

With up to 128 Kbytes of programmable Flash and EEPROM,

AVR is not only up to 12 times faster than the MCU you’re using
now. It’s probably 12 times smarter, too.

And when you consider that it can help slash months off your

development schedule and save thousands of dollars in project
cost, it could make you look pretty smart, too.

AVR comes in a wide range of package and performance

options covering a huge number of consumer and industrial
applications. And it’s supported by some of the best development
tools in the business.

So get your project started right. Check out AVR today at

www.atmel.com/ad/fastavr. Then register to qualify for your free
evaluation kit and bumper sticker. And get ready to take on the world.

Our AVR microcontroller is
probably 12 times faster than
the one you’re using now.

(It’s also smarter.)

AVR 8-bit RISC Microcontrollers

Memory Configurations (Bytes)

Debug and

Processor

Package

Flash

EEPROM

RAM

Development Tools

tinyAVR

8-32 pin

1-2K

up to128

up to128

Available Now

low power AVR

8-44 pin

1-8K

up to 512

up to1K

Available Now

megaAVR®

32-64 pin

8-128K

up to 4K

up to 4K

Available Now

© 2002 Atmel Corporation. Atmel and the Atmel logo are registered trademarks of Atmel Corporation.

R

background image

8

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Edited by John Gorsky

IR TO RS-232 CONVERTER

The IR232 is an infrared-to-RS-232 converter that is

based on the Sony SIRCS protocol of 12-bit control
codes. The IR232 not only sends and receives control
codes in one of two binary modes, but it also can be
configured to send predefined character strings to the
serial port when specified infrared control codes are
received. This mode allows it to act as a host to any
slave device that can accept RS-232 commands.

The IR232 printed circuit board assembly contains a

40-kHz infrared receiver module, a high-power

infrared LED, and a visible LED for confirmation of
transmissions. It has a true RS-232 interface with a
DE9 connector that matches the pinout on PC-com-
patible RS-232 ports, and can communicate at speeds
up to 19,200 bps.

Its on-board 5-V power supply can operate from a

wide range of input voltages provided through a pin-
type power jack, and the 5-V supply is available on
pin 9 of the DE9 connector to power auxiliary devices.

The IR232 is available as a complete circuit board

assembly or in an optional ABS plastic enclosure with
infrared window. The circuit board is 2.25

× 2.25

×

0.75

, while the enclosure is 2.6

× 2.6

× 1.1

.

A wall block power supply, an RS-232 cable for con-

nection to PC-compatible computer during setup, and
terminal emulation software for the PC are included.

The IR232 costs $69, and the enclosure is available

for $10.

IndustroLogic
(636) 723-4000
www.industrologic.com

300- TO 450-MHZ TRANSMITTER IN SOT23 PACKAGE

The MAX1472 is a VHF/UHF PLL-based ASK transmitter

housed in a tiny 3 mm × 3 mm 8-pin SOT23 package. The
transmitter is perfect for low-cost, high-volume applications
where space is critical, such as security products and remote
sensors operating in the 300- to 450-MHz band. The
MAX1472 runs directly from a lithium cell and operates
down to 2.1 V, consuming only 100 nA of current in Standby
mode. During transmission, the MAX1472 can output –10 to
10 dBm of power into a 50-

load. For a 10-dBm power level,

the MAX1472 consumes 5.5 mA of current at 315 MHz when
using a 50% duty cycle encoding scheme, such as
Manchester. Current consumption drops to 3 mA at 0 dBm
output. The part can accept data rates up to 100 kbps.

After the MAX1472’s ENABLE pin is activated, it takes

only 250 ms for the device’s PLL and crystal to settle so the
device is available to transmit. The MAX1472 accepts crystal
frequencies between 9 and 15 MHz.

The MAX1472 uses a crystal-based PLL, so most of the

problems of an LC- or SAW-based transmitter are eliminated.
The inherent accuracy of the crystal frequency allows for a
narrow IF bandwidth in the receiver to improve system sensi-
tivity. With a receiver like the MAX1470 or MAX1473, a 9-
dB improvement in sensitivity is possible by narrowing the IF
bandwidth from 600
to 50 kHz. Improved
sensitivity translates
directly to greater
range or more reliable
transmissions for your
product.

Prices start at $1.25

in 1000-piece quanti-
ties. An evaluation kit
for the MAX1472 is
available directly from
Maxim and other
authorized distributors.

Maxim Integrated Products
(408) 737-7600
www.maxim-ic.com

NEW PRODUCT NEWS

NEW TCVCXO

The FOX923E is a new temperature-compensated, volt-

age-controlled crystal oscillator (TCVCXO) that measures
only 3.2 mm × 2.5 mm × 1.2 mm, which is half the length
of previous models. The significantly reduced footprint and
competitive pricing makes the oscillator
ideal for applications where size and cost are
critical, such as in the portable, handheld,
and wireless markets.

The frequency range of the FOX923E is 13

to 26 MHz, with a supply voltage range of
2.85 to 3.15 V and an initial frequency toler-
ance of –0.5 to 0.5 ppm at 25° ±2°C.
Standard operating temperature is –20° to

75°C. The new TCVCXO’s frequency stability is –2.5 to
2.5 ppm over the temperature range and –0.2 to 0.2 ppm
over the supply voltage change of 3.0 V ±5%. Pullability

is ±5 to ±15 ppm at a control voltage of
1.5 ±1 V and input current is 2 mA at 3.0 V
(25°C).

Pricing for the FOX923E with a stability

of ±2.5 ppm and a frequency of 26 MHz
starts at $1.99 in 10,000-piece quantities.

Fox Electronics
(888) 438-2369
www.foxonline.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

9

EMBEDDED WIRELESS COMMUNICATION MODULES

The XE900M second-generation Smart Transceiver and

the XE924M Base Access Point add a number of perform-
ance and feature enhancements to their predecessors. The
XE900M and XE924M provide a low-cost and convenient
solution to collecting data wirelessly from up to 128 dis-
crete nodes located within a 150

(indoor) radius.

The XE900M Smart Transceiver combines a microcon-

troller and 900-MHz transceiver in a miniature, dual-in-
line package. It can communicate with another Smart
Transceiver or with the XE924M Base Access Point to cre-
ate a data collection network. The count-off function has
been enhanced to enable the network hub to quickly check
the status of the up to 128 network nodes.

The XE900M is also capabable of communicating using

up to 126 carrier frequencies within the 900-MHz ISM
band. The availability of multiple channels reduces inter-
ference problems by permitting a change in the communi-
cation channel if noise levels affect data throughput.
Multiple frequency channels also permit the network to
include more than one Base Access Point. Multiple Base
Access Points operating on different frequencies can
extend both the distance and number of nodes within the
network. The Sensor-On-Air function allows two analog
inputs and four digital I/O lines to be monitored and/or
manipulated by the Smart Transceiver’s communication
controller. Nodes can be easily added to the Base Access
network without any additional hardware installation
other than the installation of an XE900M Smart
Transceiver into the new equipment.

The XE924M Base Access Point combines a 900-MHz

transceiver and a communication controller housed in a
miniature, dual-in-line package. The XE924M eliminates
dial-up hardware redundancy, and therefore reduces both
the initial installation cost and continuing operating costs.
Agency approval is simplified because the integration
modem includes transferable Part 68 Approval and is a UL-
recognized component. The 900-MHz transceiver complies
with FCC Part 15 rules.

The unit price of the XE900M Smart Transceiver is $39,

and the XE924M Base Access Point is $59 in OEM vol-
umes.

Xecom, Inc.
(408) 942-2200
www.xecom.com

SOLUTION FOR SHORT-RANGE RF APPLICATIONS

A complete system solution for short-range, unidirec-

tional RF communication consists of three microcon-
trollers with integrated transmitters and two receivers.
Several products supporting frequency bands ranging from
260 to 930 MHz are now available. By combining the
rfPIC12F675 microcontroller/transmitter with either the
rfRXD0420 receiver or rfRXD0920 receiver, users can easi-
ly create a wireless unidirectional communication link for
embedded-control applications. The receivers also can be
combined with rfPIC devices and KEELOQ encoders to
create remote sense and control applications.

Available in a 32-pin low-profile quad-flat pack (LQFP),

the rfRXD0420 and rfRXD0920 single-conversion super-
heterodyne UHF RF receivers support frequency bands of
300 to 450 MHz and 850 to 930 MHz, respectively. The
devices offer a maximum data rate of 80 kbps, a standby
supply current of 100 nA, and operate over a voltage range
of 2.5 to 5.5 V. The active supply currents for the
rfRXD0420 is 6.5 to 8.2 mA depending on the low-noise
amplifier (LNA) setting, and 7.5 to 9.2 mA for the
rfRXD0920.

The rfPIC12F675 is a 20-pin microcontroller that feature

an integrated UHF RF transmitter. Output power for the
transmitter section is specified at 6 dBm for increased
range, and it is available in three frequency ranges: 260 to
350 MHz (rfPIC12F675K), 390 to 450 MHz (rfPIC12F675F),
and 850 to 930 MHz (rfPIC12F675H) with a maximum
data rate of 40 kbps. A standby supply current of 100 nA
and operating voltage range of 2 to 5.5 V make the device
suitable for low-power battery-operated applications. The
microcontroller features a 14-bit instruction set with
1.8 KB of flash program memory, 64 bytes of RAM, and
128 bytes of EEPROM for nonvolatile storage. Additional
features include an analog comparator and four channels of
10-bit ADC, making it easy to interface to a sensor for
wireless sensor applications.

Pricing in 10,000-unit quantities is $2.55 each for the

rfRXD0420 and rfRXD0920, and $2.03 for the rfPIC12F675.

Microchip Technology, Inc.
(408) 792-7200
www.microchip.com

NEW PRODUCT NEWS

background image

10

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

EMBEDDED COMPUTER HOOKS INTO WIRELESS NETWORKS

The SBC1390 is a powerful controller in a PC/104 foot-

print that will communicate with other computers in a
wireless network. In addition to PC-compatible features—
such as four serial ports, three timer/counters, and two
cascaded interrupt controllers—the new model can also
include an on-board PC card interface that accepts a WiFi
(IEEE 802.11b) wireless Ethernet card.

In addition to the wireless network capability, the

SBC1390 has other features that make it a full-blown
embedded PC. The SBC1390 is
implemented with the Intel
386EX processor, which offers
speeds of 25 or 33 MHz. With
up to 32 MB of SDRAM, a
CompactFlash connector, a syn-
chronous serial port, a watchdog
timer, and AT-compatibility,
high-performance control sys-
tems can be developed as single-
board solutions. If needed, I/O
expansion can be added to the
SBC1390 through PC/104 cards.
In its stack-through version, the
SBC1390 is ideal for plugging
into a custom OEM I/O card.

The CompactFlash connector can accept flash memory

cards from 16 MB to 1 GB in size. The unit comes
installed with a ready-to-run firmware system. This
firmware includes a complete industrial BIOS, board setup
screens, application download utilities, and a DOS-compat-
ible operating system that boots immediately upon power-
up. Alternatively, the board may be configured to boot 32-
bit operating systems.

The following are options: a PC card interface, a WiFi

PC card, CompactFlash,
increased DRAM, and an
enhanced accuracy real-time
clock. An industrial version
with –40° to 85°C operation is
also available.

The basic SBC1390, with

16 MB of DRAM and 1 MB of
flash memory , costs $315. A
free development kit is provided
that includes cables, sample soft-
ware, and full documentation.

Micro/sys, Inc.
(818) 244-4600
www.embeddedsys.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

11

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 3

—A simple electronic combination

lock has four toggle switches, each of which
may be either up or down. One of the switches
is disconnected and has no effect on the lock,
but you don’t know which one. What is the
smallest set of combinations you can devise that
is guaranteed to open the lock?

Contributed by Eddie Insam

Problem 4

—If two of the four switches are

known to be nonfunctional, how many combina-
tions must be tried in order to open the lock?

Contributed by Eddie Insam

Edited by David Tweed

Problem 1

—Consider the logic expression

Y = A.B.C! + B.C + C.A!. This is called the sum of
products (SOP) notation. The normal way to
implement it would be to use AND, OR, and NOT
gates. But it is sometimes required to implement
such expressions using only NAND or NOR gates.
Explain how would you implement it using only
NAND gates. The aim here is to guess the NAND
gate structure required to implement the expres-
sion by simply looking at the expression with no
calculations involved.

Contributed by Naveen PN

Problem 2

—What 1-bit changes in the following

circuit may cause glitches?

Contributed by Naveen PN

A!

C!

A!

C

F

A

B

B!

background image

were a number of wireless bridge
devices on the market, there wasn’t a
wireless CAN network. One year later, I
had a wireless CAN system up and run-
ning, as well as a fairly powerful activ-
ity board for evaluation and testing.

At that point, I started looking for

problems to fit my solution. I discov-
ered that the need for a true peer-to-peer
type of system was minimal. Many con-
trol systems that use CAN operate in
master/slave mode and require at least
one master at some point during the life
of the system to get things going.

Wireless systems in the Industrial/

Scientific/Medical (ISM) bands suffer
from low-range, fading, and multipath
interference. Everyone seems to want

an extra 50 m more than possible
when transmitting within MOT or
FCC power emissions regulations. And
yet, tying in a garden path lighting sys-
tem with a wireless security system
seemed like an appropriate way to use
a peer-to-peer wireless network.

Note that my yard is large enough that

there are locations where RF modules
cannot see each other. Even a centrally
located master wouldn’t work because of
the trees and topography, which would
block the line of sight for the signals.

CAN BASICS

The CAN protocol uses carrier sense

multiple access with collision recovery
(CSMA/CR), which allows multiple
devices to access the bus at the same
time. Thus, the bus must be able to
handle two or more simultaneously

12

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

I

have a few PIR motion sensor-con-

trolled flood lamps that can light up a
driveway when a warm body is within
range. The lamps work well, but they’re
often triggered by false signals such as
passing cars and small animals. They’re
also extremely bright, which is useful
on some occasions but detrimental on
others. They can actually impair my
vision when I’m walking the dog.

Alternatives to flood-lamp lights are

small 12- and 24-V yard lights, some
of which are solar-powered LED units
that recharge during the day. However,
if you experience a few cloudy days,
the solar-charged lights become non-
operational. In addition, low-voltage
systems and solar-powered LED lamps
are dim, so they’re only useful after
my eyes have adapted to the darkness.

After I thought things over, I decided

that I need low-voltage garden lights that
use more than 7 W, generate adequate
lighting, and consume current only when
necessary. Ideally, the lights should be
able to sense a person’s presence, dis-
creetly light the path without impairing
anyone’s vision, and shut down when
the person leaves the vicinity.

PIR-based flood lamps with low-

wattage bulbs would solve the problem,
but they can be troublesome: unless you
open your curtains and look outside, you
may not notice a visitor or intruder. If
possible, such a system should also act
as a security system capable of notifying
you when someone enters your property.

One shortcoming of mine is that if I

can find a complicated way of doing

Wireless CAN Yard Lamp Control

In addition to providing a sense of security from intruders, sensor-controlled yard lamps make
it safer for you to walk on your property after dusk. But they can pose problems, particularly
when a flash triggered by a nocturnal animal awakens you from a dream. Other systems like
solar-powered lights have problems, too. Wouldn’t it be nice to have more control over the
technologies you use? Check out the CANRF module John built for yard lamp control.

something, or somehow involve a
computer in the simplest task, I’ll do
it. I’ve been working with controller
area network (CAN) systems for more
than 10 years, and a peer-to-peer net-
work seems well suited for lamp con-
trol. However, the idea of stringing
low-voltage power cables around my
property, and a second pair for the net-
work, seems like overkill—not to
mention it isn’t nearly as entertaining
as a wireless control system.

When I first designed the CANRF

modules, I didn’t have a specific applica-
tion in mind, although a few of my cus-
tomers were interested and had ideas
for the product. After I had completed a
survey, I discovered that although there

FEATURE ARTICLE

by John Dammeyer

Photo 1—

The module is mounted on a 2.625

× 3.75

metal plate. The battery holder for the four AA cells is
screwed to the bottom, and the antenna is a quarter-
wavelength piece of solid 22-gauge wire. Ultimately, the
unit will be placed in a cast aluminum enclosure with
an external Rubber Ducky antenna. I borrowed the
LED array from another project.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

13

The receiver interface always moni-

tors the signal levels on the bus. The
CAN processor expects to see a domi-
nant when it asserts a dominant; it
anticipates a recessive signal level
when it stops driving the bus. If the
receiver reads a dominant during the
transmission of a recessive, then there
is either an error in its driver or anoth-
er device is asserting a dominant.

The ISO11898 CAN bus is defined by

a pair of signal wires that are held at
2.5 V relative to ground for a recessive
signal. The line labeled CAN_H is
pulled high to a level near 4.5 V, and the
CAN_L signal is pulled low to a level
near 1 V for a dominant level. There are
a number of different types of drivers
targeted at solving various speeds, bus
lengths, and power supply needs. You
should consult the various datasheets
to determine which ones are suitable.

Like Ethernet, the CAN processors

first listen to the bus to determine if it
is available for message transmission. If
the bus appears free, it asserts a domi-
nant start bit and the rest of the header
bits. If another node needs, by chance,
to send a message and the test for the
available bus happens at the same
time, the two messages would collide.

The moment the Ethernet transmit-

ting node detects a signal level that’s
different from what it is transmitting, it

transmitting devices. The major differ-
ence between Ethernet and CAN is
that Ethernet uses collision detection
whereas CAN uses collision recovery.

The terminology for CAN signals is

recessive for a logic high and dominant
for a logic low. Look at it as if all the
nodes are wire ORed together using
open-collector transistors. When a

device wishes to transmit a logic low
(e.g., a start bit), it turns on its transis-
tor, which pulls the common signal line
low (dominant). Turning off the transis-
tor brings the bus idle, which is equiva-
lent to a logic high. Two or more nodes
turning on their transistors would not
damage the others, because the signal is
already pulled down as low as possible.

Figure 1—

The interface to the CANRF module is simple. The processor is marked as a PIC12C509, but you can use a PIC12C508 or PIC12CE674. You can install a 0-

R9

to allow for processor control of the power supply to cause the unit to power down and draw only microamps. Or, remove R9 and connect the A/D channel 0 of the
PIC12CE674 to a temperature sensor via J2.

Listing 1—

The general-purpose I/O line is used as a simple UART with a short start and stop bit identifying

the start of the bitstream. With a storage scope triggering on the rising edge, the 8 data bits are easily
determined. This type of debugging is especially useful for battery-operated projects that cannot keep
the in-circuit debugger active while they sleep. The extra NOPs are there to make the highs and low
symmetrical.

void

ReportByte(int bt @ local1) {

int i @ local2;

GP_BIT = 1;

GP_BIT = 0;

for (i=0; i<8; i++) {

if ( bt < 0 ) {

NOP; NOP;

GP_BIT = 1;

NOP; NOP;NOP;

}

else {

GP_BIT = 0;

NOP; NOP;NOP; NOP;

}

bt <<= 1;

}

NOP; NOP;

GP_BIT = 0;

GP_BIT = 1;

GP_BIT = 0;

}

background image

14

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

that I’ll soon describe in more detail.

Although I said robust, I wasn’t

being totally truthful. CAN devices
have a clever method of ensuring that
defective nodes don’t become babbling
idiots. They have several weighted
error counters that track transmit and
receive errors. To prevent the long
stream of bad messages that can occur
when a low-priority node holds off an
import message from a high-priority
node, an error flag can destroy a bad
message. Too many transmit errors,
and a node’s bus will go off, requiring
intervention from the processor to go
back to active bus activity.

An error flag is a sequence of six

dominant bits that creates a bit stuff
error. The bit-stuffing technique is an
added benefit for RF transmissions. In
order to properly condition the bit-
detection logic inside the RF receiver, a
comparator called a data slicer is condi-
tioned to have the threshold for deter-
mining a one or zero set at 50% of the
signal level. Ideally, there should not be
a long string of ones or zeros, or the
average signal level will drift upwards
or downwards and the data slicer won’t

stops the transmission and
delays (a random period of time)
before trying again. The other
node will do the same. As long
as the delay is different between
the two, both messages will be
subsequently transmitted with-
out a collision. If the bus is
busy, the throughput may be
drastically effected because
numerous nodes collide, detect
the collision, and then retry a
short time later. In the worst
case, all of the nodes are con-
stantly colliding and retrying.

The new 802.11-based wire-

less systems use a collision
arbitration method that enables
them to not only listen for a
cleared bus but also wait a short
time before listening and transmitting.
That goes a long way toward reducing
collisions but can still leave the bus
free for certain periods of time. Note
that 100% utilization is impossible.

CAN implements a collision-recovery

scheme by considering a dominant bit
in the arbitration bits of the header as
higher priority than the recessive bits.
As soon as the CAN processor detects a
dominant where it expects a recessive,
it aborts the rest of the transmission
and switches to Receive mode. After the
current message is complete, the node
will try again. The message still may be
delayed but based only on the relative
priority of the arbitration field.

In place of two wires with drivers cre-

ating dominant and recessive voltage lev-
els, imagine substituting an RF frequen-
cy for a dominant bit and no frequency
for a recessive bit. The bus would be idle
when one isn’t transmitting. A dominant
would occur when the transmitter is on
long enough to be interpreted as a signal
above the RF noise floor. That’s not
unlike the technique that Guglielmo
Marconi used to transmit signals across
the Atlantic Ocean. In radio parlance
it’s called on-off keying (OOK).

By treating the CAN signals as the

simple absence or presence of a radio
frequency carrier, I have a simple and
somewhat robust peer-to-peer network,
because I don’t need a master polling
and waiting for a response. This is espe-
cially important if the master cannot
reach the node, which is a situation

be able to detect a valid signal.

CAN bit stuffing ensures

that there are never more than
5 bits of any polarity. If a string
of 8 zero bits needs to be trans-
mitted, the first five zeros will
be followed by a single high-
level stuff bit and the next
three zeros. If the receiver sees
five zeros in a row, it automati-
cally removes the next oppo-
site-polarity bit, assuming it’s a
stuffed bit. However, if the fol-
lowing bit is still dominant, a
stuff error is flagged.

Bit stuffing helps keep the RF

receiver’s data slicer roughly cen-
tered on the average signal level.
The error flags should destroy
badly formed messages. [1] In the

relatively quiet environment of a CAN
bus transmission line, the occasional
noise spike or burst will have little
effect on overall communication. Errors
reduce the determinism of the individ-
ual messages. An ACK from a node
doesn’t automatically imply that the
intended receiver obtained the message.
All nodes that correctly received the
message issue an ACK.

Another key variable dictating the

range of OOK-based RF systems is the
signal-to-noise ratio (SNR). When no one
is transmitting, the signal level detected
by the receiver is called the noise floor.
It doesn’t matter if the receiver has a
sensitivity of, say, –115 dBm when the
noise floor or background noise is
–70 dBm. However, this often is an
average, and it doesn’t address short
noise spikes above the noise floor that
may fool the receiver into thinking
that a message has begun.

If the CAN receiver section supposes

that a start bit has occurred and then
sees the equivalent of six consecutive
recessive bits (no signal after the noise
pulse), it will think that the message
has a bit-stuff error and transmit an

Listing 2—

The MAPCAN commands can be found in byte 1 of the 8-byte CAN message. Byte 0 is the destina-

tion ID, and bytes 2 through 7 hold command-specific data. In the case of the motion forward command, byte 2
holds the lamp and switch status, while bytes 3 and 4 hold the originator’s ID and the message lifetime.

#define UNIT_STATUS

0x10 //I/O status heartbeat message

#define MOTION_SENSED

0x11 //Motion detected

#define MOTION_STOPPED 0x12 //No motion anymore

#define MOTION_FWD

0x13 //Someone else’s MOTION_SENSED message

Photo 2—

I have a fairly large yard. The nodes are represented by small

bitmap images that are loaded depending on the status of the node. The left-
most node has its switch closed. The other nodes are all turned on. The Delphi
application also responds to mouse clicks on the node images and can send
messages as if they came from that node, which is extremely useful for testing.

background image
background image

16

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

error flag of six dominant bits. Next,
it will increment the transmit-error
counter by eight. This scenario can hap-
pen numerous times until the receive-
error counter reaches 128, at which
point the device becomes error passive.
In other words, it won’t produce domi-
nant, or active, error flags anymore.

The downside is that if a real mes-

sage is received with bad data, an active
error flag won’t abort it early. Instead, it
has to run to completion without any
nodes issuing an ACK. Worse yet, it

could happen that one node issues the
ACK and the rest do not. For CANRF
to be robust, the higher-level protocol
(HLP) must handle missing messages.
Soon I’ll cover message forwarding,
which addresses the problem.

To summarize, the CAN device is

always listening for a start bit. It detects
the edge, verifies a short time later at
the sample point that the bit is a domi-
nant, and then starts accumulating the
identifier and data-length code bits. By
chance, if the device starts transmitting

at the same time, it listens during the
recessive bit windows. If it sees a domi-
nant when it expects a recessive, it
relinquishes the bus and starts receiving
the message. At the end of the message
it issues an ACK in the ACK slot if the
message was correctly received. Then,
it tries resending its own message.

HARDWARE

For small projects, the absolute cost

of the processor rarely justifies the extra
software development that may be
required to fit the application in a
restricted environment. The PIC12C509
is one of those environments.

Normally, I would pick the largest

device available (e.g., a PIC16F877) so
that the code, data, or stack size would-
n’t be an issue. But for this project, I
thought I’d try to make the application
as compact as possible, so I chose a
simple eight-pin processor that could be
upgraded with an A/D converter and
EEROM. (I also had five PIC12C509
devices in my prototype tray.) One of
the six modules I built is shown in
Photo 1. Figure 1 is the schematic.

By the time I had allocated pins for

the SPI interface and interrupt line, I
had only one line left for I/O. However,
the MCP2510 CAN device used on the
CANRF has five user-definable pins
that can be defined as three inputs and
two outputs. I designed the board so
that the one leftover pin on the PIC
could be used for digital input or out-
put or as an analog input on one of the
more sophisticated eight-pin processors
like the PIC12CE674.

Speed or timing accuracy weren’t

important in this application, so the
internal oscillator (4 MHz) and reset
were enabled. That came back to haunt
me later on. The standard SPI MOSI,
MISO, CLK, and CS signals constitute
the brunt of the interface. I also chose
to use the interrupt from the MCP2510
as the signal that a message had arrived
rather than having to poll the registers
inside the device.

The two MCP2510 outputs drive

small FETs to create high-current sink-
ing outputs for LED arrays or relays.
The inputs are filtered through an RC
network. The free PIC I/O pin is used
as a debugging output to blink an LED
or to provide a bitstream with embed-

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

17

ded digital information (see Listing 1).
The

ReportByte() function generates

a short pulse and then longer 0/1 pulses
representing the value of the byte fol-
lowed by another short end-of-frame
pulse. This function lets you examine
program variables and follow move-
ment through the various states or dur-
ing the parsing of the CAN messages.

Because of the two-level hardware

stack in the PIC12C509, most of the
code is in line, and there are only a few
function calls, which make the code size
larger with a lot of duplication. However,
the SPI bus CANRF support code ended
up using only about 539 words of code
on the ’12C509 and 449 words on the
’12CE674. Filter setup will increase the
code size (as will the application), but
this is impressive nonetheless because in
this small code size, there is a wireless
20-kbps peer-to-peer network with retries
and CRC checks on the messages. Even
better, the entire application fits within
the 1024-word code space.

Contrast the code space with the

wireless data link described in Tom
Dahlin and Donald Krantz’s article,

on the features implemented on the
core microprocessor. Bluetooth modules
that incorporate the 4-MB flash ROM
have enough space to accommodate an
end user application. 802.15.4 is expect-
ed to use 35 KB of code. Both protocols
have many advantages over CAN, but
CANRF seems to have a few of its own.

With a few carefully placed macro def-

initions, I’ve been able to make the code
portable between the PIC12C509 and
’12CE674. The ’12CE674 has two times
the code space as well as EEROM and
an ADC. And, it uses the PIC14xxxx
architecture. Thus, it will be possible,
because of the larger stack and more
subroutines, to shrink the code and
support an analog channel on GP0 and
EEROM for parameters and node ID.

MESSAGE HOPPING

My property has areas that make

low-powered, line-of-sight transmis-
sions difficult. Photo 2 is an aerial
view of my lot. The small icons repre-
sent locations where I want to mount
CANRF transceivers.

A program written in Delphi demon-

“Wireless Data Link” (Circuit Cellar
131). When I compiled the sample code
from their article, the core software was
588 words for a master/slave network
running at 600 bps using the 20-MHz
PIC16F877. Although Bluetooth is far
more sophisticated, Bluetooth can take
from 200 KB to over 2 MB depending

Photo 3—

The CANRF activity kit logs messages at

119 kbps from the serial port to the PC. A flag set in
the EEROM causes the red LED to blink when a mes-
sage is received. You can program the push button to
send a custom CAN message, which I use for an All
Lights On command. The activity board’s firmware
allows for full access to the MCP2510 CAN device. I
found it handy for concept testing.

background image

18

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

announcing the status of the inputs and
outputs. The message has a lifetime of
one, so it is sent one time to each one
(task 0) and nothing else is done with it.

If a change of state occurs (e.g., a

switch closure or output change), a
MOTION_SENSED or MOTION_STOPPED
message is sent with a lifetime of five.
All nodes receiving this message check
the sender’s ID value to determine if
the number is within a range of their
own ID. If the sender’s ID fits within
that range, the lifetime is decremented
by one and the message is reissued as
a

MOTION_FORWARD command.

A node receiving a

MOTION_FORWARD

executes the same tests along with an
additional test against the original
sender ID value. The originator of the
MOTION_SENSED message isn’t allowed
to forward it, but everyone else is. This
creates a flurry of messages that will
ultimately touch every node in the net-
work. As long as a node can see at least
one other node, odds are that it will
receive messages from the others.

Listing 3 is the entire message

sequence, which demonstrates how
device 5 senses the switch closure,
turns on its own lamp, and sends out
the status message with a lifetime of
five. Device 4 receives that message

strates an individual light sensor send-
ing messages (a mouse click on the
icon) to the other lights to turn on.
I’ve also written serial port interface
code, which parses the CAN messages
reported by the CANRF activity board
and changes the icons representing the
transceivers, sensors, and lamps (see
Photo 3). The activity board reports a
CAN message in the following format:

Time, ID, length and data bytes.

[RSSI]

00:00:16.22 ID:226 DLC:8 20 10

70 26 03 01 10 61 [458]

The 11-bit ID is broken into groups

as defined by the MAPCAN protocol,
which stands for modular automation
protocol for the controller area network.
The first two bits of the message ID
(bits 10 and 9) define the type of message
organized in the same type of ring struc-
ture as a real-time operating system. The
highest priority, ring 0, is the control (or
signal) message represented by the 0b00
value. The next priority ring holds the
devices that have the first two bits set to
0b01. Tasks, or threads, have the 0b10
value. Block transfers, or files, are the
lowest priority with a 0b11 value.

Bit 8 is defined as a client/server bit

that represents the direction of
the message. The final eight bits
have different values depending
on the type of message. Devices
break the 8-bit field into two
4-bit nibbles. The most signifi-
cant nibble identifies the type or
class of device while the lower
nibble is the device number in
that class. Tasks, or threads,
use all 8 bits to identify the
task/thread ID, where zero is a
global ID to which all devices
can respond (see Figure 2).

Messages in MAPCAN use the

first data byte as the destination
ID and the second byte as a com-
mand. A destination zero means
all devices can react to the com-
mand in the second byte.

Refer to Listing 2 for the com-

mands for the garden light sys-
tem. The

MOTION_FWD message

command makes the entire sys-
tem work. Every 2 s each node
issues a heartbeat message

and turns on its own lamp. It sets bit 7
of the I/O status byte to show that the
lamp is on (based on a received mes-
sage) and then forwards the message.

Finally, node 4 sends out a new sta-

tus message showing that the switch
reopened and the lamp is still on. This
message has a lifetime of one, so it
won’t be forwarded by anyone else.
Each lamp is run on a timer. Thus, if
the motion sensed or forwarded mes-
sages stop, the lamp will turn off by
itself shortly thereafter.

I’ve obviously run into restrictions.

I’ve had to think carefully about how to
assign IDs for each of the nodes. Ideally,
each node should be within range of at
least two other nodes, and those nodes
should be within a numeric range of
two away from the node. That means
node 2 should be placed close to nodes 1
through 4. Node 4 should be close to
nodes 2 through 6, and so on.

An unexpected issue was that of the

time it takes to transmit a single mes-
sage, and the time it takes to retrieve it
from the MCP2510 via the SPI interface.
The 4-MHz PIC12C509 doesn’t have a
built-in SPI controller, so I needed to bit
bang it. It turns out that it takes about
500 µs longer to detect and pull out a
message than it takes for the message to

be transmitted. That’s because I
also need to check overflow and
transmission-complete flags,
acknowledge the interrupt, and
enable the receiver. The inter-
rupt routine also performs some
of the store and forward filtering.

With this simple application,

overruns are a fact of life
because a single message could
generate an immediate response
from four nodes that generate
another flurry of messages back
to back. It’s a given that this
simple application will lose
messages, yet it works well. If I
were to use a processor with a
hardware SPI module, reliabili-
ty would improve.

I’ve placed the units in my

yard and tested the messaging.
I have to rely on the Delphi
application to know if all the
lights turn on, because I cannot
see them in the 10 s that they
remain on when a single unit is

Message type
00

Control or signal

01 Device
10 Task
11

File or block

Direction (

tt is the message type)

tt1 Client
tt0 Server

Node: device type (01) direction (d)
01dccccnnnnn

cccc Device class

0 User

defined

1

Keypads, keyboards, and switches

2 I/O

bit

devices

3 User

defined

4 Analog-to-digital

devices

5 User

defined

6 Counter

devices

7 Digital-to-analog

devices

8 User

defined

9 Encoder

devices

10

Motor

controllers

11

User

defined

12

PWM

Devices

13

Display devices like LED or LCD

14

User

defined

15

User

defined

Node: task or thread
x0dnnnnnnnn

nnnnnnnn Node ID for originator of control or task message.

Figure 2—

Organized like the ring structure of a multitasking executive, the

MAPCAN message IDs are broken into bit fields that make use of the
inherent priority structure of CAN messaging. Control or signal messages
have a higher priority than device messages. Server messages will win
arbitration over client messages. Devices outrank tasks and threads.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

19

pulsed. If I leave the switch input
closed, a walk around the yard shows
all lights on. The next step is to find
inexpensive PIR motion sensors, build
weatherproof housings, and run the
nodes over a longer period of time.

PEER INTO THE FUTURE

The CANRF peer-to-peer environment

is suitable for a large node system in
which many of the nodes are out of
range. Data acquisition systems that
cover a large physical area can be tied
together inexpensively. Using the
’12CE674, I could program a unique ID
in the EEROM rather than compile each
of the nodes with a hard-coded ID value.

The analog channel on the 12CE674

could be connected to an LM235 tem-
perature sensor and used to acquire
localized temperature readings over a
wide area. One idea would be to use
these modules in a vineyard to detect
frost and turn on sprinkler systems to
prevent the grapes from freezing.
Because the messages would be for-
warded around the wide area network,
a centralized master could monitor
and log the vineyard over time.

To save power, the large network tem-

perature profiling system could shut
down and turn on only once per minute.
To make sure all nodes wake up at the
same time, additional software—used to
synchronize the TOD clocks—could cir-
culate before a sleep is allowed. New
nodes installed in the system would stay
awake until they start receiving mes-
sages. They could determine which IDs
are not being used within their local

John Dammeyer earned a B.S. from the
University of Alberta after studying
both computer science and electrical
engineering. He has been designing and
writing software for embedded systems
for 20 years and CAN bus systems for
the last 11 years. In his spare time, he
enjoys working in his machine shop
and sand-casting aluminum and
bronze bits for his sailboat. You may
reach John at johnd@autoartisans.com.

PROJECT FILES

To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2003/157.

SOURCES

PIC12C509/C508/E674, MCP2510
CAN Device
Microchip Technology, Inc.
(480) 786-7200
www.microchip.com

CANRF Module
Automation Artisans, Inc.
www.canrf.com

REFERENCE

[1] J. Bachiochi, “The Missing

(Wireless) Link,” Circuit Cellar
132, July 2001.

range. Then, they’d issue sync up to a
clock message, receive a permanent ID
from a master, and go to sleep. As
always, some sort of node location iden-
tification would be required in order to
display the device’s location.

I

Listing 3—

This is a sequence of messages logged from the activity board. Devices 4 and 5 each send

their status message. Device 4 then forwards the message from device 5 with the last byte, the message
lifetime, decremented by one. When the message lifetime equals one, it’s no longer forwarded.

224 5 20 10 70 24 01

//Motion status from device 4

225 5 20 11 61 25 05

//Motion sensed, switch closed, lamp on

from device 5

224 5 20 13 E1 25 04

//Motion forward from device 4

224 5 20 10 71 24 01

//Motion status, switch open, lamp on

from device 4

| | | | | | |

| | | | | | --- //Message lifetime

| | | | | --- //Message originator

| | | | --- //Bit 0 = LED status, bit 4 = switch status

| | | --- //Command

| | --- //Destination class 2, all devices

| --- //Five bytes in CAN message

--- //ID is device type, device class 2, device ID 4 and 5

background image

the second star and has you make fine
adjustments. At that point, the Auto-
star can automatically point toward
any of several thousand objects it has
listed in an on-board database.

The trouble is that, like so many

product designs, usability was sacri-
ficed to save cost. As you can see in
Photo 1, the controller unit has a sim-
ple two-line display and a numeric
keypad as its user interface. It uses a
nested menu, which gives you access
to all of its operating modes as well as
the thousands of items in its star cata-
log. This is an inconvenient interface

20

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

G

alileo achieved lasting fame by

being one of the first to turn a tele-
scope toward the heavens to have a
closer look. Such innovative applica-
tions of technology were his specialty,
and I wonder what he would do with
today’s telescopes. Modern telescopes
are smaller, higher powered, and have
computer-controlled pointing, but they
could still use the hand of a master.

The controls on my Meade ETX-105

telescope (with Autostar controller),
for instance, include a sophisticated
star location and tracking algorithm.
Unlike my Palm Pilot, however, the
user interface for the telescope is a
primitive set of buttons and a two-line
display. What would Galileo do? I like
to think he would do what I did,
which was to create an adapter that
enables a Palm to run the telescope.

Palm-Enabled Telescope

Why can’t a Palm Pilot talk to a telescope? That’s the question that prompted Steven to
attempt adding an IR port to his telescope’s control unit. His effort has proved rewarding. Not
only can he control his telescope with his Palm, but he has also created the possibility for
Internet access.

Of course, you may be wondering

why someone would want to use a
computer to control a telescope. After
all, you just point and look, right? Well,
that’s true if you know where you want
to look. But many interesting objects in
the night sky cannot be seen with the
naked eye, which makes it difficult to
figure out where to point the telescope.
Fortunately, astronomers have cata-
loged the positions of sky objects so
you can find them. Unfortunately, the
position is given in the celestial coordi-
nates of declination and right ascen-
sion, the latitude and longitude of the
sky, which remain fixed in space
while the Earth moves underneath.

The Meade telescope’s Autostar

controller helps locate objects in the
sky by compensating for this motion.
The compensation depends on your
location as well as the Earth’s daily
and annual movement, so the
Autostar needs to know latitude and
longitude as well as time and date.
With this information, and a little
alignment, the Autostar can point the
telescope to any celestial coordinate.

The alignment process is relatively

simple, at least in concept. You enter
the day and time, your location, and
choose one of the alignment modes.
The two-star alignment mode, for
instance, picks two easily identifiable
stars as its reference marks in the sky.
With the alignment mode picked, the
telescope points itself at the first star,
and then you make fine adjustments
to bring the star to the center of the
telescope’s field of view. When you’re
done fiddling, the telescope moves to

FEATURE ARTICLE

by Steven Pope

Photo 1—

The Autostar controller provides many useful

functions for controlling the telescope, but its user inter-
face is awkward. It has a two-line display and a data-
base of more than 1000 objects to select from.

Photo 2—

The complete system has three parts: the

telescope with Autostar, a Handspring handheld (run-
ning Palm OS), and the bridge module. The module is
housed in the box at the bottom of the photograph.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

21

TWO SOFTWARE MODULES

The hardware was the simple part. In

order to make the bridge module work, I
needed to develop two sets of software.
One set runs on the eZ80 and handles
the exchange of information between
the Autostar and the IrDA link.
Commands and responses follow the

Meade telescope serial command proto-
col, which functions like the old AT
command set for modems (and bypasses
the annoying nested menus). The other
software runs on the Palm and provides

the user interface as well as the inter-
face to the GPS receiver. The Palm is
the master controller, which means that
the Palm initiates all communication
between the telescope and user. The
telescope does not send messages
without a command from the Palm.

Of the two software modules, the

eZ80’s is the simplest. The eZ80 takes
a command coming over the IrDA link
and passes it to a routine that reformats
it into an Autostar message. It then
completes the operation by passing the
message to the Autostar through the RS-
232 link. It takes responses from the
Autostar and passes them back to the
IrDA link. One other note: when the
eZ80 firmware powers up, it blinks
the status LED hanging on JP2 pin 1,
reminding you that the date, time, lati-
tude, and longitude have not been set.
After you send this information from
the Palm to the eZ80, the status LED

for entering the date, time, and loca-
tion, and it’s extremely clunky when
trying to find an object in the data-
base. Scrolling two lines at a time
through a list of thousands of stars is
not my idea of usability.

What my telescope really needed

was a graphical user interface that
made it simple to find what I was look-
ing for. Automating the entry of set-up
information also seemed like a good
idea, because I can hardly keep track of
time much less my latitude and longi-
tude. The Autostar includes an RS-232
port for using a laptop computer to
handle the interface, but I didn’t want
to have cables that I could trip over in
the dark connecting my laptop to the
telescope. With my luck I’d trip, pull
the telescope over, crash into the com-
puter, and destroy them both.

PALMING THE PROBLEM

As I thought things over, I realized

that my Palm personal organizer could
serve as the computer interface and
connect to a GPS receiver to automati-
cally determine the viewing location.
The Palm also offered a wireless
infrared IrDA port for communicating
with remote devices. That would solve
the cable problem, if the Autostar also
had an IrDA port. It didn’t, so I decid-
ed to build one.

The overall system design is shown

in Figure 1 with the completed module
and telescope shown in Photo 2. I creat-
ed a bridge module with an IrDA port
that connects to the Autostar controller
and receives its commands from the
Palm. The module allows the Autostar
to function normally as a handheld
controller, but it adds the ability to
send commands from the Palm, as well.

I had a number of requirements to

meet with this module beyond its
ability to offer an IrDA interface: it
had to be small, low power (it runs on
the same battery power as the tele-
scope), and inexpensive to build and
develop software for. I also wanted
some expansion capability for adding
more interface options in the future.

I chose the Zilog eZ80 as the module’s

core processor because it provides the
two main features I wanted, an IrDA
port and an Ethernet port (for future
expansion). In addition, it includes a

number of other features that would be
useful for this and future projects. For
instance, the eZ80 offers an RS-232 port
and an I

2

C interface, which allow the

bridge module to connect to a number of
different displays if I want to give the
module its own user interface. The
eZ80’s real-time clock allows the mod-
ule to maintain time of day, eliminating
one manual step in the telescope’s setup.
The processor also has a large address
range (up to 16 MB), which will come
in handy as I keep adding functions.

Another important reason for choos-

ing the eZ80 processor is that it is avail-
able in fully formed modules with a
complete development tool package. In
this case, I chose the eZ80 Webserver
module (eZ80L925048MOD), which
comes with on-board IrDA transceivers
and an Ethernet port, 1 MB of flash
memory, 24 general-purpose I/O lines,
and a system-expansion port for con-
necting other hardware. The module’s
software development support includes
a full tool suite with a flash memory
loader, debugger, compiler, assembler,
and application examples. The software
package also includes Internet software
that I will use for future enhancements.

The Webserver module needs a little

bit more circuitry in order to serve as
the bridge between the Autostar and
Palm. The additional circuits, shown
in Figure 2, are on a PCB with pins
that mate with the Webserver mod-
ule’s expansion sockets and provide
back-up batteries, voltage regulation
for the Webserver module’s power, and
RS-232 drivers for the serial port. I
also needed to relocate the IRDA
transceiver from the eZ80 module to
the front of the enclosure and add a
red IR window. The complete assem-
bly is shown in Photo 3.

Meade

ETX motor drive

Meade

Autostar

Zilog’s

module

GPS

option

Palm OS

device

Wireless access

point (802.11 or

Bluetooth)

Any ’Net-based client:

Tungsten C Pocket PC, Mac Linux, or Window

Motor drive

interface

Power to

Autostar on

this cable

RS-232

Interface

12-VDC Input

Battery pack

or wall adapter

RS-232

IRDA

Ethernet

Figure 1—

The bridge module attaches to the Autostar

through its serial port and receives infrared signals
from the Palm. It formats messages for the IrDA link
using a protocol designed to ensure message delivery.

Photo 3—

By looking inside the box, you can see the

Webserver module and the secondary board under-
neath it. The module contains the core processor, mem-
ory, and IrDA circuits.

background image

22

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

IrDA link. Any message that includes
these values in the datastream has to
be modified. When sending data con-
taining a reserved value, the eZ80 or
Palm (whichever is sending) inserts a
0xF2 command to tell the receiver
that something is up, and then breaks
the offending data into two bytes with

stops flashing and stays on.

The datastream over the

IrDA interface is different
from the Meade protocol.
The first difference is that
messages passing over the
IrDA link include a com-
mand code at the begin-
ning and add a checksum
followed by end-of-mes-
sage code at the end, fram-
ing the telescope’s protocol
string. The eZ80 uses the
command code to deter-
mine the start of a message
coming over the IrDA link and the
checksum to verify that the message
arrived correctly. If there is a message
error, the eZ80 will not acknowledge
the message and will throw it away.

The other difference is that the

binary values 0xF0 through 0xFF are
reserved as command codes in the

the first nibble set to zero.
Thus, an attempt to trans-
mit 0x04 0xF3 0x06 would
be sent as 0x04 0xF2 0x0F
0x03 0x06. This minor refor-
matting, along with the
framing elements, help
ensure reliable communica-
tion over the IrDA link.

The Palm software

includes an application pro-
gram and the IrDA commu-
nication program. I used the
Metrowerks CodeWarrior
for Palm OS software devel-

opment tool (V.7.0) to create the Palm
code. You may download the source
code from the Circuit Cellar ftp site.
The software targets the Palm OS
V.3.5. The code will not work with
later versions of the Palm OS because
of a change Palm made to the IrDA
Enable API call in version 4.0. The

Figure 2—

The bridge module consists of a manufactured processor board and additional circuitry. The additional board provides RS-232 interface signals as well as voltage

regulation for the module.

Photo 4—

You can activate the telescope software by tapping the Galileo icon, which

takes you to the Welcome screen. The main control screen, shown on the far right,
emulates the functions of the Autostar controller.

background image
background image

24

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

new call causes a hardware conflict in
this application, so if you want to use
the later version of Palm OS, you’ll
need to make an assembly routine for
the Palm to bypass the API call.

THE PALM APPLICATION

Users initiate the Galileo application

from an icon on the Palm screen, which
takes you through a Welcome screen to
the main control screen, as shown in
Photo 4. This screen emulates the
Autostar control functions, giving you
the ability to control the direction and
speed of telescope movement for manu-
al pointing. It also gives you the ability
to adjust the telescope’s focus and pro-
vides user location information. The
display takes the day and time from the
Palm OS; it also takes latitude and longi-
tude from a GPS receiver if one is con-
nected to the Palm’s RS-232 port and
the port is enabled. You can enable the
GPS port from the Preferences menu.

Enabling the GPS receiver port allows

the Palm to read your current location
from the GPS. You cannot leave the
port enabled, however, because the
Palm will allow only one port, the RS-
232 or IrDA, to be active at one time.

Because you are not going to move

the telescope while you’re viewing,
you need only activate the GPS port
long enough to get your set-up loca-
tion and store the information. You
can use the location data for one view-
ing session, or you can create an entry
in a site list so you can return to the
site another time and set up without
the GPS. I will eventually upgrade the
software to include personal notes
with the site information.

Each of the information blocks on

the Palm, as well as soft buttons emu-
lating the Autostar, can trigger a com-
mand to the telescope. Tapping the
time of day display, for instance, sends
the time to the telescope. Sometimes,
however, a soft button is too much
trouble, so I also mapped the com-
mands I use frequently to the Palm’s
hard buttons (see Photo 5).

The Slew/Focus select toggles the

button mapping from Slew mode to
Focus mode. In the former, the hard
buttons allow you to move the tele-
scope in any of the four compass
directions at the speed you select

through the Palm screen. In Focus
mode, you can control the telescope’s
focus motors at one of two speeds.

Another feature of this screen is the

pull-down selection menu. Tapping on
the top bar of the screen will bring up
the menu. With the Autostar’s two-
line display, finding an object in the

database requires a lot of tedious scroll-
ing. The Palm’s pull-down menu inter-
face makes finding an object in the
database a simpler, more pleasant task.

COMPENSATING FOR IRDA

Although the software routines for

the eZ80 and Palm are mostly straight-

Listing 1—

The Palm uses this communications routine to talk to the telescope. It has to reformat bytes that

might be confused for commands and resend the commands when they fail.

//Format message to send to IRDA Port. You can enable/disable

the handshake feature with the do_not_wait_for_handshake bit.

void Send_Message(Char Msg[])

{

int i;

FormPtr pForm;

Msg[byte_count] = 0;

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

{

Msg[byte_count] ^= Msg[i];

}

Msg[byte_count] = ~Msg[byte_count];

//Determine checksum byte

Msg[byte_count] = Msg[byte_count] & 0x7F;

//Determine checksum byte

//Remove the MSB bit to make sure this byte does not look like a

command byte.

byte_count++;

Msg[byte_count] = END_MESSAGE;

//Load up end of message byte

byte_count++;

index=0;

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

{

Msg_temp[0] = Msg[i];

SerSend( refNum, Msg_temp, 1 ,&err);

//This API sends a byte out the IRDA port.

msDelay(1);

//Delay time between bytes

}

if (!do_not_wait_for_handshake)

{

timer = 0x0AFFF;

//Timeout time before sending retry

timeout_timer=true;

//Enable timer out timer

next_pos = 50;

pForm = FrmInitForm (SearchingForm);

FrmSetActiveForm(pForm);

FrmDrawForm (FrmGetActiveForm());

FrmSetEventHandler(pForm,

SearchingFormHandleEvent);

}

else

{

do_not_wait_for_handshake = false;

}

}

background image
background image

26

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

forward translation and display, the IrDA
link is a critical element that requires
careful consideration. The IrDA link is
not simply a wireless version of the RS-
232. There are two major differences.

The first difference is that the IrDA

must operate in Half Duplex mode.
Unlike a pair of wires, which don’t
interfere with one another, the optical
pathways interact. The IrDA transmit-
ter is located next to the receiver,
sharing a common molded lens assem-
bly. Thus, during transmission, you
have to shut down the receiver, or you
will see your own outgoing message.

The second difference between RS-

232 and IrDA is the reliability of the
link. A wire is either working or dis-
connected. IrDA requires the sending
and receiving units to be aligned (i.e.,
they need to point at each other) in
order to connect, so connection
depends on your aim and the steadi-
ness of your hand. It also depends on
not being blocked, such as when my
dog walks between the Palm and the
telescope during transmission.

When the Palm tries to send a mes-

sage to the telescope, it must be point-
ed correctly and stay that way
throughout the message exchange or
the message won’t make it through.
To keep this uncertain link from being
a major frustration, the Palm should
be able to tell when messages fail and
correct the situation.

The IrDA controllers in the Palm

and eZ80 don’t address this problem.
Their function is to handle things like

Palm will resend the command. In
this way, the Palm maintains control
over the communications link, and
the eZ80 can simply send its response
messages blindly.

This protocol makes the communi-

cation bulletproof in that it ensures the
accuracy of messages. It also makes the
use of the IrDA link more convenient.
Unlike a television remote, the Galileo
Palm tries multiple times during a peri-
od of several seconds to get the mes-
sage through. You don’t have to point
first and then press the button to see if
they are aligned correctly; nor must
you try again if there is no response.
You can simply press, point, and let the
Palm take advantage of the link as soon
as everything lines up.

Be careful when using this protocol.

Because of the need for handshaking
and retry, the messages sent over the
IrDA interface should be short. The
longer the message, the more likely it
is that the link will be broken before a
successful transmission and response
have been completed. That means

clock recovery and bit synchroniza-
tion. It’s up to the higher-level proto-
cols to address the unreliable link.
When I began looking at the IrDA
specifications, however, I was over-
whelmed with all the software layers
needed to get a standard protocol stack
up and running. I put the specification
book back on the shelf and created my
own protocol to get the job done.

THE GALILEO PROTOCOL

The aforementioned command and

checksum framing are part of my
Galileo protocol. Starting the message
with a reserved command word, the
Galileo protocol ensures that the
receiver can distinguish between a
valid incoming message and a message
fragment. The checksum at the end of
the message ensures that the message
was received correctly. Listing 1
shows the Palm routine that builds
the IRDA command string.

The eZ80’s protocol task is to validate

incoming messages, send an acknowl-
edgement when a message arrives cor-
rectly, and to format its respons-
es properly. All of the protocol
intelligence is in the Palm.

As you can see in Figure 3,

the Palm software provides for a
message retry. When you press a
button to initiate a command to
the telescope, the Palm writes
the message to a buffer and
sends it to the serial port. The
IrDA driver software sends this
message and awaits a response
from the telescope. If the tele-
scope doesn’t respond within
500 ms, the Palm resends the
message. During the message-
sending process, the user dis-
play shows a “Searching” mes-
sage. Each pass through the
retry loop adds a period to the
end of the Searching message.
After 20 passes (10 s), the Palm
reports a “Cannot find eZport”
message and quits.

When the Palm is expecting a

response from the telescope,
the retry loop includes looking
for a valid response as part of
its definition of a completed
message. If the response is cor-
rupted, or never occurs, the

Figure 3—

To ensure reliable communication over the IrDA link,

the Palm software uses a wait-and-retry approach to communi-
cations. It sends a message and waits for a response, resending
if the response fails.

Palm main

control screen

Button

push?

Control message

for button just

pushed formatted

into “Message

packet”

“Message Packet”

written to Palm’s

serial port

Message

“OK”

back from

IRDA

port

Operation

complete

back to main

Wait

100 ms

Output “Searching”

message

Retry

counter

0?

Y

N

Output

“Cannot Find

IRDA Port”

Y

N

N

Resend message

Start retry counter

Palm’s

serial port

enabled in

IRDA mode

Y

No user input

Palm OS controls

Palm resources

Photo 5—

Mapping the Autostar to the Palm display

gives soft keys. The software also maps those keys to
the Palm’s hard buttons.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

27

network connection, I could even
stargaze over the ’Net from the com-
fort of my home.

Although searching the stars from

inside my house doesn’t generate the
same thrill as standing outside in the
clear night air to gaze at heavenly
objects with my own eyes, it does
have one benefit: I can scan the stars
and still be able to meet my wife’s
request, which is to stay home and
gaze at her.

I

you’ll have to use additional retry
attempts to increase the odds of hav-
ing the link work, which will make
the link less responsive.

I found that keeping the data packets

to 10 or 20 bytes yields the best results
in terms of reliability and speed. Longer
data blocks should be broken up and
numbered so that the receiver can put
them back together and have labels to
identify the start, end, and size of the
block. Figure 4 is an example of a
command string.

Using the Palm and bridge module

to control the telescope, I get more
than a better user interface. I also have
the beginning of remote control capa-
bility. But pointing the handheld Palm
at the telescope is a tedious way to
issue a long series of commands. A
wireless Ethernet link would be more
practical. I chose to use the Webserver
module as a core so that I could
expand in that direction.

The Webserver module includes an

Ethernet port and comes with full
Ethernet and TCP/IP software support,
so turning the Galileo Palm bridge into
a Galileo Internet bridge would require
only RF access point components as
hardware additions. The eZ80 software
would become more complex, of course,
but most of the necessary software ele-
ments are available and ready to use in
the Webserver support package. The
support software also includes a full
HTML server, which turns the design
of a user interface into a simple HTML
programming effort. A PC, running any
operating system, can run the telescope
without additional programming.

I could even set up the telescope for

’Net-based control. I could download
star data from the ’Net and pass it to
the telescope, which would give me an
unlimited database of objects to gaze
at. With a CCD camera and a wireless

CT_CRL = 0×F8
MT_MOVE = 0×05
MESS_SOUTH = 0×01
MESS_CS = (CT_CRL

MT_MOVE

MESS_SOUTH) & 0×7F

END_MESS = 0×FE

CT_CRL

MT_MOVE MESS_SOUTH CS

ENDMESS

5-byte messge approximately 1 ms

CT_CRL

MT_MOVE MESS_SOUTH CS

ENDMESS

Wait for handsake time 500 ms

Figure 4—

A typical message from the Palm demonstrates the Galileo format. Messages are short and framed with

a command code and checksum.

PROJECT FILES

To download the code, go to ftp.cir-
cuitcellar.com/pub/Circuit_Cellar/
2003/157.

SOURCES

ETX-105 telescope (with Autostar)
Meade Instruments Corp.
(800) 626-3233
www.meade.com

m100, OS Development tool
Palm, Inc.
(408) 503-7000
www.palm.com

Visor Prism
Handspring, Inc.
www.handspring.com

eZ80 Microcontroller and Webserver
module (eZ80L925048MOD), IrDA
development system
Zilog, Inc.
(408) 558-8500
www.zilog.com

Steven Pope has a B.S.E.E. and holds
five U.S. patents. Currently, he is a
fellow at Zilog, where he focuses on
embedded microprocessor applica-
tions. Steven’s hobbies range from
astronomy to model trains and radio-
controlled cars. You may reach him
at stevens-designs@attbi.com.

background image

however, to be perfectly honest, I ended
up soldering one connection when a
lead from one of the LED digits broke
during the wire-wrapping process.

HOW IT WORKS

My calculator’s internal workings are

similar to those of commercial calcula-
tors and computers. User input and
numeric key sequences are entered by
means of the keypad or through the
serial port when it’s used as a numeric
coprocessor unit.

The calculator processes the selected

operations by feeding data to the
embedded microcontroller for evalua-
tion. Then, it performs the calculations
using standard floating-point arith-
metic, as shown in Listing 1. Answers
are converted from the internal IEEE
floating-point formats to ASCII values
and sent to the desired output device,
which includes the LED display, LCD,
or the serial port connected to a host
PC or laptop. In Coprocessor mode, the
system uses the serial interface exclu-
sively for its I/O. A unique feature of
this calculator is that answers may be
displayed in any combination of the
three display methods.

CONSTRUCTION TECHNIQUES

You may prefer soldering to coding

software, but I prefer the lost art of wire
wrapping because messy chemicals are
unnecessary. Therefore, it’s cleaner and
doesn’t generate smoke. If I had my way,

28

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

E

lectronic calculators are amazing

tools that have been around in one
form or another for nearly half a cen-
tury. They’re used each day in homes,
offices, and schools for tasks such as
balancing checkbooks, paying taxes,
and performing most arithmetical
tasks. For convenience, calculators are
now available in sizes to accommo-
date almost any purpose. The inner
workings of a basic calculator using
programmable logic devices may now
reside on a VLSI, FPGA, or CPLD chip
no bigger than a pinhead.

Because PCs and laptops are descen-

dents of the calculator, gaining an under-
standing of calculators and how they
work should furnish you with insight
into the workings of modern digital
computational devices. Newer genera-
tions of calculators have evolved in
parallel to PCs, and they are equipped
with financial, trigonometric, and scien-
tific functions. Some calculators from
Hewlett-Packard and Texas Instruments
even include matrices, symbolic inte-
gration, differentiation, and program-
ming languages such as Basic.

You can build your own four-func-

tion calculator with common elec-
tronic components available on the
Internet or at your local electronics
shop. In this way, you can recapture
something of Blaise Pascal and Charles
Babbage’s spirit of invention by build-
ing a calculator piece by piece. If
you’re interested learning more about

Build Your Own Four-

Function Calculator

Daniel recently built his own electronic four-function calculator, citing little more than the spir-
it of invention as the impetus for his choice of design. In this article, he presents us with a
thorough description of the project.

the history of the calculator, you may
download my essay on the subject
from the Circuit Cellar ftp site.

BUILD IT YOURSELF

In this article, I’ll help you get started

on the construction of your own basic
four-function calculator, which you
may later modify to perform additional
operations. In addition, I’ll show you
how all of the calculator’s subsystems
(keypad, display, and PIC18C452 micro-
controller) work together (see Photo 1).

I took on the challenge of attempt-

ing to make this project completely
solder-free. PC boards, chemicals, and
point-to-point wiring are unnecessary,
although you may use any method of
construction that you desire. For the
most part, I succeeded in assembling
my own calculator in this manner;

FEATURE ARTICLE

by Daniel Ramirez

Photo 1—

Ready to build your own calculator? The

clear casing allows you to see it all!

CONTEST ENTRY

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

29

THE VISIBLE CALCULATOR

Inspired by the visible man and visi-

ble car engine educational models,
which you can find in most science
stores, I chose to encase my calcula-
tor’s electronics and LED display in
transparent plastic boxes. I obtained
the boxes from an arts and crafts
store. I color-coded the LED digits to
create a unique display.

The display digits are grouped in four

sets of three LEDs. Each set has a differ-
ent color (red, green, orange, or amber)
to indicate thousands. I arranged the
digits in the color-coded groupings
because I felt it was more intuitive than
using digits of the same color. When
the LCD is used, alphanumeric char-
acters appear on the LCD and prompt
you for input. Text messages cus-
tomized in the firmware also can be
sent to the LCD for output.

PSYCHEDELIC DISPLAY

In order to make this project visually

interesting, I decided to use large, bright-
ly colored LED digits. The LEDs shown
in Photo 2 display well in a dimly lit
room. Seeing the pi value in rainbow
colors might take you back to the psy-
chedelic 1960s. I produced a carousel of
colorful numbers using a simple loop
and calling one of the LED display rou-
tines (see Listing 2). I selected the larger
LED digits (12.3 mm × 14.4 mm) to
make the easy-to-read numeric display.

The LED display module is assem-

bled from individual LED digits that
were stacked together with glue. The
12 LED digits are arranged in clusters
of four: three red, three green, three
orange, and three amber. To keep the
digits aligned, I used a heavy bookend
with a straight edge and carefully
glued one digit at a time. I let each set
for a few minutes and dry before I
attached another digit.

After the LED digits were glued, it

was time to wire wrap them. As you
can see in Figure 1, connecting each of
the leads makes the LED display bus. I
did this carefully because the LED
digit leads are delicate and can only
support a one-level wrap.

Compared to an LCD, the LED dis-

play has some disadvantages. An LED’s
power consumption is much greater
than that of an LCD, so the 9-V battery

the pin of each surface-mount IC that’s
used for prototyping would be brought
out to a one- or two-level gold-plated
post used to hang a wire-wrap wire.

Ordinarily, prototype boards such as

those sold by Radio Shack (part no.
276-174) use heavy-gauge jumper wires
to make the circuit connections. The
result is a wiring nightmare when all
of the calculator’s components are con-
nected. I remedied this situation by
using multiple rows of 0.1

pin headers

as one-level wire-wrap posts to make
the connections. I used the extra-long
3/8

pin headers, which are available

from Jameco and Digikey, for making
multilevel wraps. Thus, I no longer
need to buy expensive wire-wrap
sockets for the ICs, and I’m able to
use the thin 30-gauge wire-wrap wire
for the connections.

A basic Radio Shack wire-wrap tool

(part no. 276-1570), which costs $7.49,
is required for the delicate LED digit
display. In order to save time, I also
used an electric wire-wrap gun, which
I purchased at a surplus supply store,
although the entire project can be
built using only the wire-wrap tool.
The 30-gauge wire used for wire wrap-
ping may be found at Radio Shack in
red, white, and black 50

spools.

The wire-wrap connections may be

soldered for extra durability, because
they aren’t as reliable as normal two-
or three-level wire wraps. But this
would make it harder to reuse compo-
nents, including the wire-wrap wire.
For a more durable calculator, it may
be a good idea to consider using
point-to-point or PC board construc-
tion methods.

Listing 1—

The code for the project is straightforward. This section of code shows how the four-function cal-

culator evaluates simple arithmetic expressions.

The calculator performs double precision floating-point addition,

subtraction, multiplication, and division. It does not currently sup-

port levels of nesting parentheses for complicated mathematical

expressions.

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

double Calculator(double Argument1, char Operator, double Argument2)

{

double TheResult;

switch(Operator)

{

case '+':

{

TheResult = Argument1 + Argument2; break;

}

case '-':

{

TheResult = Argument1 - Argument2; break;

}

case '*':

{

TheResult = Argument1 * Argument2; break;

}

case '/':

{

TheResult = Argument1 / Argument2; break;

}

default:

{

TheResult = 0;

break;

}

}

return (TheResult);

}

background image

30

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

MAX7219 DRIVER BOARDS

The MAX7219 LED digit display

driver IC is extremely flexible. At $9,
it’s one of the more expensive compo-
nents, but it’s well worth the expense.
It drives the LED digits’ segments
using a multiplexing scheme that
keeps them from drawing too much
power, and it also keeps them at the
correct level of brightness. A single
MAX7219 can drive up to eight LED
digits or 64 individual LEDs, although
it can be cascaded to drive groups of

will not last as long if the LED display
is constantly in use. Another drawback
is that the LED display isn’t of the
matrix variety. So, it displays only the
following: “H,” “E,” “L,” “P,” digits
zero through nine, periods, and dashes.
Obviously, the letters can be used to
display a “HELP” message in the event
of incorrect data entry. Floating-point
exponents may be entered and dis-
played using the “E” character (e.g.,
5.5E–20). Despite the disadvantages, I
enjoyed working with an LED display.

eight digits. Furthermore, it can con-
trol their brightness using a PWM and
a current-limiting resistor (10 k

).

The MAX7219 converts the binary

values to BCD to drive the correct LED
segments. Although the PIC18C452
has the ability to drive the LED digits
with additional low-cost discrete com-
ponents attached, it would make the
calculator firmware code more com-
plicated, because timer-driven inter-
rupts and PWM waveform generation
would be required.

The PIC18C452 sends data to the

MAX7219 display driver using a
three-wire SPI interface. The configu-
ration data—consisting of the level of
brightness, number of digits, and data
format (BCD or binary)—are sent to
the MAX7219. Test mode lights all
the segments of each LED digit that’s
connected. The MAX7219 commands
are shown in Table 1.

For the final version of this project, I

used three prototype boards, one for
each MAX7219 controller IC and a third
for the PIC18C452 micro. I could have
made the MAX7219-based LED display
driver circuit simpler if I hadn’t ordered
the wrong type of LED digits. I found
out too late that I should have ordered
the common cathode variety instead
of the common anode. They were list-
ed next to each other in the catalog.

Ordering the correct parts at that

stage of the project would have added
to the cost, so I decided to add four
low-cost 74240 inverted octal latches
from my parts box. My intention was
to invert the signals required by the
two MAX7219 LED driver ICs. The
74240 ICs may be substituted with
common cathode LED digits connect-
ed directly to the MAX7219. (You may
purchase the cathode LED digits from
companies like Digikey and Jameco.)

Next month, I’ll provide you with a

schematic that includes the common
cathode LEDs. This will save time
when building the boards, although
the project looks more impressive
with the extra components. You can
drive even larger LED digits with the
MAX7219 by making minor changes
to the power supply and adding some
transistors. If you’re interested in
studying the wiring diagram, refer to
the Resources section at the end.

CadSoft Computer, Inc., 801 S. Federal Highway, Delray Beach, FL 33483

Hotline (561) 274-8355, Fax (561) 274-8218, E-Mail : info@cadsoftusa.com

EAGLE 4.0

Schematic Capture • Board Layout

Autorouter

800-858-8355

Light

Standard

Professional

Layout

Schematic

Schematic +

Autorouter

Autorouter

Layout +

Layout +

Layout +

398$

798$

399$

398$

798$

49$

597$

1197$

199$

Prices

Pay the difference for Upgrades

EAGLE 4.0 Light is Freeware!

EAGLE 4.0 Light is Freeware!

http://www.CadSoftUSA.com

http://www.CadSoftUSA.com

Windows is a registered trademark of Microsoft Corporation
Linux is a registered trademark of Linus Torvalds

Windows

®

for

and

You can use EAGLE Light for testing and

for

non-commercial applications without charge. The Freeware
Version is restricted to boards up to half Eurocard format,
with a maximum of two signal layers and one schematic
sheet. All other features correspond to those of the
Professional Version. Download it from our Internet Site
or order our free CD.

The Standard Version is suitable for boards in Eurocard
format with up to 4 signal layers The Professional Version
has no such limitations.

Frustration? No, thanks.

Fun? Yes, please.

Version 4.0 Highlights

!
!
!
!
!
!

!

!

!

New Library Management with
Component Browser
Technology and Package variants for
components
Design your own commands via User
Language
Unlimited length for component
names/values
Design Rules define pad/via
dimensions and shapes
Net Classes for Autorouter and DRC
Minimum Autorouter grid: 0.02 mm

SMD pads can be rounded or round
Different pad shapes for Top, Bottom,
or Inner layers

Satisfied customers - the key to our success

>
>

>

>
>

that´s why every new EAGLE version is based
on the feedback from our customers
that´s why all our customers have access to our
highly acclaimed, comprehensive support, free
of charge
that´s why EAGLE has no hidden costs for
libraries or modules which prove to be
indispensable after purchasing
that´s why we really want customers to enjoy
working with EAGLE
that´s why EAGLE is one of the top-rated
programs for schematic capture and board
layout

FREE

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

31

Using two cascaded MAX7219 LED

driver ICs capable of multiplexing up to
16 digits, I could only drive 10 digits by
using them to push five LED digits
each. This may have been the result of
the excessive current drawn from each
of the large LED digits or it may have
been caused by the fact that I used com-
mon anode LED digits instead of com-
mon cathode LED digits. In the near
future, I plan to add the remaining four
digits to the LED display. Hopefully,
I’ll be able to find blue LED digits.

To build the calculator, I used a wire-

wrap technique with the 0.1

pin head-

ers plugged into the prototype boards
parallel to each IC. These boards are
shown in Photo 3.

STANDARD 4 × 4 KEYPAD

The standard 4 × 4 keypad has

enough keys for a simple four-function

calculator. As you can see in Figure 2,
the keys are mapped to functions. If
you want to build a more powerful sci-
entific calculator, you’ll need a larger
keypad (e.g., 5 × 4). By changing the
keypad firmware, you can designate a
special shift key to allow for access to
two times as many functions.

A simple way to effectively increase

the number of keys is to add push but-

tons or toggle switches that are tied to
unused I/O lines (e.g., use port A, RA4
with a 10-k

pull-down resistor). One

switch may be used to act as an
inverse, shift, or secondary function in
order to assign different meanings to
each key. The firmware must perform
a logic bitwise OR between the state
of the switch and the keypad code
that’s returned in order to create a
unique function identifier.

Using a 16 × 16 keypad opens unique

keystrokes. When using one switch or
push button, you get 32 functions
(1 × 16 + 16 = 32). If you use two
switches or push buttons, you get
48 functions (2 × 16 + 16 = 48).

The inputs to port B are pulled high

by using the PIC’s internal pull-up
resistors (see Figure 2). Because calcu-
lator keypads can generate electrostat-
ic discharges that can damage the PIC,

Photo 2—

The 12-digit LED shows the value of pi in

rainbow colors. I took the photos in a dimly lit room.

Figure 1—

You can use the schematic to assemble the calculator’s optional common anode numeric LED display driver circuit. Parts placement and board fabrication tech-

niques are not crucial.

background image
background image
background image

34

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

330-

resistors are placed in series

with the port B inputs for ESD protec-
tion. You can use a standard eight- or
14-wire parallel ribbon cable to con-
nect the keypad, or you can try a stan-
dard stranded hook-up wire for flexi-
bility. I could have used the PIC’s
change on port B status interrupt, but
I chose not to. Basically, I wanted to
keep the firmware simple without
interrupt service routines.

One problem with using the keypad

for input is the translation of charac-
ters required for entering exponential
floating-point numeric values (i.e.,
2.718 × 10

2

). Normally, the value is

entered through the keypad as “2 ×
718E2”; however, the keypad I select-
ed doesn’t have an “E” character.
Consequently, I’m limited to entering
fixed-point numbers, although the cal-
culator is capable of handling expo-
nential numbers.

When using the serial interface, all

of the keystrokes are entered from the
PC or laptop host keyboard instead of
the calculator’s keypad, so character
translation isn’t required. In addition,

there are more characters available,
such as “E” for exponentiation, when
entering floating-point numbers using
scientific notation. Thus, the value
may be entered as “2.718E2.”

The labels for calculator functions

(+, –, ×, /, =, and .) may be affixed to
the keys. You can enlarge the labels
with a copier, print them on trans-
parencies with an inkjet printer, and
then glue them on the keys. In order
to distinguish overlaid functions, the
secondary function key labels could
be printed in different colors as seen
on commercial calculators. For
instance, you could use white for pri-
mary functions and red for secondary
functions.

DEBOUNCING THE KEYS

Depending on the mechanical and

electrical characteristics of the selected
keypad, extra keystrokes may be
encountered each time a key is pressed.
You can eliminate this anomaly by
debouncing the keys, which is usually
accomplished by placing a 20-ms delay
in a loop where the key is polled.

I referred to Michael Predko’s book,

Programming and Customizing
PICmicro Microcontrollers

, as I wrote

my version of debounce in PIC18xxxx
C. I rehosted Predko’s debounce routine
in PIC assembly to C so that I could
include it for my calculator. [1] The algo-
rithm worked flawlessly, and it filtered
multiple keystrokes. Listing 3 is my
C version of his debounce algorithm.

You may download the C files from

the Circuit Cellar ftp site. The source
code shown in the keypad.c file
demonstrates how you can integrate
it in customized designs.

THE BRAIN

You must use a microcontroller for

this application, unless you incorpo-

Photo 3—

Notice the placement of the pin headers.

They are parallel to each IC on the prototype board so
that they may be wire-wrapped.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

35

rate EPLD, FPGA, or VLSI techniques.
I chose the PIC18C452 microcontroller
because it was more economical at $15
than a BasicX or ATOM micro costing
approximately $50 (supporting IEEE
floating point). The Stamp BSP doesn’t
have support for floating point, so I
couldn’t have considered it for this
project. Any Motorola 68HC12 or Intel
8052 derivative, such as the Domino
or a high-end Atmel processor, is suit-
able for this project. The 8052 Basic
interpreter that supports floating
point could be substituted with mini-
mal changes to this design.

The PIC18C452 has 32 KB of EEP-

ROM and 1536 bytes of RAM, most of
which I used for the firmware develop-
ment. I selected a 20-MHz oscillator for
the microprocessor clock, although I
could have selected up to 40 MHz for
speedier calculations. Note that the new
flash memory-based PIC18F452 doesn’t
require a UV eraser. This should help
alleviate the UV erase cycles. It will also
reduce the need to constantly remove
the PIC from the hardware when using
ICSP programming to burn the PIC. The
chip’s low-cost in-circuit debugging
capability allows for ICD2 debugging.

The MAX233 IC shown in Figure 2

uses the USART (RS-232) interface to
communicate with a PC or laptop
host via HyperTerminal. It also pro-
vides the means to use the calculator
as an IEEE floating-point coprocessor
to another PIC or STAMP microcon-
troller that doesn’t currently have
access to floating point.

When it’s used as the primary calcu-

lator storage device, the 24LC16B I

2

C

serial EEPROM can store up to 2048
bytes, which can be used for look-up
tables. In addition, it can store inter-
mediate calculation results. Another
possibility is for the firmware to use it
as a stack to evaluate expressions or as
a Forth or Basic interpreter. The
capacity is easily increased to 32 KB
by dropping in a 24LC256 32 KB × 8
serial EEPROM device. The storage
capacity can be increased even more
with additional I

2

C-networked serial

EEPROMs (e.g., eight 24LC256 devices
for a total capacity of 256 KB with
only minimal changes to the
firmware). You can add a 64-KB SRAM
for the faster operations required by

Listing 2—

I used this snippet of code to produce a carousel of colorful numbers on the numeric LED display.

while(1)

{

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

{

//Convert i to string for display

itoa(i, TestNumber);

//Send it to the numeric LED display in color

MaxPrint(TestNumber);

pause(10);

}

}

background image

36

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

the more sophisticated functions,
graphics displays, and languages.

BUILD THE BOARD

Use the schematic shown in Figure 2

to build the calculator’s controller
board. Point-to-point and PC board
construction are viable options, but I
chose the wire-wrap method for a
challenge. Also, you can wire-wrap
the controller by following the specif-
ic set of instructions I described in my
article titled “Optimize Your PIC”
(Circuit Cellar 133). In fact, you can
recycle previously built boards by
simply connecting the keypad and
MAX7219 driver boards.

If you don’t have an older board, you’ll

have to build the circuits from scratch.
To do so, use two or three standard
Radio Shack prototyping cards (part no.
276-174). First, insert the required pin
headers parallel to each IC. Use a small
block of hard wood to apply even pres-
sure to the pin headers as you insert
them into the prototype board (don’t use
your fingers). Photo 3 is a great guide.

For multiple connections, use a one-

or two-level wrap, or try a double row
of pin headers. Next, place the 0.1-µF
bypass capacitors as close to the IC
socket power pins as possible. Place the
remaining discrete components (resis-
tors, capacitors, and diodes) on the pro-
totype boards. If you use the wire-wrap
method, consider purchasing labels.

The next step is to connect the

power and ground wires. You may find
it advantageous to use the heavier
gauge jumper wires instead of the 30-
gauge wire-wrap for power and ground.

Connect the power lines with red
jumpers and the ground lines with
black jumpers. Finally, wrap each logic
signal with white, yellow, or blue
wire. Check each off from the diagram
until all of the signals are wired. Screw
PC standoffs to the prototype board
and glue or solder the RS-232 connec-
tor directly to it. Use a digital multi-
meter to check all of the connections
between the keypad and the controller.

The next step is to check the circuit

for shorts or open lines. Use the digi-
tal multimeter to check the continu-
ity on all of the power, ground, and
logic signals. You can inspect the
board with a magnifying glass.

Before populating the board with

the ICs, power the board by connecting
a 6-V battery to the positive and negative
power terminals, and then check to see
if the Power LED lights up. If it does,
check for 5 V at the V

DD

pin of each IC

and volts at the V

SS

pins. Then, the board

may be populated with the ICs, and
you can fire it up for the first time.

POWER UP

A good power supply is a must for the

LED display. Even though the LED dig-
its are multiplexed, they can still draw a
lot of power when all of the segments
are turned on (e.g., when displaying the
number eight). Earlier, I mentioned the
problem of only being able to display
a total of 10 large LED digits, which I
believe could be the result of excessive
current drawn by each LED. The power
supply must be able to handle this load
along with the power required for the
PIC18C452 and the other ICs.

As Figure 3 demonstrates, a 5-V

supply is sufficient for all of these
power-consumption requirements.
But, you could also use a 9-V alkaline
or NiCd rechargeable battery, or even
a 9- to 12-V wall transformer to power
the project. Depending on the number
and type of devices connected to the
controller board, the 7805 IC may
need a heatsink if it gets too hot dur-
ing normal use or if it shuts down
(although I didn’t require one for my
hardware configuration).

The power supply can be separate

from the board, or you can build it in
using any vacant real estate on the

prototype board. The calculator is
turned on and off with a convenient
toggle switch located next to the
power supply. A push button would
work as well.

My project doesn’t address low-

power consumption concerns, so the
type of display you use (LED, LCD, or
PC) will determine the length of time
the calculator will run using a 9-V
battery. I recommend a 12-VDC wall
transformer for continuous use.

C COMPILER AND TOOLS

As you can see, building a simple

four-function calculator from scratch
isn’t as easy as it sounds, particularly
because of all the software tools and
even some of the hardware (e.g., the
programmer and UV eraser) that are
required. It would be even more diffi-
cult and expensive with a hardware-
specific solution—such as using VLSI
techniques—unless you happen to
have access to the required silicon
compiler tools. But this method tends
to embed the entire application in one
monolithic IC, which is something
I’m trying to get away from.

I chose a flexible software solution

using the PIC18C452 that fully demon-
strates exactly how a calculator works.
The PIC18C452 has extensive capabili-
ties needed to handle most of the arith-
metic processing required by the calcu-
lator. Many of the PIC’s hardware fea-
tures are directly supported, using the
PIC18xxxx C libraries, so that PIC
assembly language is not required.

This project provides a great opportu-

nity to learn all about the PIC18xxxx C
compiler and tools, using Microchip’s

Command

Code

Description/results

No Operation

0

No operation performed. Used to cascade multiple MAX7219(s)

Digit 0

1

Select digit 0

Digit 1

2

Select digit 1

Digit 2

3

Select digit 2

Digit 3

4

Select digit 3

Digit 4

5

Select digit 4

Digit 5

6

Select digit 5

Digit 6

7

Select digit 6

Digit 7

8

Select digit 7

Decode

9

Decode register, a value of one enables BCD decoding

Brite

10

Intensity register

Scan

11

Scan limit register

Switch

12

On/Off register

Display Test

15

Activates test mode

Table 1—

I’ve listed all the MAX7219 LED controller commands that are available. You may customize the firmware

for special effects.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

37

free tool suite, because they’re simple
to use and inexpensive. I recently pur-
chased Microchip’s PICDEM 2 and
ICD2 to support the new PIC18F452.
These new tools are a boon to hobby-
ists because they provide excellent
low-cost development systems, which
allow a PIC to be programmed within
the application by using in-circuit seri-
al programming (ICSP). The result is
the elimination of the need to con-
stantly erase the PIC with a UV eraser.
It also enables low-cost debugging via
the PIC18F452’s in-circuit debugger
(ICD), which provides ICE capabilities
similar to the ICE2000 at one-tenth the
cost. The ICD2 capabilities include set-
ting one breakpoint anywhere in the
program memory and giving the user
the ability to watch any register or
memory location while actually con-
nected to the hardware.

I used the PIC18C452 because the

’F452, which is functionally identical,
was not available at the time. However,

in order to reduce the UV eraser
requirement, I suggest using the lower-
cost PIC18F452 and ICD2 programmer
needed to burn the PIC18F452. In addi-
tion, use the firmware contained in the
calc1.hex file (download from the
Circuit Cellar

ftp site), which

includes the complete four-function
calculator application.

There is one drawback to using the

calc1.hex file instead of the C code: it
prevents the customization of the calcu-
lator. I recommend the USB version of
the ICD2, because it’s much faster than
the serial RS-232 version during pro-
gramming and single-stepping code. It’s
too bad these tools weren’t available
sooner. They would have made debug-
ging my code much easier. The MPLAB
and MPSIM tools are available on the
Microchip web site along with the
PIC18C C compiler demo.

MISSING MATH FUNCTIONS

A calculator needs some kind of

floating-point capability, unless
you’re only going to use it for han-
dling fixed-point or integer quantities.
This is where I took advantage of the
PIC’s floating-point capabilities.

In the past, I’ve expressed my regret

that Microchip doesn’t supply certain
C libraries and functions with its demo
C compiler, specifically the stdio.h
library that supplies the

printf and

scanf functions. I later found, to my
surprise, that I couldn’t access the nor-
mally available trigonometric and sci-
entific C functions from the math.h
library, even though my application
had compiled and linked correctly.
According to Microchip’s latest release
notes, these functions aren’t provided,
but I hope they will be in the future.

Not having those libraries was dis-

couraging, to say the least, because my
calculator is dependent on those func-
tions. However, I eventually completed
some of the required floating-point for-
matting and conversion functions.

Figure 2—

Now you can build the main controller board. Use this schematic to connect the other subsystem components including the keypad, optional LED numeric display,

and LCD.

background image

38

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

The functions are needed to scan

numbers and operators from the key-
pad, and to convert ASCII floating-point
numbers to binary IEEE floating-point
format so they can be arithmetically
processed by the firmware. They’re
also needed to convert from binary
IEEE floating-point format back to an
ASCII formatted string so they may
be shown on the LED, LCD, or PC
displays. Although I haven’t modified
my version of

printf to handle float-

ing-point (

%f) and fixed-point (%d) spec-

ifiers, these functions are still neces-
sary. Eventually, I will have to do this
modification or, hopefully, Microchip
will fill the gap for me.

I could have saved program storage

space and constructed a more sophisti-
cated calculator if the functions had
been available in time for this article.
Because of time constraints, I could
only provide support for four functions:
addition, subtraction, multiplication,
and division. You can work on the
financial, trigonometric, and scientific
functions if you’re interested in numer-
ical methods. Use the serial EEPROM
provided in the controller board for
storing sine and cosine look-up tables.
I may explore this option myself.

BASE CONVERSIONS

You use the decimal system daily,

but other systems—such as binary
(base 2), octal (base 8), and hexadeci-
mal (base 16)—are commonly used in
digital computers. A trinary system—
such as the one in Arthur C. Clarke’s
classic novel, Rendezvous with Rama
(1973), in which visiting aliens did
everything in threes, and the sci-fi
movie, War of The Worlds (1953), in
which the Martians formed groups of
three before attacking—sounds
intriguing to me.

If a calculator is needed to convert

between the bases and display the
answers, it’s easy to add the base con-
version function. This function is
equivalent to the Stamp BS2/BSP hex
function. The LED display isn’t able
to handle all of the hex digits, so I
recommend an LCD when you’re
using this function.

The unique color-coded LED dis-

play is easy to read. In addition, hand-
icapped persons would find it helpful

if you were to add larger LEDs, voice
recognition, or voice synthesis hard-
ware to the design.

NO SWEAT

Using simple tools and common

components, you can build a calcula-
tor in a few evenings. It makes a great

conversation piece at the office or at
home, especially if you use clear plas-
tic housing to showcase the interior.

This was a fun project, especially

after I figured out how to get the multi-
colored LED display working, because I
was able to produce animated color dis-
plays. I also felt a great sense of accom-

Listing 3—

What do you think about my version of Predko’s keypad debounce algorithm written in PIC18 C? It

was originally written in PIC assembly, but I converted it to C so that I could use it for my calculator application.

//KeyScan: Scan a 16-key matrix keypad for operator keystroke

int KeyScan(void)

{

int i;

//Loop index

int j;

//Loop index

byte PortBValue;

//Value read from port B

//pause(20);

//Debounce keypad input

do

{

//Wait for all keys up

PORTB = 0x00;

TRISB = 0xF0;

} while ((PORTB >> 4) != 0xF);

pause(20);

//Debounce keypad input

//Debounce the keypad here

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

{

//Discharge the keyboard

PORTB = 0x0F;

TRISB = 0x00;

//Send PIO mode command to set port direction to input, this

works for any row

TRISB = 0xF0;

//Drive all columns low to determine if a key has been pressed;

port B pull-ups should be enabled

Low(PORT_B, i);

PORTB = Cols[i];

//Save Port B value

PortBValue = PORTB;

//Look up the key scanned in table

for (j = 0; j < 16; j++)

{

if (PortBValue == KeyLookupTable[j])

{

key = j;

goto ExitLoop;

}

}

key = 0xFF;

}

ExitLoop:

if (key != 0xFF)

{

if (db == 1)

goto done; //Already responded to this press, so

done

db = 1; //Set debounce and keypress flags

press = 1;

}

done:

db = 0;

//Reset the debounce bit

return key; //Return keystroke to caller

}

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

39

Daniel Ramirez is a software engineer
with more than 10 years of experience
working on real-time embedded sys-
tems. In his spare time, when he’s not
working on new robotics projects,
Daniel enjoys traveling, golfing, and
treasure hunting. You may reach him
at mgatron@aol.com.

PROJECT FILES

To download the C code, floating-
point formatting and conversion
functions, firmware for the MAX7219
and keypad, and an essay on the
history of the calculator, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2003/157.

RESOURCES

Maxim Integrated Products, Inc.,
Serially Interfaced, 8-Digit LED
Display Drivers

, 19-4452, rev. 3, 1997.

W. Press, et al., Numerical Recipes
in C: The Art of Scientific
Computing

, Cambridge University

Press, Cambridge, UK, 1993.

D. Ramirez, “Robot Sensor
Controller Board: Part 1,” Circuit
Cellar

135, 2001.

SOURCES

MPLAB, PIC18C452 Microcontroller,
PICDEM 2
Microchip Technology, Inc.
(480) 792-7200
www.microchip.com

Author’s Note: I’d like to thank to
my wife Pamela for her time and
assistance with this article.

B. A. Toole, Ada, the Enchantress
of Numbers: Prophet of the
Computer Age

, Strawberry Press,

Mill Valley, CA, 1998.

plishment after building an educational
electronics project using only wire-
wrap construction techniques.

If you want to learn how to build a

reverse Polish notation (RPN) calcula-
tor, be sure to read my next article,
which you’ll find posted on the
Circuit Cellar

web site in September.

In that article, I’ll provide you with a
schematic that uses common cathode
LED displays. In addition, I’ll go into
more detail about the firmware that’s
needed for the calculator to perform
mathematical scientific and trigono-
metric functions.

I

Figure 3—

You’ll need a 5-V power supply to power

your calculator’s controller board and the optional LED
display board. A heatsink may be required for the 7805
IC if the current drawn by LEDs and other peripherals
is excessive.

REFERENCE

[1] M. Predko, Programming and

Customizing PICmicro Micro-
controllers

, McGraw-Hill/TAB

Electronics, New York, NY, 2000.

background image

everything discussed here, you should
pass this column along to a younger
friend. Perhaps you can share your
oscilloscope and circuit ideas, as well,
to get them started in the right direc-
tion. Remember, these students will
become tomorrow’s engineers. They
need all the help they can get!

THE ENVIRONMENT

Because human vision doesn’t

extend into the infrared part of the
spectrum, IR LEDs look the same
whether they’re on or off. For some
reason, this leads many people to
believe that the only IR energy in a

ABOVE THE GROUND PLANE

by Ed Nisley

40

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

A

fter a few years of designing,

building, and fiddling with electronic
gadgets, you learn that everything you
need isn’t in the datasheets. Simply
put, your designs fail unless you factor
in your real-world experience.

Last April, I gave a talk titled “IR

Sensing for the Bewildered” at the
Tenth Annual Trinity College Fire-
Fighting Robot Contest. Most of the
robots used infrared emitters and detec-
tors of one sort or another to navigate
through the maze. In previous years, I
had witnessed considerable confusion
caused by misbehaving sensors.

The overall goal of the contest is to

design an autonomous robot that can
find a candle placed in a room of the
maze, extinguish it, and return to the
starting point. As Jake Mendelssohn,
the contest’s founder, says, “The
only people who think this is easy
haven’t tried it.” He’s right!

Many of the contestants are high

school and college students who
haven’t had much exposure to the
real world. Their robots and sensors
use straightforward designs that
work perfectly well at home or in
the lab but then fail completely in
Trinity’s Oosting Gym. Is some mys-
terious force at work?

Although Circuit Cellar readers

have much more experience with IR
and circuit design than most students,
Steve Ciarcia and I thought that
reviewing some basic IR sensing
would be useful. Even if you know

room comes from their IR LEDs.
Photo 1 clearly demonstrates the fal-
lacy of that notion!

Photo 1a shows Oosting Gym in

visible light. Photo 1b depicts what it
looks like in IR. My Sony DSC-F717V
digital camera has a NightShot mode
that removes an internal IR-blocking
filter, thus passing both visible and IR
to the CCD array. I added an external
filter that eliminates all visible light,
so Photo 1b shows pure IR that the
camera renders in green-tinged
grayscale. I suppose that’s in honor of
the phosphors in those awful first-gen-
eration IR nightscopes.

IR Sensing

Most professional engineers believe they have an adequate understanding of IR sensing
concepts, but it never hurts to brush up on the basics. In this column, Ed expands on many
of the topics he covered in a lecture last spring at the Tenth Annual Trinity College Fire-
Fighting Robot Contest. Both seasoned designers and curious students will find Ed’s
straightforward commentary useful.

Photo 1a—

High-pressure sodium lamps illuminate the Fire-Fighting Robot Contest in Trinity College’s Oosting

Gym.

b—

Taken through an optical filter that passes no visible light, this picture shows how the scene looks to IR

sensors. Some robot designers don’t anticipate the high intensity or AC modulation of the ambient IR.

a)

b)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

41

Figure 1 plots the char-

acteristics of several
emitters, detectors, and
filters against the wave-
length in nanometers.
The y-axis scale is linear,
which exaggerates the
highest decade but gives
you an idea where the
peaks lie. All of the
responses are normalized
to a maximum of one, so
you must take into
account the actual power
of a source or the sensi-
tivity of a detector.

Notice that IR photo-

diodes exhibit a broad
response with equal sen-
sitivity to both IR and
visible-red LEDs. Optical filters added
to their packages can reduce, but not
eliminate, the effects of visible light.
Many people are surprised when their
IR photodiodes produce signals caused
by visible light, even though visible
light is a small part of the problem.

Optical filters cannot eliminate

wavelengths close to those emitted by
IR LEDs for the same reason you can-
not build brick-wall electronic filters.
The HP sodium lamp curve in Figure 1
shows that high-pressure sodium
vapor emits a great deal of energy at
about 820 nm, which is almost exact-
ly at the peak response of IR photo-
diodes and extremely close to the
930 nm of IR LEDs.

The lighting in Oosting Gym con-

sists entirely of high-pressure sodium
lamps, because they have excellent
efficiency, decent color, and good oper-
ating lives. Their visible color tends to
be reddish-orange, but there’s enough
green energy to make the light fairly
pleasant. They have a completely dif-
ferent spectrum than the low-pressure
sodium lamps found in parking lots,
which produce essentially monochro-
matic orange-yellow light at the 590-
nm sodium D-lines.

During the first years of the contest,

the organizers realized that IR-rich
ambient lighting posed a major prob-
lem for most contestants, and since
then they’ve tried many seemingly
good ideas. One year featured banks of
fluorescent lamps above the mazes,

which seemed like a good way to elimi-
nate excessive IR. Unfortunately, even
though fluorescent lamps convert
much of their input power into visible
light, ionized mercury has an IR emis-
sion at 1014 nm, which can (and did!)
light up the IR detectors.

The phosphors inside fluorescent

tubes convert mercury’s ultraviolet
emissions into visible light, and the
glass tube itself absorbs UV, but enough
UV escapes to trigger the Hamamatsu
UV-Tron sensors with which many
robots detect candle flames. The fluo-
rescent lamps were gone by the next
year’s contest, and, eventually, they
simply turned off the HP sodium
lamps above the mazes, which pro-
duces the distinct shadows on the
matte-black floor cast by lamps in the
rest of the gym.

The curve for incandescent tungsten

in Figure 1 matches up well with IR
photodiode sensitivity, and, thus, it
cannot be filtered out. A glowing fila-
ment has a high thermal mass; there-
fore, unlike mercury and sodium arc
discharges, it doesn’t have much
120-Hz AC modulation from the 60-Hz
power supply. Some contestants
debugged their sensors under incan-
descent lamps only to find a buzz on
their signals in the gym.

In short, IR energy is everywhere,

and you must understand how to
detect your signal despite considerable
interference from the real world. Let’s
see what that requires.

REFLECTIONS

Most robots and, for

that matter, people detect
their surroundings by
reflected light. The con-
test maze has matte-
white walls and matte-
black floors, all of which
are carefully painted
prior to each contest and
sometimes touched up if
an errant robot leaves a
major scuff. Even these
simplified conditions
pose major problems for
many robots.

IR energy behaves just

like visible light in most
respects: it can be reflect-
ed, refracted, diffused, and

absorbed. Figure 1 shows that it has
about two times the wavelength of visi-
ble light, which makes surfaces twice
as shiny and accentuates chromatic
aberration in lenses. Thus, reflected IR
tends to have more glare and to be less
diffused from a given surface, while
refracted IR focuses on a different plane
than the corresponding visible image.

The matte-maze walls exhibit what’s

called Lambertian reflection, where
incoming light is diffused equally
well in all directions: you can see a
spot of light on a wall from any
direction. Every light source falling on
a Lambertian reflector contributes to
the outgoing energy in all directions.

Mirrors exhibit specular reflection,

where all the incident energy bounces
off at the same angle it enters. A sensor
that isn’t located exactly in that outgo-
ing beam won’t see any of the energy,
just as you can’t see a flashlight beam
on a mirror unless it’s glaring in your
eyes. A robot in a hall of mirrors has a
terrible time detecting the walls!

Most surfaces fall somewhere

between Lambertian and specular,
being neither completely matte nor
perfectly reflective. The Phong surface
model describes this situation using
mathematics that isn’t relevant here
because you generally don’t have the
exact numbers. To get the general idea
of Phong reflection, think of a “hot
spot” when viewed at the specular
angle plus a diffuse component visi-
ble from all other angles.

1.00
0.90
0.80
0.70
0.60
0.50
0.40
0.30
0.20
0.10
0.00

300 350 400 450 500 550 600 650 700 750 800 850 900 950 10001050 1100

Wavelength (nanometers)

Relativ

e response

LEDs

Eyeball

Lee 181 Congo blue

IR Photodiode

IR LED

Tungsten

87C IR filter

HP sodium lamp

Figure 1—

Infrared energy lies beyond the human eyes’ range, so you must rely on graphs to

show what’s happening. You can see that infrared photodiodes respond equally well to both
IR and visible LEDs, high-pressure sodium lamps perfectly match the peak response of IR
photodiodes, and even IR optical filters aren’t much help against glowing tungsten filaments.

background image

42

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Many robots sport IR LEDs and

photodiodes that are mounted side by
side, lined up parallel to each other,
and pointed directly at the wall. Even
in an ideal Lambertian world, that
doesn’t work well because the LED
doesn’t light up the entire area viewed
by the photodiode. Worse still, in a
specular world, the photodiode might
not see the LED’s reflection at all.

If you want to detect a wall at a spe-

cific distance, mount the LED and
detector as if they were looking at each
other in a mirror at that distance. The
wall won’t be a perfect mirror, of
course, but a detector aligned with the
middle of the LED’s Phong “hot spot”
reflection from the wall will capture as
much IR energy as possible.

Because the strongest ambient IR

generally comes from overhead, detec-
tors should angle down toward the
floor. The maze floors at the Trinity
contest are flat black to minimize
reflections, but, in the real world, floors
are generally the most specular sur-
faces after windows and doorknobs.
Therefore, you must trade-off direct
light from the ceiling versus a specular
reflection from the floor. Part of the
trade-off involves not seeing any unnec-
essary light. Here’s how that works.

COLLIMATION

According to their datasheets, IR

LEDs and photodiodes have a teardrop-
shaped spatial response: maximum
along the forward axis and falling off
symmetrically around that axis. The
beam width is typically given as the
angle where the response falls to half
of the on-axis peak value measured in
current or power. The actual response
may have spots and lumps, but the
model is a good start.

Common devices use an epoxy

package, perhaps with filter dyes
mixed in to reduce visible light.
Despite the datasheet information,
their response doesn’t fall off to zero
in any direction simply because the
entire package is transparent. The
peak response may be to the front, but
when you shine a light on the side or
back of a photodiode, you’ll definitely
get (at least!) a small response from
light bouncing around inside. When
you’re trying to detect a weak reflec-

tion from the front, any extraneous
light can be devastating.

Eliminating that light involves put-

ting the photodiode in an opaque
enclosure with an opening only in the
forward direction. A simple tube does-
n’t work well because light can enter
from the rear, penetrate the photodi-
ode’s package, and bounce off the
front of the lens. Duct-seal putty, nor-
mally used for sealing air conditioning
equipment, is available at your local
hardware store and blocks light just as
well as it does air.

After you’ve eliminated extraneous

light from the sides and rear, you may
want to concentrate your sensor’s
attention on a smaller spot to the
front. Although you can do this with
lenses, most designers favor simple
collimators because they’re easy to
build, they don’t require focusing, and
they don’t absorb IR.

For a given spot size at a certain dis-

tance, the sensor’s acceptance angle
works out to the following:

When a photodiode’s beam width is
larger than the desired spot size,
which is usually the case, you can put
an aperture or two of the appropriate
size between the photodiode and the
spot. The apertures strip off light out-
side the acceptance angle, so only light
from the spot hits the photodiode. This
reduces the total amount of energy on
the photodiode, but it can dramatically
increase the signal-to-noise ratio.

Typically, you build a simple collima-

tor from a brass tube and shim stock
washers. What most people don’t real-
ize is that you must make the inside
of the tube nonreflective, because IR
entering at an angle that ordinarily
wouldn’t make it through the rear aper-
ture must be absorbed rather than
bouncing around. Flat black paint is
good, but black construction paper is
even better, particularly because you can
make the tube and apertures from the
black paper without a machine shop.

LEDs can be collimated the same way

with the same attention to reflections
inside the tube. You need not seal the
back of the collimator, because you gen-
erally won’t care about light leaks from

arctan

spot diameter

wall distance







background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

43

Ed Nisley, PE, is an electrical engineer
and author living in Poughkeepsie,
New York. You may contact him at
ed.nisley@ieee.org.

an LED. Even with a matched, filtered,
collimated, and aligned optical system,
many robots have trouble finding the
walls. Let’s talk about energy.

DISTANCE

Light sources follow the familiar

inverse-square rule: the power incident
on a given area decreases as the square of
the distance from a point source. A pho-
todiode farther than a few meters away
from a light bulb or a few centimeters
from an LED will follow the rule almost
exactly. Laser beams follow somewhat
different rules and pose different prob-
lems that I won’t consider here.

An LED must put at least as much

power on a given surface as the ambient
light in order to be detected by simple
circuitry. As the signal-to-noise ratio
drops, the circuitry must become more
complex until, at some point, you sim-
ply don’t have enough signal no matter
how clever you are. Many robots get into
trouble because their sensors are either
too sensitive, not sensitive enough, or
sometimes both at the same time.

Sunlight ranges from 100 to 400 W/m

2

and indoor illumination can be 0.1 to
10 W/m

2

. The lighting in Oosting Gym

probably exceeds 10 W/m

2

, although

you can see, with some difficulty, the
spot a visible LED casts on a tabletop
from a few inches away. A typical IR
LED might reach 6 W/m

2

at a distance

of 6 cm, which gives you an idea of
the problem!

The photodiode must detect reflect-

ed, not incident, light, which means it
“sees” all sources that contribute to the
reflection. A Lambertian surface, such
as the walls of the maze, reflects a frac-
tion of all the overhead lights as well as
from the nearby IR LED. That reflec-
tion will be much dimmer than a direct
source, which is why collimation is so
important: you must ensure your detec-
tor doesn’t see anything other than
the desired spot on the wall.

Pop quiz: If an LED illuminates a

maze wall with 6 W/m

2

at 6 cm, what’s

the power level at 24 cm? Answer:
Because the distance increases by a fac-
tor of four, the power drops by a factor of
4

2

to 375 mW/m

2

. The incident power

goes from the high end of indoor illumi-
nation to the low end just by moving
half the width of a maze corridor!

RESOURCES

K. Boone, “Building Organic Robots
with Students: A How-To Lesson,”
Circuit Cellar

128, March 2001.

Filter spectrographic data,
www.amasci.com.

Lee optical filter information,
www.leefilters.com/home.asp.

Sony Electronics, Inc., DSC-F717:
Cyber-shot Digital Still Camera

,

2002, www.sonystyle.com.

Trinity College Fire-Fighting Robot
Contest, www.trincoll.edu/
events/robot/.

Author’s Note: I would like to thank
William Beaty for the e-mail discus-
sion regarding IR filters and for provid-
ing full spectrographic data for some
Lee filters. I would also like to
acknowledge Ken Boone, a Wizard-
class roboticist, for providing hints and
tips. Ken’s article, “Building Organic
Robots with Students,” shows how to
build an organic robot that’s ideal for
classrooms, even if it doesn’t use IR.

Now you know why it’s so important

to eliminate all extraneous light. A pho-
todiode that works under dim light will
saturate in Oosting Gym’s ambient
glare, but, paradoxically, may not be sen-
sitive enough to see across the maze.

CONTACT RELEASE

Everything you’ve seen so far operates

at what’s effectively DC. The LED is
either continuously on or turned on as
needed. Ambient IR and visible light
provide a high background level, and
even high-brightness IR LEDs are dim in
comparison. The signal-to-noise ratio
can be extremely bad and well beyond
the capabilities of simple digital logic.

Next time, I’ll take a look at modu-

lation and detection, which are analog
topics relevant to both RF and IR that
improve the odds of detecting a faint
signal. Stay tuned!

I

background image

an appropriate microcontroller.

I chose the 40-MHz PIC18F258 micro-

controller from Microchip because of its
built-in CAN 2.0B controller, which can
communicate at up to 1 Mbps. Its 32 KB
of on-board flash memory and internal
debugging capability make this an
extremely simple circuit for software
development. The 10 MIPS of processing
power make it capable of transferring
messages back and forth without break-
ing a sweat. (Note that my wife says it
takes me about 3 h to follow one
instruction. So, I’m about 10

11

times

slower. But enough about me.)

The 5-V power for the microcon-

troller comes directly from the USB
cable. Also, because the circuit is so
small, USB Implementers Forum
(USB-IF) recommends that if a device is
light enough not to yank out the cable
when it falls off a desk, you should
attach the USB cable directly to the

board. This helps prevent
lost cables, saves the cost
of the extra connector, and
prevents miswiring.

ADVANTAGES

You’ll find CAN benefi-

cial for several reasons.
First, note that all packets
are filtered for their correct
node ID and others are
ignored. (Firmware isn’t
required, except for setting

44

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

D

o you want the capability to con-

trol numerous microcontroller circuits
from your computer? With this handy
project, now you “CAN.” In conjunc-
tion with fellow designer Dale
Herman, I built an inexpensive circuit
that allows a PC’s universal serial bus
(USB) to interface to a controller area
network (CAN) bus.

When it comes to communication

between multiple microcontrollers, I
cannot think of a nicer interface than
the CAN bus. You may be asking your-
self, why? What’s wrong with RS-232,
RS-485, SPI, or I

2

C? The simple reason

is that if you really need full processor
power, nothing will slow you down
like constant interrupts for every byte
received, not to mention the fact that
the additional software overhead of
packet decoding and checksum check-
ing, ACK NAK schemes, and so on eat
processor bandwidth. The CAN link-
layer hardware handles
many of these issues in
the background.

OK, so what’s the best

choice for communicating
with a PC? Unfortunately,
the PC does not come stan-
dard with a CAN bus, and
some manufacturers are
starting to phase out paral-
lel and RS-232 ports (par-
ticularly on laptops).
However, on the PC side,

Flexible USB-CAN Bridge

When Craig decided that he needed a cost-effective, efficient way to control several micro-
controller circuits from one computer, he used a PIC micro to design a USB-CAN distributed
motion controller. Like many do-it-yourself endeavors, this project was born of necessity, so
it’s inherently inexpensive and easy to follow.

USB has been growing in popularity, and
for good reason: its simple plug-and-play
and high speed make for a great bus.

At first, I was worried about how long

it would take me to develop drivers
for a USB interface. I’m certainly not a
USB expert. That’s when I stumbled
across Future Technology Devices
International’s (FTDI) FT245BM chip,
which is a cost-effective device for
quickly interfacing a microcontroller to
the USB bus with little knowledge of the
USB specification. The FT245BM allows
a transfer speed of up to 1 MBps, and its
384-byte transmit and 128-byte receive
FIFO buffers allow for high data through-
put. A parallel microcontroller interface
allows for the quick transfer of data.

But what about the drivers? No

problem. To my relief, I found out
that FTDI supplies free Windows driv-
ers and example schematics. With my
fear subsided, I pressed on looking for

FEATURE ARTICLE

by Craig Beiferman

6-MHz

Resonator

40-MHz

Oscillator

ICD2

Port

FT245BM

USB FIFO Chip

PIC18F258

Microcontroller

TJA1050

CAN Transceiver

EEPROM

LEDs

CAN Bus

USB Bus

Figure 1—

Several subsystems make up the USB-CAN board. For less than $30, you too

can have a high-speed USB-to-CAN bus.

FIRST PRIZE WINNER

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

45

the FTDI’s drivers. The message’s for-
mat is extremely simple. I sent a 16-
bit identifier (only the lower 11 bits
are actually used). Then, I sent from 0
to 8 bytes of data. The message is byte
stuffed and then sent over the USB.

The byte-stuffed message will arrive

in the FT245BM’s receive buffer. This
in turn causes the ’18F258 to read in
this message. The message is unstuffed
and loaded into the CAN transmit
buffer. The CAN link layer hardware
internal to the ’18F258 continually
transmits this message until another
node acknowledges its reception.

After receiving a CAN message, the

’18F258 reads the CAN receive buffer
into RAM. This data is byte stuffed,
and the message is transferred to the
FT245BM’s transmit buffer. The data sits
in the FT245BM transmit buffer until
the PC’s USB drivers poll the FT245BM
to check to see if it has available data.
This polling is a weak point for USB,
because the USB slave node must wait
for a USB packet to indicate that it is
ready to begin transmission. But, you
probably won’t notice this because the
FTDI’s transmit buffer is so large.

Also, note that the polling rate is

up the message filtering.) In addition,
multiple transmit and receive buffers
hold entire CAN packets (i.e., up to
8 bytes of data and an 11- or 29-bit iden-
tifier). Received messages are checked
for proper CRC, and bad CAN packets
will set error flags for recovery if neces-
sary. All transmitted messages are auto-
matically appended with correct CRC.

Another benefit is carrier sense mul-

tiple access with collision detection
(CSMA/CD). For instance, when two
Ethernet packets collide, both nodes
have to retransmit after a random delay
(yuck!). However, when two CAN pack-
ets collide, the packet with the lower
priority loses, and the original packet
continues to be sent as if nothing had
happened (awesome!). The losing node
will attempt to retransmit automatically
after the other node has completed send-
ing its packet. Firmware isn’t required.

Moving on, note that hardware gener-

ates an interrupt after receiving an
entire message packet. Hardware inter-
rupts on an empty transmit buffer. With
three transmit buffers, you can really
crank out the messages at full speed.

Finally, keep in mind that the CAN

transmitter will continually try to

retransmit automatically until at least
one node acknowledges that its data
packet was successfully received.
Furthermore, the CAN bus trans-
ceivers use differential signals, which
laugh at external noise sources. The
transceiver I used also suppresses tran-
sients on the CAN lines. Ha, ha, ha!

Do you want to learn more? Refer

to the Resources section of this article
if you’re interested in gaining a more
in-depth understanding of CAN.

HARDWARE AND SOFTWARE

The hardware design is actually simple

(see Figure 1). The schematics on FTDI’s
web site show its chips in numerous
configurations. I choose the schematic
with a 5-V microcontroller powered via
the USB bus. After adding a few extra
components like LEDs and the CAN
transceiver, I was finished (see Figure 2).

The software on the PC side works

with the firmware in the microcon-
troller to form a virtual bridge between
the PC and the CAN bus. This is the
master node. All other nodes on the
bus are considered slave nodes.

To send a message to the CAN bus,

the user’s program sends a message via

Figure 2—

A USB bus-powered circuit allows the high-speed microcontroller to easily provide a communications bridge between a PC’s USB and a CAN with up to 127 nodes.

background image

46

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

you to read. The microcontroller TRISC
should be set to 0xFF, so it is an input
port. Toggle RD from high to low to
fetch the next data byte from FIFO. The
FT245BM will put data on the data bus
(D0 through D7). Finally, read port C to
a local variable to fetch data and tog-
gle RD from low to high to return to
the normal state. The FT245BM will
return its data port to high impedance.

CONFIGURING EEPROM

The FT245BM has a serial EEPROM

(Microchip’s ’93C46B) attached direct-
ly to its output pins. The EEPROM
isn’t needed for proper operation, but
if you would like to distinguish your
product from other vendors, it’s used
to store vendor ID (VID) and product
ID (PID), serial numbers, and so on
that are specific to your USB product.

Unfortunately, USB-IF wants to charge

money to rent a VID. Luckily, FTDI will
let you use its VID and give you a few
PIDs to use for your product. When
Windows checks the USB devices, the
PID and VID are used to determine
which drivers are loaded. FTDI also sup-
plies a utility—FTD2XXST.exe—that
allows you to program these variables
into the EEPROM via the USB.

Heed this warning: If you change

the variables, you may have to rein-
stall the drivers because the USB
device won’t be recognized. However,
in order to install these drivers, first
you have to modify the FTD2XX.INF
configuration file. The instructions are
posted on FTDI’s web site.

BYTE STUFFING

After you establish simple byte

communication between the PC and

settable by FTDI’s drivers. This
polling period can drop as low as 1 ms.

INTERFACE TO THE FT245BM

Interfacing to the FT245BM is

straightforward. There are eight bidi-
rectional data lines and four control
lines: RD, WR, TXE, and RXF.

When transferring data back and forth

to the chip, there are two tricks you’ll
need to remember. First, the data bus is
bidirectional, so you must make sure
that both the FT245BM and PIC18F258
data ports aren’t set as output pins at the
same time. Second, you should meet the
timing requirements of the FT245BM
chip when transferring data. (Note that
the ’18F258 has a 100-ns instruction
time. This is code-dependent, so you
should refer to the datasheet.)

There are a few simple rules for inter-

facing to the FT245BM. When RXF goes
low, there is at least 1 byte of data in
the FT245BM’s receive buffer waiting to
be read by the microcontroller. When
TXE goes high, the transmit buffer is
full, so you should stop writing data to
the transmit buffer. Also, when a low-
to-high transition on the RD pin fetches
the next data byte from FIFO, put the
pin low again to have data placed on
the data bus (D0 through D7). A high-
to-low transition on the WR pin writes
what is on the data bus (D0 through
D7) to the transmit FIFO.

When you want to write data from

the microcontroller to the FT245BM,
you cannot write data to the FT245BM
if TXE is high (i.e., the transmit buffer
is full). Set *RD to high (to set the
FT245BM data port to an input port)
and WR high. Also, change the micro-
controller’s TRISC register to 0x00 (to
set port C as all outputs), and
write the data byte you want
to send to port C. Finally, set
the WR line low (a high-to-
low transition writes the
data to the TX FIFO buffer)
and change the microcon-
troller TRISC register to
0xFF (this sets port C as all
inputs, or a safe state).

To read data from the

FT245BM to the microcon-
troller, keep the following
things in mind. If RXF is high,
there is no data available for

PIC, you’ll have to face the problem of
knowing where the real message pack-
ets begin and end. For instance, if a
byte were lost, how in the world
would the firmware resynchronize
with the host?

To solve this problem, I used a

straightforward byte-stuffing protocol:

<DLE><STX>message<CHECKSUM>

<DLE><ETX>

where the two bytes

<DLE><STX> rep-

resent the beginning of transmission
and

<DLE><ETX> represent the end.

The message has an arbitrary length,
and if any byte in the message con-
tains a

<DLE> character, then a second

<DLE> is inserted in the message
stream. The inserted

<DLE> characters

are not included in the

<CHECKSUM>

calculation, and the

<CHECKSUM> is

the XOR of all the characters in the
message. Refer to Figure 3 for an
example of byte stuffing.

Using the simple byte-stuffing proto-

col, you can create a simple state
machine in software to know if you
have properly received a correct mes-
sage. After you have a complete mes-
sage, you can pass the unstuffed mes-
sage to a handler function. Because
both the PC and microcontroller have
this potential synchronization problem,
all of the messages passed between
them are byte stuffed. After I had
worked out the bugs pertaining to the
byte-stuffing and unstuffing functions,
the communications were reliable.

WINDOWS USB DRIVERS

FTDI offers two choices for USB

drivers. (Note that these drivers can-

not be installed at the
same time.) I recommend
using FTDI’s virtual
comport drivers when
you first complete your
hardware design. This
makes the USB port look
like another COM port.
To start a simple
HyperTerminal program,
open a terminal window
and send and receive mes-
sages over the USB just
like you would with any
RS-232 device.

Original message:

A

B

C

Bytes stuffed:

DLE STX

CHKSUM

A

B

C

DLE ETX

A

B

C

Unstuffed:

Message that
contains DLE:

Bytes stuffed:

Unstuffed:

A

B

C

DLE

A

B

C

DLE

DLE STX

A

B

C

CHKSUM DLE ETX

DLE DLE

Figure 3—

You can take a string of characters and byte stuff them so the microcon-

troller and host computer can regain synchronization immediately following a corrupted
message. The included checksum ensures that corrupted messages are not acciden-
tally received.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

47

When you want to get serious, use

FTDI’s D2XX drivers for Microsoft
Visual C++. The drivers let you
exploit the full speed of the USB
device, and they afford you a free (one
of my favorite words) programming
interface on the PC side!

CAN INTERFACE

After getting the PIC to talk to the

CPU via the USB bus, it was time to
turn my attention to the PIC18F258’s
CAN interface. Luckily, Microchip had
much of the firmware already com-
pleted. It was a simple matter to con-
vert this code to the CCS compiler.

Also, because of the complicated

nature of debugging the CAN inter-
face, I used a Microchip ICD2 debug-
ger with good results. Unfortunately, if
you’re a new developer writing CAN
firmware, you’re stuck with a chicken-
and-egg problem. If you don’t already
have a CAN device to read and write
CAN messages, you need to build two
devices to test it. Luckily, I already
had a separate PCI CAN card to which
I could send and receive CAN mes-
sages. And, luckily for you, I’m supply-
ing you with working source code, so
you should be able to send CAN mes-
sages immediately without a problem.
You may download the code from the
Circuit Cellar

ftp site.

I think it is important to explain the

CAN message format that you need to
be concerned with. At first glance, a
CAN message frame format is pretty
complicated:

Idle [SOF][Identifier 11 or

29 bit][RTR][IDE][R0][DLC]
[DATA 0 to 8 bytes][CRC]
[ACK][EOF][IFS] idle

And don’t forget the bit stuffing. The
CAN in Automation (CiA) web site
contains an excellent explanation of
the fields.

A good part of the CAN message is

filled with extra bits, which you need-
n’t concern yourself with. The bits are
used by the CAN hardware to ensure
reliable communications, and they
should not worry you. For basic com-
munications, there are only three
fields that you should be concerned
with: [Identifier], [DLC], and [DATA].

[Identifier] is the address of the node
you want to send the message to
(either 11 or 29 bits). [DLC] is simply
how many bytes are in the data field
(i.e., the data length code valid range,
zero to eight). And, finally, [DATA] is
the 0 to 8 bytes of the data you want
to send. How simple is that?

CAN PHYSICAL LAYER

I used a Philips TJA1050 for the

CAN transceiver. The device is inter-
esting for several reasons. First, the

CAN transceiver (the physical layer)
can output a differential signal of
either a dominant bit (0) or recessive
bit (1). The collision avoidance feature
of CAN comes into play when a node
tries to output a recessive bit and
another node on the bus outputs a
dominant bit. The dominant bit
appears on the bus, and the transceiv-
er that tried to output a recessive bit
will recognize that its output isn’t
correct. Then, the CAN controller, or
link layer, will recognize this condi-

background image

48

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

tion and stop attempting to transmit
its message until the current message
is completed.

With that said, when two nodes

attempt to communicate a message at
the same time, the node that outputs a
dominant bit first has the highest priori-
ty message. Thus, you must be careful
about how they choose to use the 11-bit
(or 29 bits for extended mode) identifier.
The lower the CAN identifier number,
the higher the message priority.

Another thing to note about this

CAN transceiver is that when the
power is off, it will not disturb any
nodes that are running. It is short cir-
cuit proof to V

CC

and to ground. The

bus pins are protected against tran-
sients, which allows for high-speed
traffic up to 1 Mbps and at least
110 nodes to be connected together.

ICD2 INTERFACE

I added a five-pin header to interface

to the debugging port on the PIC
microcontroller. For all of you PIC
fanatics out there, I highly recommend
purchasing the ICD2 debugger. The
simple serial debugger may not pro-
vide lots of breakpoints or advanced
debugging functions like the ICE4000
(not that I really know, the ICE4000 is
a little out of my price range). But the
ICD2’s simple interface makes it easy
to download your latest firmware into
flash memory. Having a couple of real-
time breakpoints in your code seems
to be more than adequate for most
debugging. And, if you are used to
ultravioletly erasing your microcon-
trollers, it’s time to celebrate. Never
again will you have to pry your chip
out of its socket with a small screw-
driver. Just solder in a blank device,

PROJECT FILES

To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2003/157.

RESOURCES

CAN Information, CAN in
Automation Organization (CiA),
www.can-cia.org.

K. Pazul, Controller Area Network
(CAN) Basics

, AN713, DS00713A,

Microchip Technology, Inc., 1999.

USB Information, USB
Implementers Forum, Inc.,
www.usb.org.

SOURCES

CU-742-MB Utilibox
Bud Industries, Inc.
(440) 946-3200
www.budind.com

Compiler
CCS, Inc.
(262) 797-0455
www.ccsinfo.com

FT245BM Interface Chip
Future Technology Devices
International
+44 141 353 2565
www.ftdichip.com

ICD2 Debugger, PIC18F258
microcontroller, and ’93C46B EEP-
ROM chip
Microchip Technology, Inc.
(480) 786-7200
www.microchip.com

TJA1050 CAN Transceiver chip
Philips Semiconductors
(408) 991-3773
www.philips.com

and you never need to worry again. (If
only that were true!)

BOOTLOADER

The next problem arose because it’s

impossible make everyone happy,
which is something I learned in my
previous career as an embedded soft-
ware engineer. So, I designed a boot-
loader program to allow for in-field
downloads of the program via the
USB bus—the details of which are
better left to a future article.

You may download the bootloader

code for the CCS compiler from the
Circuit Cellar

ftp site. Note that it

took about 3 s to download the main
firmware via the USB bootloader. If
you’re used to downloading with the
PICSTART plus, you should let out a
big sigh of relief.

BUILD THE UNIT

Unfortunately, for some of you do-it-

yourself people, the FT245BM comes
only in a surface-mount LQFP-32
package. However, with some careful
soldering and solder wick (for the
inevitable bad soldering), you can hand-
solder this device yourself (see Photo 1).

As you can see in Photo 2, I imple-

mented a CU-742-MB plastic enclosure
from Bud Industries. I had a machinist
make the holes for the four LEDs, the
USB cable, and the D-Sub connector.

Now it’s your turn. Go ahead and

build one yourself! If you want a
jumpstart, kits are available on the
DipChip Electronics web site
(www.dipchipelec.com).

I

Craig Beiferman earned a B.S. in
Electrical Engineering and an M.S. in
Computer Science from the University
of Massachusetts at Lowell. Currently,
he’s a senior electrical engineer at
kSARIA Corp. When Craig’s not at
work, he focuses on running DipChip
Electronics and spending time with
his two children, Zachary and Julia.
You may reach him at craig-
beiferman@dipchipelec.com.

Photo 2—

I had the plastic enclosure machined to

accommodate the board, which is designed to fit in the
box. The four holes in the corners of the PCB line up
with the screw holes in the plastic enclosure. This pro-
vides a secure fit.

Photo 1—

I hand-soldered the board. Note that the

toughest parts to hand-solder are the 40-MHz crystal
and the TQFP-32 package.

background image
background image

Refer to the Resources section of this
article for a few useful links.

I had a difficult time finding

detailed PCMCIA information on the
’Net, but I obtained a lot of useful
information from F. Imdad-Haque’s
book, Inside PC Card: CardBus and
PCMCIA Design

. In addition, you can

download the 802.11b specification
from IEEE (www.ieee.org).

Important aspects of the microcon-

troller include its on-board 32-KB flash
memory and 512-byte RAM. The appli-
cation code resides in the on-board flash
memory. Most significantly for this

50

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

T

he WiFi SniFi, which I pronounce

“wiffy sniffy” for the fun of it, sniffs
out 802.11b wireless networks and
displays captured packet information
(see Photo 1). This little device can
remain quiet on the network or asso-
ciate with an access point and act as a
network node. In Monitor mode, the
WiFi SniFi can listen to a specific
channel or scan all of the channels.

The big news is that the WiFi SniFi

performs these functions without a
high-powered microprocessor. In fact,
one of its main advantages is that it
generates a large amount of function-
ality from its 8-bit, 5-MHz microcon-
troller. Wireless local area networks
(WLANs) operate at much higher
speeds than the microcontroller, but
the WiFi SniFi manages to nab the all-
important management frames. It
even grabs some of the data frames.

Even if you don’t want to nab ‘n’ grab

WLAN frames, you might find some
useful hardware and software nuggets in
the WiFi SniFi that apply to other types
of microcontroller designs. I created the
WiFi SniFi as part of the 2002 Esprit de
KORE contest, which was sponsored
by NEC Electronics America, so the
device is a demo that shows how to
leverage microcontroller resources to
achieve surprising results.

If you savor the kind of minimalist

design techniques that squeeze the most
out of system resources, you might
appreciate this design’s interfaces with
its input switches, PCMCIA card, and
serial EEPROM. You can easily reuse
the software for the PCMCIA interface
in applications that don’t have a suit-

The WiFi SniFi

Are you having trouble locating 802.11b wireless networks? Don’t worry. Roy has the perfect
solution. The WiFi SniFi is a compact, easy-to-build device that can “sniff” out wireless net-
works and display the appropriate packet information.

able PCMCIA interface in hardware,
even if you’re working with some-
thing other than a wireless LAN card.

The design’s user interface may

require some adaptation for other appli-
cations, but it could be useful in a wide
range of designs. The user interface con-
sists of a scroll wheel taken from a
mouse and a single push button. Roll the
wheel to scroll through menu items and
press it to select items. Use a separate
push button to clear entries. The inter-
face is simple, compact, and easy to use.

WHAT’S INSIDE?

The WiFi SniFi couldn’t be simpler

(see Figure 1). Most of the necessary
resources are inside the NEC Elect-
ronics µPD78F9418 microcontroller.
The only major external components
include a 4 × 20 LCD, a 128-Kb EEP-
ROM that’s used for saving captured
WLAN frames and device configura-
tion data, the mouse wheel, and an
Intersil Prism 2-based PCMCIA WLAN
card. These are on a board I built that
attaches to an NEC KORE9418 devel-
opment board (see Figure 2).

You can deliver power to the WiFi

SniFi with batteries, an AC adapter, or
a car cigarette lighter adapter. Either
of the latter two power sources will
charge the batteries. The voltage mon-
itor indicated in Figure 1 is used for
monitoring the battery’s charge state.

The WLAN card acts as a basic

802.11b node. I designed the WiFi
SniFi without formal documentation
for this card, but you can get informa-
tion about it from the various open-
source device drivers available for it.

FEATURE ARTICLE

by Roy Franz

Photo 1—

The WiFi SniFi uses a PCMCIA card to interact

with wireless networks, a small LCD to display packet con-
tents,

and an old mouse scroll wheel to get user inputs.

An 8-bit, 5-MHz microcontroller runs the entire thing.

Sniffing In and Out of Wireless Networks

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

51

channels overlap and inter-
fere with one another, so
only three WLANs can oper-
ate unhindered in one area.

A WLAN can operate in

either Infrastructure mode
(BSS mode, where the net-
work is controlled by an
access point, or AP) or Ad
Hoc mode (IBSS mode,
where there is no access
point). The service set iden-
tifier (SSID) is a string that
identifies a WLAN. Stations
only associate with an AP
(or another station in Ad
Hoc mode) that has the same
SSID. When you turn on a
station such as a notebook

computer with a wireless card, the sta-
tion scans all the channels checking for
a beacon frame that has the station’s
SSID in it. This beacon frame identifies
the channel and the address of the AP
that the station is seeking. If the sta-
tion finds no such beacon frame, it can-
not join any networks, so no wireless
communication is possible.

design, the microcontroller has
43 I/O pins, including multiple
A/D input channels. I used one
of the A/D channels to monitor
battery voltage. If you are used
to working with microproces-
sors, the microcontroller pres-
ents a somewhat different
interface task because it has no
external data or address buses.
Most of the I/Os on this partic-
ular microcontroller are gener-
al-purpose ports, which means
that they adapt to different pur-
poses under software control.

WiFi SniFi CAPABILITIES

To understand what the WiFi

SniFi does, you need to know a
few facts about 802.11b-based WLANs.
These wireless networks operate in the
2.4-GHz frequency range and offer a
maximum physical-layer signaling rate
of 11 Mbps. Although real-world net-
works achieve only 6 or 7 Mbps of
throughput, the data rates are rather
high for a 5-MHz system to handle. In
fact, it is interesting to see how well the

device keeps up, which probably has a
lot to do with the large amount of
buffering the wireless card performs.
With the ability to buffer several dozen
packets in its internal memory, the card
greatly eases the timing constraints of
interfacing to the microcontroller.

The 802.11b networks in the U.S.

can use 11 channels. All but three

Figure 2—

The WiFi SniFi board is designed to mate with the four 20-pin headers that the KORE development board provides. The MAX3222 is used for debugging serial out-

put and providing a negative voltage source to drive the LCD

.

PCMCIA

Card

16-bit Data
6-bit Address
9-bit Control

NEC

Electronics

µPD78F9418

8-bit Data
3-bit Control

LCD

Four switches

Analog in

Input

switches

(wheel,

buttons)

Voltage monitor

(resistor network)

1-bit Clock
1-bit Data

Serial

EEPROM

Figure 1—

The WiFi SniFi consists of few components other than the 8-bit micro-

controller, which implements the PCMCIA interface in software. The microcon-
troller includes a hardware LCD controller/driver. Some of the LCD I/Os are shared
with other devices.

background image

52

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

information displayed varies based on
the type of frame, because not all of the
fields are present in every frame type.

The WiFi SniFi is best adapted for cap-

turing management frames, which are
generally small. The system can save
and display most of the information in
these frames. Management frames
include beacons, probe requests/respons-
es, association requests/responses, reas-
sociation requests/responses, disassocia-
tion, authentication, and deauthentica-
tion. Management frames are often the
most interesting from a network-trou-
bleshooting point of view because
they control the process of joining and
leaving networks.

When it’s monitoring, the WiFi SniFi

displays the current saved frame num-
ber in the upper right corner of the

The WiFi SniFi has two basic modes.

It can find and monitor a wireless net-
work by capturing management and data
frames. Or it can associate with a net-
work, display frames, and respond to
pings and address resolution protocols, or
ARPs, which are named for mapping an
IP address to a physical machine address.

The WiFi SniFi won’t give you Internet

access, but it does enable you to poke
about the landscape to find the WLANs.
You can do so by placing the WiFi SniFi
in Monitor mode and listening for
frames. When frames come in, the WiFi
SniFi displays them on the LCD and
stores them in nonvolatile memory. You
can configure the WiFi SniFi to listen
on a specified channel or scan all of
the channels by selecting channel zero
via the user interface. Because of the
overlapping channels, frames are often
received while listening on a channel
other than the one they were transmitted
on. Most frames do not indicate which
channel they where transmitted on, but
management frames such as beacons
include this information so the stations
know which channel to use.

You can also control the types of

frames that the system displays and
saves. Because data frames tend to be
fairly large, the WiFi SniFi can display
only a portion of their content on the 4 ×
20 LCD. Similarly, the EEPROM stores
only part of each data frame. The type of

LCD. The frame number increments
until the EEPROM is full (containing
255 saved frames). Then, the WiFi SniFi
continues to display frames without
saving them. Use the Clear Captured
Frames configuration menu option to
clear the EEPROM. You can set the
WiFi SniFi to capture or ignore a specific
type of frame, including contention-free
control frames (CF-Ack, CF-Poll, CF-
Ack+CF-Poll, CF-End, CF-End+CF-Ack).

To join a network with the WiFi

SniFi, you must configure two fields
in the configuration menu: the SSID,
which is a string that identifies sta-
tions that are logically on the same
network, and the IP address. Then,
you can select the network node mode
in the configuration menu.

If the WiFi SniFi successfully associ-

ates with the AP, the “link status
change: connected” message will appear
on the LCD. At that point, the WiFi
SniFi is ready to respond to ARPs and
pings. The system displays but does not
capture the received frames. Also, note
that the WiFi SniFi does not support
the WEP encryption that is increasingly
used to secure 802.11b WLANs.

The WiFi SniFi does not need a net-

mask to associate with a WLAN because
the device does not initiate network traf-
fic. The WiFi SniFi has no concept of a
local versus nonlocal IP address. When
a frame is received, the WiFi SniFi
responds to the source MAC and source
IP addresses within that frame.

USING THE WiFi SniFi

Before getting into how some of the

WiFi SniFi’s features work, let’s look
at how you can use them. The WiFi
SniFi has a simple interface consisting

Figure 3—

The linear regulator keeps the power design simple. The Clear switch is a separate switch, while the

other three are part of the mouse scroll wheel.

Switch 0

Switch 1

Down Up

Detent

Detent

Detent

Figure 4—

As you rotate the scroll wheel, two switches open and close to generate the waveforms. Detents are

stopping points on the wheel that you can feel as you rotate it, and both switches are in the high or low state at each
detent. If you analyze which waveform goes high or low first, you can tell which way the wheel is rotating. By detect-
ing wheel-up and wheel-down events, software can iterate through menu items and packet listings on the LCD.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

53

of a Clear button and the ex-mouse
scroll wheel. Pressing the scroll wheel
activates a switch that is used as a
Select button.

If you press the Select button in

normal operation, you’ll enter the
WiFi SniFi configuration menu. Then,
you can roll the wheel up and down
to cycle through the configuration
menu selections. The top line of the
LCD displays the current configura-
tion item, and the bottom three lines
display a short help message. Pressing
the scroll wheel selects the currently
displayed menu option. When you
select an item, you can edit its value.

The way you edit menu items

depends on the context. Sometimes
you select a value from several fixed
choices. Other times you need to enter
a value, such as the SSID or IP address,
in which case, you must change the
value of a character by rolling the
wheel up or down.

Pressing the Select button moves

the cursor one character to the right,
and the Clear button moves left. If you
press the Clear button when the cursor
is all the way to the left, you’ll cancel
the editing of the field. Pressing the
Select button while in the right-most
position accepts the displayed value.
To stop SSID editing, scroll to a space
character and press the Select button.

During normal network node or

monitor operation, the Clear button
clears the LCD, leaving it blank until
the WiFi SniFi has new information to
display. When you browse captured
frames, the wheel selects the frame to
be displayed. Pressing the Select but-
ton toggles between two screens of
frame information, although some
frames have only one screen.

Because the LCD is small, the

screen displays frame information in a
compact manner, using abbreviations
for many fields. You may download a
list of these abbreviations and other
terms from the Circuit Cellar ftp site.
They may prove useful for under-
standing 802.11b-type networks.

In Monitor mode, the top line of the

LCD displays the same information for
all frame types: the type of frame, the
channel that the card was configured
for when the frame was received, the
signal strength, and the frame number

in the captured frame buffer. As you
can see in Photo 1, I labeled the fields
above the LCD. The information dis-
played in the remaining three lines of
the LCD depends on the type of frame
that’s involved. If you configure the
WiFi SniFi to scan channels, it displays
the channel it is listening to each time
the channel changes.

In network node mode, the LCD dis-

plays ARP and ping frames as they are
received. The WiFi SniFi does not save
these frames to the captured frame
buffer. When the status of the wireless
connection changes (i.e., when the
WLAN card associates or disassociates
with an AP), the WiFi SniFi displays a
message indicating the new status.

THE MOUSE WHEEL

The mouse scroll wheel handles

almost all of the WiFi SniFi’s input
needs. Only one other switch is need-
ed to act as the clear input. The wheel
is also extremely easy to design in.

Rotating the wheel opens and closes

two switches (see Figure 3). The wheel
has small detents at regular intervals
that you can feel as you rotate the
wheel. Both switches are in the same
state at each detent (both open or both
closed). In this implementation, I tied

one input of each switch low. I con-
nected the other switch input to the
microcontroller input and pulled it high
with a resistor. As a result, the I/O line
is high when the switch is open and
low when the switch is closed.

The switches open and close at differ-

ent wheel positions; therefore, if you
rotate the wheel at a constant speed,
the switches produce the waveforms
shown in Figure 4. These out-of-phase
waveforms allow you to tell which way
the wheel is rotating. From the detent
marked “Up,” for instance, you’ll know
the wheel is rotating upwards if switch 0
goes high before switch 1.

Figure 5 describes the way I dealt

with the wheel states and transitions.
Note that the 2-bit values for each
state keep track of whether the state
machine has found a detent or is wait-
ing for one; these values do not reflect
the values of the wheel switches.

Aside from the initial state, the state

machine includes three operating
states. The first state, Detent Found,
involves waiting for a move (11). When
you enter this state, you save the value
of the switches, so you can tell whether
or not a complete move has occurred.
The value also helps detect missed
transitions. After exiting the state, save

01

11

00

10

Waiting for Detent state

Switc

h

0

=

Sw

itc

h

1

Detent

Found

state

Moving state

Waiting for move to complete

Initial

state

Deten

t

b

it

W

he

el

1

(

s

ave

de

ten

t

va

lu

e)

S

witc

h 1

Swi

tch

0

S

w

itc

h

==

S

w

i

t

ch

=

= d

et

ent-bi

t

Switch

1

S

w

it

c

h

0

dir-bit

w

he

el

1

(s

a

ve

dir

bi

t

)

*

R

et

ur

n

w

he

el

up

o

f

w

he

el

do

w

n

bit 1

bit 0

Switch 0 == Switch 1

detent bit

Note: Actions performed on transitions are in parentheses. Names match source code.

Figure 5—

The state diagram describes the way software handles inputs from the scroll wheel. As soon as the

software state machine detects a valid wheel-up or wheel-down event, the software looks for the next event.

background image

54

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

one of the switch values so you know
which way the wheel is moving.

The second state, Moving, entails

waiting for a move to end (10). A move
is complete when you reach another
detent. If you return to the same
detent, you might have only rocked
the wheel slightly, or you could have
missed several transitions. If you reach
another detent and a move is complete,
return the correct action code and tran-
sition to the third state, Waiting for
Detent. Even though you reach a
detent, the calling code may do some-
thing as a result of returning an action
code. So, to be on the safe side, look for
a new detent when you are called again.

The Waiting for Detent state involves

waiting for both switches to have the
same value. When they do, transition
to the Detent Found state. Even if you
find a detent when you leave a state
(10), you need to wait for another
detent because a significant amount of
time may have passed since you left the
previous state. Finally, note that the
initial state (00) allows the state
machine to operate properly with the
state variable initialized to zero.

The state machine tracks changes in

a way that includes error checking.
The machine waits for a detent after
detecting a move to make sure the
move ended. After a move, if the wheel
ends up back in its previous state, the
state machine returns no action. If the
move generates a different value, the
machine returns a wheel-up or wheel-
down event so software can appropri-
ately iterate through the menu items.

Software polls the wheel switches

to detect changes, and the polling
must occur often to keep up with
rapid wheel movements. The wheel’s
Select switch activates an interrupt.
Listing 1 shows the code associated
with the scroll wheel.

PCMCIA INTERFACE

The microcontroller in the WiFi

SniFi interfaces to the WLAN PCM-
CIA card via the microcontroller’s
general-purpose I/Os (see Figure 6).
The same is true for the I

2

C interface

to the serial EEPROM. Therefore, I
implemented these interfaces in soft-
ware. Listing 2 shows the code for the
PCMCIA interface. The code is suit-

Listing 1—

The code that implements the state machine shown in Figure 5 uses polling to obtain the con-

dition of the scroll wheel switches. The code uses an interrupt for the WiFi SniFi’s Select button. It’s the
only interrupt in this design.

//Get button (and switch) state, debounce inputs

bs = pollButtons();

//bs.WHEEL0 bs.WHEEL1 are the

wheel switch inputs

//State machine for scroll wheel (four possible states)

if (GS_WHEEL_STATE_1_BIT)

{

if (GS_WHEEL_STATE_0_BIT)

{

//State 11: Detent Found, waiting for move, which is indicated by

the two wheel switches having different values

if (bs.WHEEL1 != bs.WHEEL0)

{

GS_WHEEL_STATE_0_BIT = 0; //Go to state 10

GS_WHEEL_DIR_BIT = bs.WHEEL1; //Save direction

}

}

else

{

//State 10: Moving and waiting for move to complete. Move is

complete when both wheel switches are the same value (i.e., you

have reached another detent), and this value is different from
the previous detent value. If it’s equal to the previous detent,

you’ve either missed some events or the user only slightly moved

the wheel, and let it return to the original detent.

if (bs.WHEEL1 == bs.WHEEL0)

{

//Either go to Waiting for Detent (if you detect a move) or

waiting for a move (if you’re back at the original detent)

GS_WHEEL_STATE_0_BIT = 1;

if (!(bs.WHEEL1 == GS_WHEEL_DETENT_BIT))

{

//You’ve moved, so take action, and set the next state to Waiting

for Detent. Even though you’re at a detent, you will likely

have work to do, which will delay your next poll of the switch

states. If the wheel is being scrolled quickly, you may miss

many transitions.

GS_WHEEL_STATE_1_BIT = 0;

//Go to state 01

//Move complete. Action!

if (GS_WHEEL_DETENT_BIT == GS_WHEEL_DIR_BIT)

return(BA_wheelUp); //Wheel

up

else

return(BA_wheelDown);

//Wheel down, or else

go to state 11

}

}

}

}

else

{

if (GS_WHEEL_STATE_0_BIT)

{

//State 01: Waiting for Detent. When wheel is in a detent

position, both wheel switches have the same value.

if (bs.WHEEL1 == bs.WHEEL0)

{

GS_WHEEL_STATE_1_BIT = 1;

//Go to state 11 and

save detent value

GS_WHEEL_DETENT_BIT = bs.WHEEL1;

}

}

else
{

(Continued)

background image
background image

56

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

able for reuse in any application that
involves a PCMCIA card.

You may download a list of the sig-

nals in the PCMCIA interface from the
Circuit Cellar

ftp site. The PCMCIA

interface is asynchronous, so the micro-
controller works well as the timing mas-
ter for the I/O bus. After looking at the
PCMCIA timing diagrams, I initially
thought that I wouldn’t need delays in
the read and write routines, but I found
it necessary to poll the *HWAIT line.
The polling loop probably exits after the
first time the *HWAIT signal is polled,
because putting a few NOPs in place of
the polling loop also worked reliably.

To put the card into I/O mode, you

need to set the COR register appropri-
ately, because all PCMCIA cards power
up by default in Memory Only mode.
Because I had hard-coded the COR reg-
ister address, I did not need to read the
information from the attribute memo-
ry to determine its location. To put the
card in I/O mode, however, I found
that I had to read the COR register
before writing it. As a result, the OE
signal had to be connected and used for
the attribute memory read operation.

I also discovered during the course

of development that I did not need to
change the signals (*CE1 and *CE2)
that control whether a bus access is for
the high byte, low byte, or both. I can
tie the signals low because I am always
performing 16-bit accesses. Even though
attribute memory is only 8 bits wide,
16-bit accesses ignore the upper 8 bits.

Implementing an 8-bit PCMCIA inter-

face would have reduced signal count
only minimally and would have compli-
cated the development. The WLAN card
is documented to support 8-bit interfac-
ing, but I could not find information on
implementing the 8-bit option. Many of
the card’s internal buffers use autoincre-
menting of 16-bit addresses, so 8-bit
operations on the registers would raise
special cases. Implementing an 8-bit
interface also requires the use of *CE1,
*CE2, and A0, which is always zero
because all of the accesses are 16 bits.
Thus, the total interface width would
only decrease by 5 bits.

Although the WLAN card decodes

10 address lines, six suffice for access-
ing all of the addresses required to
operate the card, with the exception of

Listing 1—

Continued.

//State 00: initial state of state machine. This state is not

necessary, but it’s implemented so that all possible state

values are handled properly. It’s used at startup because the

global state variable is initialized to zero, and this way you

don't have to initialize it to a special value. Go to state 01

Waiting for Detent.

GS_WHEEL_STATE_0_BIT = 1;

}

}

return(BA_noAction); //If you make it here, nothing has happened.

Listing 2—

A direct interface between an 8-bit microcontroller and a PCMCIA card is a rare thing, especially

when the interface does not use any PCMCIA byte operations. The code shown here implements the entire
interface using the microcontroller’s general-purpose I/Os.

//Perform a 16-bit read of I/O space @param addr address to read

from @return value read from card

__callt norec unsigned int ioRead(unsigned char addr)

{

unsigned int temp;

//Configure K0 data port to Input mode

DATA_H_PORT_MODE = INPUT_PORT;

DATA_L_PORT_MODE = INPUT_PORT;

//Set up address

ADDR_0_3_PORT = addr;

ADDR_4_5_PORT = (ADDR_4_5_PORT & ~ADDR_4_5_PORT_MASK) |

((addr>>4) & ADDR_4_5_PORT_MASK);

//Move these to one register. REG- could be an OR of CE1- and

CE2-, as REG is low during both I/O cycles and attribute memory

cycles. Can REG- be tied low? Reg, ce* can be set low at the

same time the address is presented.

hreg, ce1, ce2 low

#if 0

//CE1- and CE2- signals are always low, so you only perform 16-

bit accesses

CE_1_PORT_BIT = 0;

CE_2_PORT_BIT = 0;

#endif

REG_PORT_BIT = 0;

//REG- may also be able to be tied

low, not checked

//Set IO read low.

IORD_PORT_BIT = 0;

#ifndef PCMCIA_SIM

while (!HWAIT_PORT_BIT);

//Wait for hwait- high

#else

NOP();

NOP();

NOP();

#endif

//Read data

temp = DATA_H_PORT;

temp = temp << 8;

temp |= DATA_L_PORT;

IORD_PORT_BIT = 1;

//reg/ce1/ce2 high

#if 0

CE_1_PORT_BIT = 1;

CE_2_PORT_BIT = 1;

#endif

REG_PORT_BIT = 1;

return(temp);

}

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

59

to handle the sharing with greater care.

The WiFi SniFi uses only one inter-

rupt line, and it’s for the Select but-
ton. I wanted the button to be respon-
sive to user inputs without continual
high-frequency polling. That leaves
the main loop free to continuously
poll the WLAN card, and it does so at
a high enough frequency to keep up
fairly well with the packets.

The other switch inputs—the wheel

and Clear—are polled fast enough to
be responsive after the WiFi SniFi is
in Menu mode. Therefore, they do not
need to be interrupt-based.

EXPANSION POSSIBILITIES

Every design leaves you wishing you

could do more. For the WiFi SniFi, it
would be nice to include a simple state-
less TCP Internet server for downloading
captured frames to a PC. Additionally,
you could use the microcontroller’s seri-
al port for interfacing to a GPS receiver,
so the WiFi SniFi could automatically
record the location of wireless networks.

The WiFi SniFi’s power management

could be improved with a switching
regulator and microcontroller-managed

the COR register in attribute memory.
Because the register access is the only
operation that needs the top four
address bits, I tied the lines to the val-
ues required to access the COR register.
Even though I connected the A0 line to
the microcontroller, the connection is
unnecessary because the 16-bit-only
accesses make all of the addresses even.

If you want to support generic PCM-

CIA cards, you’ll need more address
lines to parse the card information
structure (CIS) in attribute memory so
you can determine the card capabilities
and the COR register location. For the
WiFi SniFi, I determined the COR regis-
ter address in the Linux development
environment and hard-coded the address
in the WiFi SniFi implementation.

The PCMCIA interface’s high pin

count did not pose a big problem,
because I reused most of the signals for
interfacing to other peripherals. For
instance, 10 of the 11 bits in the LCD
interface are shared with the PCMCIA
data bus. Polling the PCMCIA card
eases the resource sharing. You could
still share interface pins in an inter-
rupt-driven design, but you would have

power supply for the PCMCIA card.
(The design’s linear regulator is simple
but inefficient.) The PCMCIA card is
by far the system’s largest power drain,
so turning off the card while browsing
captured frames would greatly
improve battery life.

In a similar vein, the WiFi SniFi

could use a more sophisticated charg-
ing circuit. The microcontroller’s ana-
log input could monitor battery tem-
perature with a thermistor (along with
the voltage monitoring currently
implemented) to enable faster charging.

In addition to specific WiFi SniFi

improvements, the device’s core func-
tionality could be developed into a
platform that allows for the addition
of wireless networking to a variety of
microcontroller-based designs. As the
WiFi SniFi project proves, you can go
wireless with a surprisingly small
amount of hardware.

I

Figure 6—

The PCMCIA interface connects directly to the µPD78F9418’s I/O pins. The data bus lines are used for

both the PCMCIA interface and the LCD, which works because they both have separate enable signals.

SOURCES

PRISM 2 WLAN Card
Intersil Corp.
www.intersil.com

µPD78F9418 Microcontroller
NEC USA, Inc.
www.necus.com

Roy Franz earned a B.S. in Computer
Science from the University of
California, Davis. He’s been developing
software for embedded systems for
more than 10 years. His technical inter-
ests include low-level code that inter-
faces with hardware as well as systems
that interact with their environment.
When time permits, Roy enjoys hiking
and rollerblading. You may contact
him at rfranz@beartreedesign.com.

PROJECT FILES

To download the code and addi-
tional files, go to ftp.circuitcellar.
com/pub/Circuit_Cellar/2003/157.

RESOURCES

F. Imdad-Haque, Inside PC Card:
CardBus and PCMCIA Design

,

Butterworth-Heinemann, Newton,
MA, 1996.

Host AP driver information
hostap.epitest.fi/

background image

60

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

“E

ffective April 1, 2003 Hitachi

Semiconductor America has merged
with the system LSI operations of
Mitsubishi Electric U.S. and created
Renesas Technology America, Inc.”

Hmm, that wasn’t exactly what I

had expected when I first attempted to
access Hitachi’s web site. Upon further
investigation, I found that Hitachi and
Mitsubishi had reached an agreement
more than a year ago to integrate their
LSI businesses. Utilizing the core
strengths (e.g., microcontrollers, logic,
analog, and discrete devices) of both
companies, the new enterprise plans to
concentrate on the mobile, network,
automotive, and digital home elec-
tronics markets.

Renesas is organized into three areas:

MPU, SoC, and SiP; mixed-signal, RF,
and discrete devices; and flash memory
and SRAM. The MPU line includes
Hitachi’s 4-, 8-, 16-, and 32-bit micro-
computers. The H8/SuperH family of
microcontrollers touts upward code
compatibility throughout the entire fam-
ily. Smack dab in the middle of the fami-
ly stands the H8 8- and 16-bit devices.

This month, I will spotlight a num-

ber of devices within the H8 family.
With this information, you will be able
to make some sense out of the vast sea
of Renesas devices. You’re sure to find
this information to your advantage if
you’re planning on entering a project
in the Renesas H8 Design 2003:
Everywhere You Imagine contest.

cuit. The devices also include low-cost
emulators that are available for real-time
debugging when you’re using resources
built in the target hardware.

The H8 family was designed for

low-power, high-performance embed-
ded systems in the consumer, indus-
trial, medical, communication, and
automotive markets. The family
ranges from the 8-bit low-cost, low
pin count, super low-power devices up
to the latest 64-bit, high-performance
devices (see Figure 1). In this column,
I’m concentrating on the 8- and 16-bit
MCUs in the H8 family and leaving

Spotlight on the Renesas H8 Family

FROM THE BENCH by Jeff

Bachiochi

MEET THE H8 FAMILY

The H8 selection guide has nearly

350 different microcontrollers to
choose from. Trying to choose the
right device for your application is
such a daunting task that you may be
inclined to look elsewhere. To help
whittle down the giant H8 oak, I’ll
show you how a few typical devices
stack up against one another.

The devices I’ve chosen are all avail-

able with flash memory. You’ll find that
advantageous when developing applica-
tions because you can change the code
and update the device even when in-cir-

Whether you design medical, communications, or automotive components, you’re sure to
find numerous applications for Renesas Technology’s H8 family of devices. So, before you
begin your next project, you should familiarize yourself with the company’s vast suite of H8
products. To do so, take a look at Jeff’s comprehensive survey of the H8 family members
and their specs.

H8 MCU Family

H8/300L

8 MHz

Low power

H8/300 SLP

8 MHz

LCD

Super-low power

H8SX

High performance, low power, wide range of peripherals

H8 Tiny
20 MHz

Low pin count

CAN, POR, LVD

H8/300H

25 MHz

Motor control

32 bit

16 bit

8 bit

Peformance/features

Upw

ard co

de-com

patiab

le

H8S/2200

20 MHz

LCD, USB

H8S/2300

33 MHz

General

purpose

H8S/2600

33 MHz

Automotive

applications

H8S/2100

20 MHz

LPC/ISAI/F

Figure 1—

Be sure to study the performance versus features lineup of the H8 family of MCU/MPUs. Although the

natural technological progression is for bigger, better, and faster devices, these are not reasons to choose only
from the newest devices for a particular design.

Hitachi and Mitsubishi Market MCUs for Embedded Systems

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

61

the high-performance 32- and
64-bit SuperH group for
another time.

Renesas combines fast

MCU speeds, ROM or flash
memory, power-down modes,
low EMI, and a convenient
development environment
with more than 100 different
on-chip peripherals. As a
result, the H8 family is one
of the industry’s best cost-
per-performance values. A
few of the industry-standard
interfaces that are supported
include UART, SPI, I

2

C, IrDA,

CAN, and smart card.

FAMILY ARCHITECTURE

The H8 uses a general-reg-

ister architecture that con-
sists of control and general-
purpose registers (see Figure 2).
The entire family has
57 basic instructions that
treat the general registers as
both data and address regis-
ters. The eight general-purpose 16-bit
wide word registers (R0 through R7)
are accessed as eight high-byte and
eight low-byte registers (R0H through
R7H, and R0L through R7L). The last
register, R7, serves as the stack point-
er that controls the stack space.

The control registers include a 16-

bit program counter (PC) and an 8-bit
condition code register (CCR). The
PC’s least significant bit is ignored for
all instruction fetches because every-
thing is based on 16-bit instructions.
The CCR holds the status of operations
except for the interrupt mask bit (I).
Upwardly compatible family members
add extra functions to the basic CPU
(i.e., 32-bit double-word registers).

The 16-bit values are stored MSByte

first on the even address boundaries. The
H8 family uses eight addressing modes:
Direct; Indirect; Indirect with displace-
ment; Indirect with postincrement or
predecrement; Absolute; Immediate;
PC Relative; and Memory Indirect.

In Direct mode, the register field

of the instruction specifies an 8- or
16-bit general register containing the
operand (MOV R0, R1). Indirect mode
has the register field of the instruction
specifying a 16-bit general register

containing the address of the operand
in memory (MOV R0, @R1).

The Indirect with displacement

mode is similar to Indirect mode.
However, a second word (bytes 3 and 4)
contains a displacement that is added
to the content of the specified general
register to obtain the operand address
in memory (MOV R0, @(2:16,R1).

Indirect with postincrement or pre-

decrement mode is also similar to the
Indirect mode, but the general register
containing the operand is either incre-
mented after the instruction is execut-
ed or decremented before the instruc-
tion is executed. Byte registers increase

and decrease by one. Word reg-
isters increase and decrease
by two (MOV R0, @-R1).

In Absolute mode, the in-

struction specifies the absolute
address of the operand in
memory (MOV R0, H’FF00’:
16). Immediate mode uses the
8- or 16-bit value within the
instruction as the operand
(MOV #H’1000’: 16,R1).

When the program flow is

interrupted by a branch
instruction, the new PC value
is based on the old PC and a
displacement. PC Relative
mode allows branching by
byte or word displacements
(BEQ @(+10:16,PC)). Jump
instructions can use Memory
Indirect mode, in which the
instruction holds the absolute
address of a location where the
operand is located in memory
(JMP @@(#H’0010’: 16)).

The H8/300L MCU has

57 instructions including mul-

tiply (byte × byte) and divide (word/
byte). Table 1 separates these into their
respective functions. There are four
basic MCU states. Figure 3 shows how
these states relate to one another.

Any state applying power or activat-

ing the hardware reset can place the
MCU in the reset state. When released
from reset, state transfer can only go
to the exception handler state, which
can execute priority code and transfer
control to the program execution state
or place the MCU back in reset state.

The normal code execution is per-

formed in the program execution
state. From the program execution

E0

E1

E2

E3

E4

E5

E6

E7

R0H

R1H

R2H

R3H

R4H

R5H

R6H

R7H

R0L

R1L

R2L

R3L

R4L

R5L

R6L

R7L

15

0

7

0

7

0

(SP)

31

15

0

H8/300L
H8/300L SLP

H8/300H
H8/Tiny

PC

23

15

7

0

0

7

CCR

EXR

63

41

330

Sign extension

MACH

MACL

MAC

31

(only H8S/26xx)

0

H8S/2100
H8S/2200
H8S/2300

H8S/2600

Figure 2—

The H8 family CPU is register-based. The general registers can be used

as data and address registers. The control registers include a 16-bit program PC
and a CCR. Note that upwardly compatible devices add to this base architecture.

Function

Instructions

Number

Data transfer

MOV, PUSH, POP

3

Arithmetic operations

ADD, SUB, ADDX, SUBX, INC, DEC, ADDS, SUBS, DAA

14

DAS, MULXU, DIVXU, CMP, NEG

Logic operations

AND, OR, XOR, NOT

4

Shift

SHAL, SHAR, SHLL, SHLR, ROTL, ROTR, ROTXL, ROTXR

8

Bit manipulation

BSET, BCLR, BNOT, BTST, BAND, BIAND, BOR, BIOR

14

BXOR, BIXOR, BLD, BILD, BST, BIST

Branch

BCC, JMP, BSR, JSR, RTS

5

System control

RTE, SLEEP, LDC, STC, ANDC, ORC, XORC, NOP

8

Block data transfer

EEPMOV

1
Total: 57

Table 1—

Although POP and PUSH are available instructions, they are identical to a MOV using indirect with

postincrement or predecrement addressing (i.e., MOV.W R0, @-SP).

background image

62

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

state, control can transfer to the
reset state, exception state, or
program halt state. The program
halt state has various power-
reduction modes and can only
transfer to the reset state or the
program exception state.

H8 SERIES OPTIONS

The entire H8 family is based on

the aforementioned CPU architec-
ture, and it is divided into a series
of devices with similar purpose.
Each series contains devices with differ-
ent peripherals. Each device is available
with varying memory size and type.

Take a look at the differences in the

flash memory devices listed in Table 2.
Each device was chosen from one of
four different H8 series. Table 3 lists
the special features of each series as well
as a few sample applications that may be
appropriate for devices within the series.

To save space, I combined function

diagrams of the devices into one chart
(see Figure 4). Use the chart to learn
how the devices stack up function for
function. As I describe each device,
refer to Figure 4 and the combined
memory map in Figure 5.

H8/300L SLP SERIES

The H8/300L super low-power series

runs on reduced voltage (some devices
down to 1.8 V). Most are in the 3- to 5-V
range. Multiple power-down modes,
module standby, dual clocks, and fast
oscillator stabilization times help reduce
power consumption to a minimum. On-
chip LCD drivers and an internal voltage
booster simplify external LCD interfac-
ing. High-current output can drive LEDs
without an external current driver.

The 300L SLP includes several

peripherals: 8- and 16-bit multipur-
pose timers, an asynchronous event
counter, 10-bit PWM, a serial commu-
nications interface, a watchdog timer,
and a 10-bit A/D converter. The low-
power consumption and LCD drive capa-

bility make the device ideal for battery-
powered hand-held applications that
require a customized or standard LCD.

If you require long battery life, you

can reduce current consumption by
placing the micro in Sleep mode. Power
is a function of the amount of time
the micro spends in Operating mode
between sleep cycles. In many applica-
tions, the oscillator stabilization period
is longer than the actual time of code
execution before going back to sleep;
therefore, it’s a major factor in current
consumption. The oscillator stabiliza-
tion time for the SLP series is on the
order of microseconds as opposed to
milliseconds, so it can save precious
power at each wakeup.

There are three clock speeds for pro-

gram execution. In Active High Speed
mode, the CPU and all of the on-chip
peripheral functions are enabled, and
execution occurs via the system
clock. In Active Medium Speed mode,
the CPU and all of the on-chip periph-
eral functions are enabled, and execu-
tion proceeds via a divided system
clock. Finally, the CPU executes from
the subclock in Subactive mode.

The sleep instruction has seven pos-

sible power-down modes. Sleep in
High Speed mode halts the CPU while
the on-chip peripherals function via the
system clock. Sleep in Medium Speed
mode stops the CPU while the on-chip
peripherals functions via the divided
system clock frequency.

Subsleep mode freezes the CPU

while the time base function of
TimerA, TimerC, TimerF, TimerG,
SCI, AEC, and the LCD con-
troller/driver operate on the sub-
clock. In Watch mode, the CPU
halts, and the time base function
of TimerA, TimerF, AEC, and the
LCD controller/driver operate on
the subclock.

In Standby mode the CPU and

all of the on-chip peripheral func-
tions are paused. Module Standby

mode allows individual on-chip periph-
eral functions specified by software to
enter Standby mode.

A number of I/O bits are responsible

for setting the MPU’s programming
mode. In User mode, flash memory pro-
gramming is handled via user program
control by 1- and 28-KB erasures and
128-byte block writes. In Programmer
mode, the MPU is programmed using
a PROM programmer.

In Boot mode, boot code is executed

that uses the UART (TX/RX) to com-
municate with an external host pro-
gram. The boot code auto bauds on
incoming data (H’00’), and acknowledges
and erases the flash memory. (Note that
the data rate is automatically deter-
mined by analyzing the datastream via
the auto baud process.) The host indi-
cates the length of the code (word) it
wants programmed followed by the data.
After all of the data has been acknowl-
edged, the MPU can reset to User mode
for user program execution.

H8/TINY SERIES

The H8/Tiny series has an internal

16-bit architecture that runs on 3 or
5 V. (An internal step-down unit is used
when 5 V is supplied.) The general
registers are increased to 32 bits wide
(double word), which can be used as
16/16-bit registers, 8/16-bit registers,
and 16/8-bit registers.

Additional functions were added to

the basic H8 instruction set to make

Reset state

Exception-handling state

Program halt state

Program execution state

Reset

occurs

Interrupt

occurs

Exception-

handling

complete

Interrupt

occurs

Reset

occurs

Reset

cleared

Reset

occurs

Sleep instruction

executed

Figure 3—

The MC has four states. Now you know where execution

can be transferred between states.

H8 Series

Device

CPU

Pins

Speed (MHz)

Instructions

RAM

Flash memory

Address space

300L

38024

8 bit

80

8

55 (57)

1 KB

32 KB

64 KB

H8 Tiny

3687

16 bit

64

20

62 (64)

4 KB

46 KB

64 KB

300H

3048B

16 bit

100

25

62 (64)

4 KB

128 KB

16 MB

H8S

2329

16-bit static

120

33

63 (65)

32 KB

384 KB

16 MB

Table 2—

The four devices represent a sampling of the wide range of technology available within the H8 family.

background image

MOTOROLA

and

the

Stylized

M

Logo

are

registered

in

the

U.S.

Patent

and

Trademark

Office.

All

other

product

or

service

names

are

the

property

of

their

res

pective

owners.

©

Motorola,

Inc.

2003.

This

product

incorporates

SuperFlash®

technology

licensed

from

SST

.

DURACELL

and

the

colors

copper

and

black

as

applied

to

a

battery

are

registered

trademarks

of

The

Gillette

Company

and

are

used

with

its

permission.

• High-performance 8-bit HCS08 CPU core (up to 20 native MIPS)
• Innovative on-chip trigger and trace debug interface
• Integrated third-generation .25 micron Flash memory
• Extensive serial communication with 2 SCIs, 1 SPI, and 1 I

2

C

• 10-bit analog-to-digital converter down to 1.8 V
• Up to 8 programmable timer channels w/ center- or edge-aligned PWM

• MC9S08GB60 demonstration board

– Battery-operated with dual RS232 serial ports, switches, LEDs,

small prototype area, and demonstration code

• Modify demo code or develop new code, program and debug using

free CodeWarrior

®

Development Suite for HC(S)08 Special Edition

through DB9 serial port and included cable

MC9S08GB & GT FAMILY KEY FEATURES

NOW AN 8-BIT MCU THAT’S

BIG ON PERFORMANCE,

LONG ON BATTERY LIFE.

We’ve expanded Motorola’s family of 8-bit

MCUs with new additions that operate down to

1.8 V – without sacrificing performance one

bit. Taking advantage of multiple power

management modes – a 20 nA power-down

mode and auto wake-up timer mode – the new

HCS08 MCUs are designed to get the most out of any

battery. They also come with innovative on-chip trigger

and buffer debug hardware, and can be combined

with Processor Expert

TM

auto-code generator. All

that with performance as fast as 50 ns minimum

instruction cycle at 20 MHz bus. And you’ll speed

your time to market, because the HCS08 family is

compatible with all Motorola

analog and sensor products.

Big-time performance and

longer battery life – our HCS08

Developer Kit has the tools and information you need to put that powerful combination

to work for you today. Learn more now at motorola.com/mcu

HCS08 Developer Kit

HCSO8 EXTENDS BATTERY LIFE

background image

64

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

use of the 16-bit architecture. These
include signed multiply and division,
byte-to-word and word-to-double word
sign extension, as well as software inter-
rupt vectors (TRAPA). Multiple power-

down modes, module standby, dual
clocks, and fast oscillator stabilization
times help reduce power consumption.

High-current output can drive LEDs

without an external current driver.

Peripherals for this device include a
real-time clock, 8- and 16-bit timers,
PWM, UARTs, I

2

C, and a 10-bit A/D

converter. The H8/300H series is suit-
able for home appliances and electron-
ics, small DC motor control, the
mechanical control of office machines,
and automotive control modules.

Dual synchronous/asynchronous

UARTs and an I

2

C interface (master/

slave) give the ’3687 plenty of commu-
nication power. There are eight analog
inputs to the 10-bit ADC. A conver-
sion takes a maximum of 134 clock
cycles. Single and continuous conver-
sions are handled on a single- or mul-
tiple-channel basis. Power-on reset, a
watchdog timer, and low-voltage
detection circuitry help keep the
MCU’s operation stable.

Two clock speeds are available for

program execution. In Active High
Speed mode, the CPU and all of the
on-chip peripheral functions are
enabled, and execution occurs via
the system clock. The Subactive
mode has the CPU executing from
the subclock.

Table 3—

I’ve decided to highlight four groups within the H8 family. Designed with specific features, each series is

aimed at a particular market segment.

H8 Series

Special features

Applications

38024

Super-low power

Utility meters

LCD Drive

Glucose meters

Low EMI

Bar code scanners

High EMS

Battery-powered security devices

Single-supply flash memory

HVAC
Home electronics

3687

Low pin count

Kitchen appliances

Small packages

Home electronics

Single-supply flash memory

Automotive control systems

POR

Motor controllers

LVD
CAN

3048B

External SRAM bus

HVAC

DMA Controller

Industrial control systems

Single-supply flash memory

Motor controllers

Motor control unit

2329

Smart card interface

Label printers

Single-supply flash memory

CD R/W Drives

DMA Controller

GPS Systems

On-chip debugger

Blood oxygen monitors
LAN Hubs

JK

microsystems, Inc.

Visit us on the web www.jkmicro.com

Call 530-297-6073 Fax 530-297-6074

Tools

to

Move

Data

µFlashTCP-EP

*

10Base-T Ethernet

2 Serial Ports

7-34 VDC

Optional I/O Interface

Rugged Enclosure w/

Industry Standard

Connectors

Starts at

$229

LogicFlex

*

10Base-T Ethernet

2 Serial Ports

46 Digital I/O’s

Programmable Xilinx CPLD

Hardware Clock/Calendar

Expansion Bus for

Peripheral Boards

Starts at

$189

Dual-E

*

2 Ethernet Ports

2 Serial Ports

3 Counter / Timers

5 Digital I/O’s

Onboard Connectors

USNET TCP/IP

Software in Kits

Starts at

$199

TCP/
IP

Solutions

All products based on the Intel 386Ex with DOS and NE2000 compliant, 10Base-T Ethernet. Standard
memory includes 512K RAM

&

512K Flash plus DIP socket to accept an M-Systems DiskOnChip.

Development systems contain necessary hardware and software tools for fast development.

1403 Fifth St., Suite D

Davis, CA 95616 USA

JK microsystems connects you with embedded control solutions. Our cost-effective DOS based
controllers are ideal for data acquisition, networking or industrial technology applications.

*

LogicFlex-EPX

*

10Base-T Ethernet

2 Serial Ports

16 Opto-Isolated inputs

16 Relay Outputs

@

500mA ea.

Quick-Disconnect Connectors

Rack Mount Enclosure

LCD

&

6 Pushbuttons

Starts at

$499

NEW

Products

background image
background image

66

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

The sleep instruction has

six possible power-down
modes. Sleep in High Speed
mode halts the CPU while
the on-chip peripherals func-
tion via the system clock.
Subsleep mode halts the CPU
while the time base function
of TimerA, TimerC, TimerF,
TimerG, SCI, AEC, and the
LCD controller/driver operate
on the subclock. In Watch
mode, the CPU stops, and the
time base function of
TimerA, TimerF, AEC, and
the LCD controller/driver
operate on the subclock. In
Standby mode, the CPU and
all on-chip peripheral func-
tions freeze. Module Standby mode
allows individual on-chip peripheral
functions specified by software to
enter Standby mode.

A number of I/O bits are responsible

for setting the programming mode for
the MPU. In User mode, flash memory
programming is handled under user pro-
gram control by 1-, 8-, 16-, and 28-KB

block erasures in addition to 128-byte
block writes. Note that this is similar
for the H8/300H and H8S series.

Programmer and Boot modes operate

in the manner described in H8/300L
SLP section of this article. To reiterate,
the host indicates the length of the
code (word) it wants programmed fol-
lowed by the data. The MPU resets to

USER after the data has been
recognized.

H8/300H SERIES

The H8/300 series has a

32-bit architecture similar to
the H8/Tiny; however, with
a 64-KB address space, the
’3048 can make full use of
the 23-bit PC and 16-MB
address. The address space
can be divided into eight
areas, each with separate bus
specifications. Enhanced
addressing and instructions
help make full use of the
address space and 32-bit data
registers. A 16-bit DRAM
controller has multiple

refresh modes. A direct memory access
(DMA), integrated timer unit (ITU), and
timing pattern controller (TPC) were
added to the standard UART, ADC, and
DAC peripherals.

The ’3048 series handles apps that

require additional processing power. It’s
useful for HVAC, AC motor control,
color copiers, and diagnostic equipment.

Photo 1—

Renesas’s HEW has the GUI interface most software engineers are

familiar with. Project generator wizards help you move through configuration
options quickly, so you can get right at the application code.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

67

The DRAM controller produces the

CAS and RAS signals in support of 8-
or 9-bit column address multiplexing.
The on-board bus controller allows
external devices requiring different
bus specifications to live in harmony
by segregating them into one of eight
address areas. Each area can have spe-
cific wait states generated for them.

The bus master also arbitrates bus

rights between the CPU, DMAC, refresh
controller, or an external bus controller.
The DMAC transfers up to 64 KB of
byte/word data one time in a block
move (or to the same address), or it
repeats the operation continuously.

DMA Short mode uses an 8-bit source

and 24-bit destination. Long mode uses
a 24-bit source/destination. The DMA
has resources for four short or two long
DMA channels that run simultaneously.

The 16-bit ITU has five timer chan-

nels. The ITU allows for synchronizing
the timers (i.e., five synchronized PWM
outputs) and triggering the TPC, which
can output 16-bit data (groups of 4 bits)
synchronized with the ITU. In addition
to the dual standard UARTs, the ’3048
contains a smart card (SC) interface.
The asynchronous serial clock and data
I/O format of the SC interface is similar
to the asynchronous UART 8-bit format
with parity. However, the receiving
device can indicate a parity error (dur-
ing the normal stop bit time) for an
automatic retransmission of data.

The ’3048 has three power-down

states for reducing power consump-
tion. Sleep mode halts the CPU while
on-chip peripherals function via the
system clock. Hardware Standby mode
requires a logic low on the input pin

(*STBY), thereby disabling internal
peripherals and placing outputs in a
high-Z state. This is also accom-
plished through Software Standby
mode by setting the SSBY bit in the
SYSCR register before going to sleep.

In User mode, flash memory program-

ming is handled under user program
control by 1-, 28-, and 32-KB block
erasures and 128-byte block writes.

Because this handles up to 64 KB of

code and the ’3048 has 128 KB of flash
memory, you cannot directly use this
method to program the additional 64 KB.
You must supply code that will establish
a new boot format to accept data and
place it anywhere in the flash memory
address space (i.e., the S-record file).

H8S SERIES

The H8S/2000 series CPU has a

32-bit architecture that can cover a
16-MB address space. Address space
can be divided into eight areas each
with separate bus specifications.
Enhanced addressing and instructions
help to make full use of the address
space and 32-bit data registers.

A DRAM interface handles up to

8 MB of DRAM. A direct memory access
(DMA), data transfer controller (DTC),
and timer pulse unit (TPU, which is
similar to the ITU), and programmable
pulse unit (PPG, which is similar to
the TPC) are added to the standard
UART, ADC, and DAC peripherals.

The ’2329 series takes on applica-

tions that require more processing
power. You’ll find it useful for touch-
screen controllers, CD R/W drives,
medical monitors, LAN hubs, GPS
systems, and bar code scanners.

The DRAM interface produces all of

the CAS and RAS signals to support
external DRAM in address areas two
through five. The on-board bus con-
troller allows external devices requir-
ing different bus specifications to live
in harmony by segregating them into
one of eight address areas. Each of
these areas can have specific wait
states generated for them.

The bus master also arbitrates bus

rights between the CPU, DMAC,
DTC, or an external bus controller.
The DMAC can transfer up to 64 KB
of byte/word data once in a block
move (or to the same address), or it

32-kHz clock

System clock

H8/300L

H8/300H

H8/300H

H8S/200

CPU

1 KB

4 KB

4 KB

32 KB

32 KB

56 KB

128 KB

384 KB

RAM

Flash memory

3

3

2

1

2

5

6

2/10

6/16

1/14

5/16

8-bit Timers

16-bit Timers

PWMs (channel/bits)

Asynchronous event counter (8/16 bit)

2/1

Real-time clock

8/10

8/10

8/10

8/10

2/8

2/8

A/D converter (channel/bits)

D/A converter (channel/bits)

1

2

2

3

UARTs

I

2

C

66/6

53/8

78/28

95

I/Os/high current

Watchdog

Smart card interface

32/4

LCD controller (segment/common)

85

4/2

16

Data transfer controller (channels)

DMA Controller (memory-I/O/memory-memory)

Programmable pulse generator (bit)

Time pulse unit

Timing pattern controller

Integrated timer unit

13/9

38/11

30/7

52/9

Interrupts (external/internal)

Key

38024

3687

3048

2329

Figure 4—

Use this combined function comparison chart to learn how the devices stack up against each other. You

should be able to select a device based on the application requirements.

background image

68

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

can repeat the operation
continuously. DMA Short
mode uses an 8-bit source
and 24-bit destination, and
Long mode uses a 24-bit
source/destination.
Therefore, the DMA has
resources for four short or
two long DMA channels
that run simultaneously.

The DTC is similar to

DMAC because it’s used
for transferring data.
However, unlike the
DMAC, the registers used
for transfer control are
located off the DTC and in
(on-board) RAM. Although
the throughput is nearly
six times slower, it is not
limited to the 4/2 chan-
nels of the DMAC.

The 16-bit TPU has six

timer channels. The TPU
allows for the synchroniz-
ing of the timers (i.e., mul-
tiple synchronized PWM
outputs) and triggering of
the PPG. The PPG can
output 16-bit data (groups
of 4 bits) synchronized
with the TPU.

In addition to the three

standard UARTs, the ’2329
contains an SC interface.
The asynchronous serial
clock and data I/O format
of the SC interface is simi-
lar to the asynchronous
UART 8-bit format with
parity, except the receiving
device can indicate a pari-
ty error (during the nor-
mal stop bit time) for an
automatic retransmission
of data.

There are two clock

speeds available for pro-
gram execution: Active
High Speed mode and
Active Medium Speed mode.

The ’2329 has three power-down

states to reduce power consumption.
Like the H8/300H series, the H8S series
features Sleep, Hardware Standby, and
Standby modes. Additionally, the
H8S series includes Programmer and
Boot modes.

In User mode, flash memory pro-

gramming is handled via user program
control by 4-, 32-, and 64-KB block
erasures and 128-byte block writes.

Because this series handles up to

64 KB of code and the ’3048 has 128 KB
of flash memory, this method cannot be
used directly to program the additional

64 KB. You must supply
code for a new boot format.

SUPPORT TOOLS

Renesas offers products to

cover each stage of your H8
development. Low-cost or
no-cost tools enable quick
investigation of H8 capabili-
ties. The Hitachi Embedded
Workshop (HEW), which is
a software and debugging
environment, puts the
power of your PC to work
by providing a familiar GUI
atmosphere in which to
write your application. You
can use assembly or C/C++
to assemble or compile a
file that’s ready for down-
loading on known working
hardware (either your own
design or one of the many
evaluation boards).

Photo 1 shows the HEW

environment on my laptop.
From here I can create a
project, edit it, make it,
and debug it. HEW is free
(sorta, kinda). It comes
bundled with some evalua-
tion kits, and it’s either
time or size limited. If you
want the full version—
which includes a simula-
tor, profiler, map editor,
and stack analyzer—you
will need to upgrade
through a distributor.

The Hitachi Debugging

Interface (HDI) launches
from the HEW. With the
HDI, you have a common
GUI to any of the supported
debugging platforms, a
ROM-resident monitor, an
on-chip emulator, or an in-
circuit emulator. The serial
port allows you to down-
load a ROM monitor and

take control of executing your code.
You can read/write registers and
memory as well as execute your
code with a breakpoint. On-chip
emulators connect via resources built
into the target hardware to provide a
debugging interface for real-time
debugging. The PCI- or PCMCIA-

H'000000'
H'000029'

H'00002A'

H'000041'

H'000042'
H'0000F3'

H'0000F4'
H'00016F'

H'000170'

H'007FFF'

H'008000'

H'00E7FF'

H'00E800'

H'00EFFF'

H'00F000'
H'00F01F'

H'00F020'

H'00F02B'

H'00F02C'
H'00F6FF'

H'00F700'
H'00F73F'
H'00F740'
H'00F74F'

H'00F750'
H'00F77F'

H'00F780'

H'00FB7F'

H'00FB80'

H'00FDFF'

H'00FE00'
H'00FF7F'

H'00FF80'

H'00FFFF'

H'010000'

H'01FFFF'

H020000'

H'05FFFF'

H'060000'

H'0FEF0F'
H'0FEF10'
H'0FFF0F'

H'0FFF10'

H'0FFF1B'

H'0FFF1C'
H'0FFFFF'

H'100000'

H'FF7BFF'

H'FF7C00'

H'FFFBFF'

H'FFFE50'
H'FFFF07'
H'FFFF80'
H'FFFF27'

H'FFFF28'

H'FFFFFF'

Interrupt vectors

Flash memory

Not used

Internal I/O

registers

Not used

LCD RAM

Not used

Work area for

reprogramming

flash memory

User RAM

Internal I/O

registers

Interrupt vectors

Flash memory

Not used

Work area for

reprogramming

flash memory

User RAM

Internal I/O

registers

Address

38024

3687

Interrupt vectors

Flash memory

Not used

3048

Interrupt vectors

Flash memory

2329

User RAM

Internal I/O

registers

User RAM

Not used

Not used

Internal I/O

registers

Internal I/O

registers

Not used

Internal I/O

registers

Not used

User RAM

H'FFFC00'
H'FFFE4F'

Figure 5—

Note that the address scale on this memory map comparison is not linear.

The ’3804 and ’3687 are limited to 64 KB, but the ’3048 and ’2329 can address 16 MB.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

69

based emulators offer 255 break-
points, multiple-level execution trace,
and source-level debugging.

For advanced real-time debugging,

an in-circuit emulator presents more
ways to track down illusive bugs.
Emulation memory is mapped to the
target processor’s address space, the
32-KB trace buffers can be examined
during execution, and event sequenc-
ing is possible via a complex event
system (CES). The CES lets you specify
the exact set of conditions you want
to examine. Break, trace, or timing
functions are triggered using event or
range criteria. Up to 12 hardware
breakpoints can be triggered via com-
plex event and range conditions or
four user-logic inputs.

The event sequencer is used to gen-

erate an event based on the proper
sequence of other events. This flexi-
bility gives the in-circuit emulator
the means to track down even the
nastiest of bugs.

If you merely want to get your code

into an H8 without all the emulating
hardware, the flash memory develop-

ment toolkit (FDT) is a free stand-
alone, easy-to-use utility. The FDT
uses the aforementioned in-circuit
programming functions. The MPU
uses a serial interface and has a built-
in boot function, which allows the
flash memory to be erased and code
to be downloaded and executed.

After a program exceeds the 64-KB

size of the internal boot code loader,
things get more complicated. The
FDT takes care of downloading a boot
kernel to takeover from the boot code
and handle the programming of larger
flash memories.

CHOICES

Don’t be intimidated by your first

glance into the vast sea of Renesas H8
products. After you have an applica-
tion in mind, surfing the product
lines will allow you to focus on the
correct MPU based on peripheral
requirements.

Evaluation PCBs are available for

each series. On-chip emulators and an
in-circuit emulator are also available.
The flash memory microcontrollers

will help you get your application up
and running, debug it, and make code
changes without ever removing the
MPU from its target PCB.

In following with its well-known

slogan “Inspire the Next,” Hitachi
has seen fit to join with Mitsubishi in
separating their semiconductor opera-
tions into a new LSI giant. With this
extraordinary base, Renesas has begun
exploring new horizons. For them,
inspiration moves beyond the next and
into “Everywhere You Imagine.”

I

Jeff Bachiochi (pronounced BAH-
key-AH-key) has been writing for
Circuit Cellar since 1988. His back-
ground includes product design and
manufacturing. He may be reached
at jeff.bachiochi@circuitcellar.com.

SOURCE

H8 Microcontrollers
Renesas Technology America, Inc.
(408) 433-1990
www.america.renesas.com

background image

70

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

I

just received a PICkit 1 Flash starter

kit, and, to my surprise, the program-
ming interface is USB! Imagine that—
a USB port on the most basic of
Microchip’s development boards (see
Photo 1). Although I think the PICkit
1’s USB programming port is a good
thing, I still have some problems with
USB when it comes to pulling a per-
sonal USB project together.

Thanks to folks like Microchip,

Cypress, and National Semiconductor,
USB hardware is relatively cheap and
easy to obtain. All of the companies go
out of their way to provide useful exam-
ple code, and some even offer compre-
hensive USB tutorials aimed at their
products. On the other hand, if you
want to market a USB-equipped product,
you have to either fork out $2500 per
year to join the club (i.e., USB
Implementers Forum) or obtain
a USB vender ID (good for two
years) for a measly $1500. Either
way, your product must pass var-
ious tests to be certified. When
the words “test” and “certifica-
tion” are used, it usually means
more money out of your pocket
that has to be offset by raising
the product’s market price.

You can’t get something for

nothing, and I’m sure the USB
license fees are used to enhance
the processes and tools imple-
mented by the USB development
community. It looks like the pro-
ceeds are being put to good use,
because the free USB tools on the

company’s actions indicated that it isn’t
interested in showing you its products.

So, I’ve decided to prove that you can

obtain personal USB connectivity with-
out spending tens of thousands of dollars
on license fees, lab certifications, USB
vendor logos, and expensive USB analy-
sis tools. I am officially on a mission.

TRACKING DOWN USB

After I had decided to write this

article, I set out to find a suitable and
inexpensive USB analysis tool. To do
so, I started my e-mail engine and
donned my telephone headset. In less
than a day, I located and obtained the
holy grail of USB, an Ellisys USB
Tracker 110 (see Photo 2).

The USB Tracker 110 is a small hard-

ware device that traps, decodes, and dis-
plays a USB datastream flowing between

the USB device being tested and
a PC. Installing the USB Tracker
110 was a snap: I downloaded the
latest version of the analysis soft-
ware, UsbShow (www.usbtracker.
com), and after a few mouse
clicks, the USB Tracker 110 soft-
ware and driver set were installed.

The next step involved con-

necting the USB Tracker 110 to
the analysis computer. After the
standard “I have found a new
USB device” Windows message
had appeared, I manually direct-
ed the installation wizard to
install the USB Tracker 110
drivers that I had previously
downloaded. I got a magic wand

Mission Possible:

Achieve Cheap USB Connectivity

APPLIED PCs

by Fred Eady

official USB web site are useful for pre-
paring a product for USB certification.

USB license fees are small change to

large companies. Unfortunately, $2500
or even $1500 may prevent a smaller
enterprise from entering the USB mar-
ket, because the license fee is just a
small part of what is needed to seri-
ously develop USB devices.

I had wanted to show you some of

the devices, so I contacted a well-
known producer of USB analyzers. The
company’s least expensive analysis tool
runs for approximately $8000, and its
top-of-the-line USB analyzers top out
at more than $30,000. There are several
negative words I could use to describe
our conversations. Anyway, as you read
this article, you won’t find any of the
company’s equipment pictured or men-
tioned. The bottom line is that the

Exorbitant USB licensing fees and the high price of analysis tools have denied many of you
access to the USB marketplace. A champion of the individual designer, Fred is on a mission
to prove that it’s possible to achieve personal USB connectivity without breaking the bank.

Photo 1—

The PICkit 1 Flash starter kit is designed to program and read the

new 14-pin flash memory PICs and the legacy 8-pin flash memory parts. The
PICkit 1 comes with an extensive software and firmware library that includes
source code for the host and PIC USB interface. I populated the snap-off
part of my PICkit 1 with a Sipex SP232ACP and supporting components.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

71

from the Windows installation wizard,
and the USB Tracker didn’t smoke, so
all was going well.

This is a good place to pause the USB

Tracker 110 discussion and comment
on the USB hardware I collected for
analysis. I have two USB development
boards and a PICkit 1 that can connect
to my newly acquired USB Tracker 110.
Let’s begin by looking at ME Labs’s
PICProto USB development board.

PICProto USB

The reader response to my column

titled “A P89C668 Development Board
for 8051 Fans” was enough to tell me
that the BASIC programming language
is—as it relates to the 8051, PIC, and
AVR—alive and well (Circuit Cellar
151). ME Labs offers a good PIC BASIC
compiler called PicBasic. I got a copy of
PicBasic Pro because it’s more than a
decent BASIC compiler. The professional
version is relatively inexpensive, and it
supports Microchip’s flavor of low-speed
USB, which is driven by the PIC16C745
and PIC16C765 microcontrollers.

The PICProto USB development

board was refreshing because I had to
build it completely from scratch. I had
to fly in two components, a 6-MHz
ceramic resonator and a series-B USB
connector. Otherwise, the through-
hole assembly process was quick and
easy. A schematic and bill of materials
are included with the bare silk-
screened PICProto USB PCB.

For a complex interface, the USB

hardware is just as simple as basic RS-
232 hardware. In fact, I’ll go out on a
limb and say that a PIC-based USB hard-
ware interface is actually simpler than a
PIC-based RS-232 hardware interface.

The PIC16C745 and PIC16C765 USB

microcontrollers are self-contained and
don’t require any of the auxiliary level-
shifting circuitry that is common for
true RS-232 implementations. Using
the PIC16C765 or PIC16C745, a bare-
bones USB hardware interface consists
of the PIC, a couple of 0.1-µF bypass
capacitors, a VUSB filter capacitor, a
ceramic resonator, a resistor, and the
series-B USB connector. Even though
the PIC USB solution provides for a
simpler hardware interface, USB com-
munication requires much more effort
to implement.

On the PICProto USB development

board, the 28-pin PIC16C745 IC sock-
et lies inside the 40-pin PIC16C765 IC
socket. I wanted to be able to mount
either the 40-pin PIC16C765 or the
28-pin PIC16C745 on the PICProto
USB development board. So, I used
machined header pins to populate the
40-pin socket pads instead of a standard
40-pin socket. This allowed me to sol-
der a standard 0.3

28-pin socket inside

the 40-pin socket footprint. My com-
pleted PIC-less PICProto USB develop-
ment board is shown in Photo 3.

Because there is no “F” in their names,

the PIC16C745 and PIC16C765 micro-
controllers are available as either
windowed ultraviolet erasable parts or
one-time programmable (OTP) parts. I
have a fancy timer-equipped EEPROM
eraser, but I’ve been spoiled by the easy-
to-program, flash memory-based PICs.
Because the new generation of flash
memory-based USB PICs wasn’t avail-
able when I started this article, I used
the MPLAB ICE 2000 and a PCM16XQ1
processor module to stand in for the
windowed PIC16C745 and PIC16C765.

Before attempting to read the PIC-

Proto USB development board’s USB
datastream with the USB Tracker 110,
it may be a good idea to check to see if
all of the solder joints took. A small
USB demo program that moves the test
computer’s cursor is included with the
PicBasic Pro compiler. I loaded that
puppy into the MPLAB ICE 2000 to
see if I could twirl the cursor.

Using the MPLAB ICE 2000 instead

of the real thing required that I invoke
the MPLAB IDE. Normally, that would
have meant loading and running a sep-
arate IDE for the PicBasic Pro compil-
er. Not in this case. The PicBasic Pro
compiler is capable of running as a lan-
guage toolset within the latest version

of the MPLAB IDE. Although being able
to run PicBasic Pro and MPLAB in a sin-
gle IDE is a good thing in terms of devel-
opment, there is another upside to this
union: PicBasic Pro generates a standard
.cod file that allows for debugging using
the MPLAB ICE 2000 hardware.

After plugging in the MPLAB ICE

2000 PCM16XQ1 USB processor mod-
ule and attaching a 40-pin DIP device
attachment module to the end of the
processor module’s cable, I carefully
plugged the MPLAB ICE 2000 device
attachment’s gold-plated 40-pin DIP
header into the 40-pin header socket
that I had installed on the PICProto
USB development board. Then, I
jumpered the PICProto USB develop-
ment board for USB-supplied power.

At that point, I loaded the PicBasic

Pro USB demo, USBMOUSE.BAS, in the
MPLAB IDE. I couldn’t get a good reset
on the MPLAB ICE 2000. After clicking
the MPLAB IDE Run icon a few times
without success, I figured that some-
thing wasn’t working correctly.

I first took the software problem

determination route. (After all, my sol-
dering should be perfect.) I muddled
around, trying this and that with files
and such with no joy. OK, maybe I did
have a problem with the PICProto USB
development board hardware. So, I dis-
connected the PICProto USB develop-
ment board and took it to the bench for
a look under the magnifier. As I had
expected, all was well with the solder-
ing job and component placement.

I did not cut any of the default

Photo 2—

You don’t need anything but this little box, a

downloadable software application, and three USB
cables to help unlock the mysteries of USB. It costs
less than $900.

Photo 3—

All of the goodies that complement the every-

day PIC are included with this board. There are a couple
of potentiometers, a pair of LEDs, and two push-button
switches. The 25-pin connector pad layout suggests that
a serial-to-USB thing could happen in the prototype area.

background image

72

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

jumpers on the PICProto USB develop-
ment board. The only live jumper pins
were the power-source pins. I decided
to reattach the MPLAB ICE 2000 and
move the powered-by jumper from
USB to external. The MPLAB ICE 2000
reset was successful, and I was able to
configure the MPLAB ICE 2000 to use
the PICProto USB development board’s
power and clock. Obviously, the emu-
lator and associated electronics drew a
bit more current than the USB was
willing to supply at that point. Despite
the little drawback, it was good.

I had already created a project directo-

ry and copied the USBMOUSE.BAS file
into it. A study of the USB documenta-
tion that was included with the PicBasic
Pro compiler indicated that I would
need to add supporting files to the
project as well. These files, which
were included with the compiler, pro-
vide a basis for the USB hardware layer
that is intended to reside in the PIC
firmware. The PicBasic Pro USB support
files are based on the original Microchip
USB support files and have been modi-
fied to compile under PicBasic Pro.

Having put my emulator hardware

problem behind me, I was on my way

to compiling the USB demo
code and controlling a cur-
sor. Well, not quite on my
way. I clicked the MPLAB
IDE’s Build icon and was
greeted with what seemed
to be a million error mes-
sages, which wasn’t good.

My first clue was the first

error, which stated that it
could not open a particular
include file, P16C765.INC.
That’s easy enough, I said to
myself. I’ll just rename the
PicBasic Pro 16C765.INC to
P16C765.INC and things
will once again be good. Ha!
My mouth was still open
when the dust stirred by a
million more error mes-
sages had settled. OK,
maybe the list file would
reveal an answer. Duh. My

second clue was on the first
error line of the listing.
MPASM header was the
comment beside the lost
P16C765.INC file.

You can configure the PicBasic Pro to

use either the MPLAB assembler
(MPASM) or the internal PicBasic Pro
assembler (PM). Well, there’s a big check
mark in the “Use MPASM Assembler”
box under the MPLAB IDE’s project
build options. I had renamed the PM

include file (16C765.INC) to fool the
MPLAB IDE assembler, but the MPLAB
IDE assembler didn’t bite on the con-
tents of the newly monikered file.

I checked my Win2K path variable

and indeed the entry for the Microchip
MPLAB IDE include files was there.
Without question (I was desperate), I
simply copied the Microchip-provided
MPLAB IDE P16C765.INC and
P16C764.INC include files into my
PicBasic Pro USB project directory.

Here we go. After clicking on the

MPLAB IDE Build icon, I was hum-
ming my favorite Bob Marley tune,
“Jammin’.” After another click on the
MPLAB IDE Run button, I was grow-
ing dreadlocks. The test machine’s cur-
sor was going in circles and dancing to
the reggae beat. It was good indeed.

BACK ON TRACK(ER)

If you’re a drag racing fan, you know

that most of the real work is done in
the pits before the race. The same can
be said for working with USB. Before
powering up the PICProto USB develop-
ment board, I reread Jan Axelson’s
book, USB Complete: Everything You
Need to Develop Custom USB
Peripherals

. [1] In addition, I perused

the Microchip USB documentation and
datasheets to get the particulars on the
PIC16C765 and PIC16C745 USB micro-
controllers. A good collection of USB

Photo 4—

I wanted to show you the

USBInit

instruction and the

MPLAB ICE 2000 breakpoint. Now you should have an idea of how
PicBasic Pro fits inside an MPLAB IDE session. Note that only two
PicBasic Pro USB commands are used, USBInit and USBOut.

Photo 5—

I couldn’t possibly show you everything, so I’ve decided to give you copies of all of my traces. You can

view them using the USB Tracker 110 display software, UsbShow.

background image
background image

retool with intelligence

September 15 – 18, 2003

Hynes Convention Center
Boston, MA

Conference Sponsors

Save up to $650

Register by July 15th

Flexible conference

packages start at $445

Save up to $450

Register by August 19th

To register or to view a complete list
of courses and events, visit:

embedded.com/esc

Source Code: MKL

Be sure to use this source

code when registering

> NEW Flexible Conference Packages

The Embedded Systems Conference Boston now
offers you more flexibility than ever before with
new customizable 1 to 4-day conference packages.
Choose the 4-Day VIP package to save hundreds
of dollars while gaining new skills and techniques.

> More classes dedicated to hardware and

software design

Designing the Next Generation of Handheld Devices,
FPGA Design for Software Engineers, and Mastering
Design Patterns are just a sample of challenging
courses we have to offer

> Meet with more than 150 leading vendors

The Boston exhibit floor is your opportunity to
meet with embedded vendors, preview exciting
innovations, and catch up with what's going on
in the embedded industry. See the industry giants
and innovative up-and-comers in person and talk
with field application engineers to get answers to
your toughest design questions.

What’s New for Boston 2003:

37 industry experts sharing their expertise
in 78 classes and full-day tutorials at the
East Coast’s premier event dedicated to
processor-based design

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

75

data comes with Microchip’s PICDEM
USB development board.

After working out the initial emulator

and compiler bugs, I decided to test run
the USB Tracker 110. I used the result-
ing USB trace in conjunction with
Axelson’s book and the USB specifica-
tion to determine what was needed from
a firmware standpoint to be successful
with USB. Now, I’ll explain how it went.

Slow-motion photography is often

used to study the minute details of a
fast-moving event. You can do a simi-
lar thing electronically using an emu-
lator like the MPLAB ICE 2000. So, I
added a breakpoint to the PicBasic Pro
compiler demo USB code to see if I
could stop the USB process and exam-
ine it up to that point (see Photo 4).
The PicBasic Pro compiler only sup-
ports three USB BASIC commands:
USBINIT, USBIN, and USBOUT.
According to Axelson’s book and the
USB specifications, three simple USB
commands won’t cut it. However, I
saw two of those simple little com-
mands wiggle a cursor using a rudi-
mentary PIC circuit and USB. It was
time to sip from the Holy Grail.

I inserted the USB Tracker 110 into

the loop with the analysis computer at
the USB Tracker 110 analyzer tap. The
test computer and PICProto USB devel-
opment board were plugged into the
USB Tracker 110’s device under test
sockets. According to the PicBasic Pro
Basic compiler description, the

USBINIT

command initializes the USB device and
completes when the USB device is con-
figured and enabled. I knew from my
reading that the USB device must first
enter the powered state and then pro-
ceed to the default, addressed, and con-
figured states (in that order) before being
able to intelligently communicate with
the host. That is called enumeration.
But how does the PicBasic Pro

USBINIT

command do it all?

Behold the screen shot in Photo 5,

which is the USB Tracker 110’s view of
everything USB that transpired between
the test PC and the PICProto USB devel-
opment board from the time the board
was powered up. Wow! Think about
what you could do with this informa-
tion. With the trace, you could correlate
the trace data to a corresponding seg-
ment of PicBasic Pro source code, and

you should be able to investigate the par-
ticulars of the

USBINIT command. Let’s

work through an example. You can fol-
low along using the USB Tracker 110
trace data in Photo 5 and either the origi-
nal USB specification or USB Complete.

According to both sources, after a

successful initial USB hardware reset
sequence, the host PC will issue a
GetDescriptor request. At power-up, the
PIC-based USB device goes into a pow-
ered state with its interrupts enabled.
When the PIC is able to execute instruc-
tions, the USBINIT macro invokes
the

InitUSB code that resides in the

Microchip-supplied USB_CH9.asm mod-
ule. When the host sees that the device
is powered, it issues a USB reset to the
powered device. Looking at the USB
trace, the

Extended SE0 (26.3 ms) is

most likely the USB reset from the host.
After starting the USB trace, it took a
few seconds to plug in the PICProto
USB development board’s USB cable and
start the MPLAB ICE 2000 emulator.

The host USB reset then triggers the

PIC’s USB reset interrupt, which con-
figures the PIC’s USB address to 0x00
and enables endpoint zero. This collec-
tion of zeros is in the default state
because every USB device must have
an active endpoint zero at that point.
In the default state, a USB address has
not been assigned by the host, and the

host expects to be able to talk to the
newly found device at the 0x00 address
using the bidirectional endpoint zero.
The default state endpoint and device
addresses (0x00) are verified in the first
GetDescriptor(Device) trace entry.

The first transaction after the forced

reset from the host is a set-up transac-
tion aimed at device zero, endpoint zero.
As you can see in Photo 6, the USB
Tracker 110 and UsbShow trace pro-
gram are able to show and decode the
bit fields inside common USB packets.
They also display the raw packet data.

You can pick out all sorts of details

from the packet information provided
by the USB Tracker 110 and UsbShow.
For instance, in the data packet of the
SETUP transaction, the packet iden-
tifier (PID) is actually the least signifi-
cant nibble of the PID. The most sig-
nificant nibble of every PID is a com-
plement of the PID’s least significant
nibble, which, along with a CRC
word, helps to ensure data integrity.

In the aforementioned example, the

token packet is followed by a data
packet, which contains the set-up
request information. Axelson says that
although the host asks for 64 bytes, it
will only read the first 8 bytes because
all it really wants is the eighth byte of
the device descriptor, which contains
the maximum packet size. She’s right.

Photo 6—

This is a handy feature. Before obtaining a USB Tracker 110, I found myself searching through the

pages of the USB specification and Microchip USB source code looking for the tables and declarations that defined
the various bit fields.

background image

76

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Axelson’s Carnac-inspired foresight

is reinforced by an information mes-
sage that UsbShow posts for the

SETUP

transaction. The UsbShow message
tells you that the retrieval of less than
64 bytes is not an error and that the
host would later ask again for the
device descriptor information. Looking
ahead in the trace shows you that the
entire device descriptor is read in after
the device address is established.

Using the ’16C765 and ’16C745 USB

micros eliminates a great deal of USB
configuration confusion because they’re
low-speed devices. Low-speed devices
are limited in many ways, one of which
is the maximum packet size, which is
set at 8 bytes. You can see the 8-byte
limit enforced throughout the USB trace.

Moving to the next transaction, the

IN transaction pulls the 8 bytes of
the 64 bytes of requested data from the
PICProto USB development board’s PIC
firmware. The host has just enough
information and status to grant the
PICProto USB development board a USB
address. But before knighting the devel-
opment board, the host wisely resets it
to make sure it is in the default state
before sending the

SetAddress request.

After the

SetAddress request is

acknowledged, the PICProto USB
development board is considered to be
in the addressed state. As you can see
in the trace, the development board
was reset and assigned an address (2).
Remember that everything in USB is
about the host. So,

IN means to the

host, and

OUT is from the host.

From what you’ve seen thus far, you

probably have a good idea of how the

rest of the USB enumeration process
will flow. Looking at the trace, you
can see that device, configuration, and
string descriptors are collected from
the PICProto USB development board’s
firmware as the USB enumeration
sequence progresses. The Windows OS
assimilates all of the data collected
from the PIC and finally sends a
SetConfiguration request, which
ultimately results in placing the devel-
opment board in the configured state.
After configuration, the development
board can pass data to and receive data
from the host PC (the test computer).

THE SONG REMAINS THE SAME

I unplugged the 40-pin MPLAB ICE

2000 device adapter from the PICProto
USB development board and plugged it
into the 40-pin PIC16C765 socket on
my PIDCEM USB development board.
I clicked on the MPLAB IDE Run icon
and, lo and behold, the PICProto USB
development board demo code ran on
the PICDEM USB as it should.

Although cosmetically modified to

compile inside PicBasic Pro, the core
USB code and fundamental hardware
design are identical. The PICDEM USB
development board differs from the ME
Labs PICProto USB development board
only in the amount of on-board equip-
ment. The former comes assembled with
a USB CD-ROM containing support code
and documentation, a preprogrammed
PIC16C765 full of demo code, a 3

USB

A-B cable, a blank ’16C745, and a blank
’16C765 (see Photo 7). It also includes a
serial port, a game port, a PS/2 key-
board/mouse port, enumeration status
LEDs, and a backlit LCD landing pad.

I wasn’t able to show you every detail

of the USB traces, and I would need a
few more pages to take a complete look
at the features offered by the USB
Tracker 110 and UsbShow. So, instead
of leaving you hanging, I’ve included all
the USB trace data that I took from the
PICKit1 Flash starter kit, the PICProto
USB, and the PICDEM USB. You may
download the data from the Circuit
Cellar

ftp site. The core USB source

code is on Microchip’s web site.

If you’re wondering how you’re going

to read the USB traces, simply down-
load your freeware copy of UsbShow
(www.usbtracker.com). The UsbShow

software will display the USB traces
I’ve provided and the detail contained
within them. However, you won’t be
able to take your own USB traces with-
out a USBTracker 110. The USB
Tracker web site also has a great picto-
rial overview of what the USB Tracker
110 and UsbShow can do. Reviewing
the overview will make it easier to
interpret the USB traces. USB is com-
plicated, but at least it’s embedded.

I

Photo 7—

If you prefer an assembled alternative to the

PICProto USB, the Microchip PICDEM USB provides
the basic functionality of the PICProto USB in addition
to the ability to experiment with using USB to control an
LCD and game pad. The PICDEM USB LEDs, which
can be switched out with a jumper or at the firmware
level, illuminate to signal each state of enumeration.

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.

PROJECT FILES

To download the UsbShow files, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2003/157.

REFERENCE

[1] J. Axelson, USB Complete:

Everything You Need to Develop
Custom USB Peripherals

, Lake-

view Research, Madison, WI, 2001.

SOURCES

USB Tracker 110
Ellisys Sarl
www.ellisys.com

MPLAB ICE 2000, PIC16C745,
PIC16C765, PICDEM USB, and
PICkit 1 starter kit
Microchip Technology, Inc.
www.microchip.com

PicBasic Pro compiler, PICProto USB
microEngineering Labs, Inc.
www.microengineeringlabs.com

SP232ACP Transceiver
Sipex Corp.
www.sipex.com

RESOURCES

USB Tracker 110 distributors
Saelig Company
www.saelig.com

USB Wholesale
www.usbwholesale.com

background image

CANbus

Starter Packs

available for almost

any board format: PCI, ISA, PCMCIA, PC104,
VME, cPCI, etc. with software for most OS’s
inc. all Windows, Linux, QNIX, etc.
CAN/Ethernet bridges, industrial
computing and automation solutions
Industry leaders worldwide trust and
specify Janz AG’s ISO9000 systems.
Janz AG - a leading CANbus supplier.

ALSO:

S C A L A B L E L E D D I S P L A Y P A N E L S , TEMP-HUMIDITY

MONITORS, T H E R M O C O U P L E P . C . A D A P T E R S , ENVIRONMENT

MONITORING SYSTEMS, EDUCATIONAL SCIENCE PROJECTS,

GRAPHICS SOFTARE, AutoCAD PROGRAMMING COURSE, USB-PIC

BOARDS, FLASH PROGRAMMERS - IF YOU DON’T SEE WHAT YOU

NEED MAYBE WE CAN FIND IT FOR YOU? - JUST ASK FOR ALAN!

by

Janz

for

all

computers

Saelig Co. brings to USA unique, easy-to-use control and
instrumentation products from overseas. Customers inc:
Intel, Philips, NEC, Kodak, Nokia, US Military, Microsoft,
Dell, Xerox, Universities, T.I., Harris, Sony, J&J,
Thomson, Sandisk, General Dynamics, H-P/Compaq, e t c .

Industrial PCs

Turn your PC into a high-
speed scope. Sampling
rates up to 100MS/s for sin-
gle shot signals (and up to
5GS/s for repetitive signals)
with 12-bit resolution. With
FREE software, your PC
becomes a powerful 2-chan-
nel scope and spectrum
analyzer.

ADC-212/100

$1090

US232 is a 6ft USB-RS232
self-powered converter
cable which instantly and
reliably solves the problem
of laptops with no serial
ports, or legacy RS232
devices that need to be
updated to USB

IN ONLY 5

MINUTES!

Buy in bulk to

update your products - $39!

"After looking at a number of packages
both large and small we have found

TRAKIT

TM

to be the most cost effective

solution for inventory management in the
manufacturing environment available for
the small to medium size company. It
contains most of the commonly used
features of the larger programs as well as
maintaining the user ease of the smaller
programs. Some of the more advanced
features of Trakit are more successfully
implemented than packages costing
many times more. Better and easier to
use than P&V" (S.P. Ltd)

TRAKIT

manufacturing

- Inventory Management

- Bills of Materials

- Build Schedule

- Sales Orders

- Instant Builds

- Purchase Ordering

- Request for Quote

- Reminders

- Reports

K2

9p-9p self-powered RS-422/485 converter

K3

9p-9p isolated RS-422/485 converter

K3-232

9p-9p isolated RS232 converter

K232-ISOL

25p -25p RS232

K422-ISOL

25p -25p RS422

K485-ISOL

25p -25p RS485

KD485-STD

DINrail-mount

RS-232/485/20mA isolators

KD485-PROG

DINrail-mount

RS-232/485/20mA isolators
C-programmable for protocol/MODbus
conversion. Program to convert custom needs.

USB-485i offers self-
powered USB to RS485
conversion with optical
isolation to 1kV. Baud
rates 184bps - 3Mbps.
Link-selectable half-duplex
mode enables the 485
transmit-buffer when data
ready. Three-point isolated
serial communciations.

200 kS/s 12-bit dual-channel USB scope adapter for
PC. Unique software looks like a “Digital Scope” right
on your PC screen! Built-in
squarewave generator.
Weighs less than 8oz so
you can take it anywhere.
Only $189!! For details:
www.usb-instruments.com

USB protocol analyzer displays USB packets sent,
decodes descriptors, detects errors in peripherals or
drivers and measures their performance.
Ideal for anyone developing
USB peripherals,
embedded soft-
ware or drivers.
Software is easy
to use - learn all
about USB. $799!

Make PCs talk I2C easily with this industry-standard
card, available in 2 - 6V bus version for low-volt I2C
systems. Optional WINI2C/PCI software gives you a
windows-interface to develop
and debug I2C bus systems.
Monitor software lets you
transparently monitor I2C bus
activity .

NEW - USB VERSION

UCA93LV: 400kHz monitoring!

Build a custom PCMCIA or CF
card datalogger or controller

- quickly!

Wizard high-level

software completes your
project in hours not weeks.
Store GPS or CANbus data.
TDS2020F is the low-power
controller of choice for sure
LONGEVITY - this one won’t
disappear like so many other
obsolete boards. Ask us why!

Join all the industry leaders who are using this easy-use
USB ic. Single chip USB-232 solution comes with all
Windows/Mac/Linux drivers. UART ASIC-based so no
software development is needed!

Euroquartz is one Europe’s largest manufacturers and
supplier of quartz crystals, oscillators, filters and
frequency-related products. They design & manufacture
a comprehensive range of frequency-related components
including custom-made filters, high
reliability oscillators for defence
applications and radiation tolerant
oscillators for high-altitude apps.
EQ-HM oscillators reduce EMI using
Spread Spectrum Technology
to slowly shift center frequency.

Easily construct small control systems communicating
through Intranet/Internet. BIT2000 is the ideal solution
for process control, building
monitoring, data logging,
alarm systems and other
industrial uses. BIT2000
can communicate with
many types of equipment
through the fast multidrop
RS485 based bus and a
standard RS232 serial port.

At last!

This tiny pocketable USB-based and USB-

powered device is the answer to your need for an eco-
nomical logic analyzer that you can take anywhere.
About the size of a small matchbox, ANT8 can sample
eight channels at up to 500 million samples-per-sec.
ANT8 offers simple or complex
triggering, upgradeable soft-
ware. View the captured eight
digital channel traces on your
PC. Save or print screens for
reference or labnotes! $199!

Manufacturing Software

RS485 factory control

Crystals & Oscillators

Easy USB in one IC!

Basic modules

No USB knowledge required! Byte-
wide ic version FT245BM too!
FT232BM is in the ready-made
US232 cable (USB-serial) - see top
right panel. Instantly update your
legacy serial RS232 products!

PC Scope Adapters

RS232<>422/485

I2C for PCs

Datalogger/Controller

CANbus Cards

Standalone Dataloggers

SM PCB Adapters

USB PC Scope

USB Bus Analyzer

Logic Analyzer

Isolated USB<>RS485

USB-Serial Adapters

BASIC Tigers

are tiny multitasking

modules for quick project development.
Powerful features and low prices make
Tigers a number one choice: super-fast
development cycle, high reliability prod-
ucts, >100,000 instructions/s, up to 38 I/O
lines, A/D, D/A, I2C, SPI, text/graphic LCD
interface.

NOW - SmartCard Interface!

iCOM200

ready-made controller with LCD

and keypad.

Touch240

controller - with

touchpad and LCD display.

Self-contained in 2” x 3” box, these
battery-powered standalone analog
and digital loggers store events,
voltages, currents or pressures for
days to weeks. Download detailed
time and data via serial port and
review results with graphic software
or upload to an Excel spreadsheet.
More details at - www.abidata.be

These SM miniboards have two foot-
prints on either side, allowing you to
use ultra fine pitch SMD components
with a more useful array of 0.1"
spaced holes. 1-to-1 pinout for circuit
probing during design and testing.
Each unique miniboard (pat-pending)
can fit several different devices.
More at www.omega-research.co.uk

Ruggedized Industrial ATX PC systems to suit almost
any budget or PC application.
Easy maintenance, economy
and reliability. $899 version
features AMD Athlon XP1700,
shock-mounted 40GB harddrive.
Lockable front doors prevent
tampering. Full Burn-in and
Test Report with every system.
LED system status indicators.
CE EMC certified. More info at www.amplicon.co.uk

S

A

E

L

I

G

B

R

I

N

G

S

Y

O

U

S

O

L

U

T

I

O

N

S

!

Saelig

Co. Inc.

585-425-3753 • fax: -3835

www.saelig.com • info@saelig.com

background image

78

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

A

s a first-hand observer of much of

the IC revolution, after almost 30 years
I still get a thrill from the march of sili-
con, something I’m very thankful for.
I’m quite sure I wouldn’t be able to
say the same had I ended up selling
insurance, for example. Don’t you just
love this business? You bet I do!

I think of the mass of humanity

around the globe mousing away at
their PCs or starting their micro-laden
cars who have little understanding or
respect for the 100 million transistor
CPUs and billion transistor DRAMs
under the hood. They take for granted,
rightfully, they’re owed more chip for
less money, just as it’s always been.

Yet for me, it’s still the little chips

that are most inspiring. Intel’s 8-bit
8080 saved me from a life of, if not sell-
ing insurance, perhaps working in a big
company MIS bureaucracy maintaining
COBOL programs or something equally
grim. A computer where me, myself,
and I was the MIS department—cool!

It’s more than just nostalgia, though.

It may seem that someday the entire
world will get integrated on a single
chip, but in fact there will always be a
need for simple little chips that do sim-
ple little things. What’s the biggest of
the simple little things the simple little
chips need to do? It’s to save the butts
of the complicated big chips. Read on,
and you’ll see what I mean.

THE NAKED CITY

With apologies to a long ago TV

show, there are eight million switch-
es—and the requisite shorts, glitches,
and transients to go with them—in the

ing about the blue-collar, big-iron
switches that get down and dirty con-
necting with the real world. They go way
beyond simple on/off and ones and zeros
by actually doing some heavy lifting in

Switch Hitter

SILICON UPDATE

by Tom Cantrell

naked city. I’m not talking DIP switches
or little togglers that live happily ever
after in a pristine digital gated communi-
ty behind white picket fences and nicely
regulated and filtered supplies. I’m talk-

+

V

PWR

V

PWR

16 mA

16 mA

2 mA

2 mA

4-V Ref

Comparator

To SPI

SP0

SP2

SP0

+

V

PWR

V

PWR

16 mA

16 mA

2 mA

2 mA

4-V Ref

Comparator

To SPI

SP7

SP5

SP7

SP4

SP6

SP3

SP1

+

V

PWR

V

PWR

16 mA

2 mA

4-V Ref

Comparator

To SPI

SG0

SG2

SG0

+

V

PWR

V

PWR

16 mA

2 mA

4-V Ref

Comparator

To SPI

SG5

SG13

SG4

SG3

SG1

SG7

SG13

SG10

SG9

SG12

SG8

SG6

SG11

V

PWR

, V

DD

, 5 V

POR

Bandgap
SleepPWR

V

PWR

V

DD

GND

5 V

V

PWR

Oscillator

and clock

control

V

PWR

Temperature

monitor and

control

5 V

Wake control

SPI Interface

and control

*INT Control

MUX Interface

V

DD

5 V

125 k

*Wake

V

DD

125 k

+

Analog MUX

output

AMUX

V

DD

*CS

40 µA

*INT

V

PRW

5 V

V

5 V

V

DD

SCLK
SI

SO

5 V

Figure 1—

MC33993 is the name, and switching is the game. Twenty-two switch inputs are provided, 14 of which

are switch-to-ground and eight are programmable as switch-to-ground or switch-to-VPWR. In addition, any switch
input can be routed via the analog multiplexer to the AMUX pin.

The MC33993 was designed with automotive applications in mind, but that doesn’t mean that
intelligent engineers in other fields won’t find it useful. This month, Tom delivers an introduc-
tion to the chip’s features in addition to discussing its applicability outside the auto industry.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

79

rather harsh environments.

As usual, the automobile pro-

vides a good setting for a reality-
based switch story. Yes, it’s going,
going, gone digital in many ways,
but under the hood, it’s still a pret-
ty rough neighborhood. And
though a good example familiar
to all, the grittier aspects are also
found in a variety of consumer
and industrial applications.

Enter the Motorola MC33993

(see Figure 1). Like its e-field chip I
wrote up in Circuit Cellar 155, the
’993 is another example of taking a
chip defined for automotive apps
and running it up the flagpole to see
if there’s broader market interest.

In principle, the chip is quite simple.

In essence, it’s little more than a shift
register connecting 22 parallel I/O lines
to and from a clocked serial port. The
story of the ’993 is less about what it
does than how it does it. Actually, there
are interesting outside-the-box poten-
tials, but for now let’s look at the basics.

And those basics start with the fact

that automotive electrical systems
were designed to serve headlights and
starter motors, not chips. Though
nominally 12 V in theory, actual prac-
tice finds even routine operation cov-
ering a range of perhaps 10 to 16 V.

Unfortunately, that’s just the begin-

ing. The instantaneous voltage is sub-
ject to wild mood swings as transient
loads come and go. And I’m not talk-
ing about turning the radio on and off
or using the cigarette lighter, but big
hitters like an AC compressor or radi-
ator fan. And let’s not even get into
the problems engendered by shade-
tree mechanics other than to say that

Murphy is quite at home behind the
wheel (if it can, it will go wrong).

As shown in the ’993’s block dia-

gram, the real-world side of the chip
accomodates up to 22 switch inputs.
Eight are programmable as switching to
battery voltage, which powers the chip
(VPWR) or ground, while the other 14
are dedicated to switch-to-ground.

There’s a separate digital logic supply

(V

DD

), but its primary role is to establish

the voltage levels (e.g., 3.3 or 5 V) for the
SPI-clocked serial port connection to an
MCU. In fact, the supply can be turned
off much of the time if you’re so
inclined. But, because V

DD

draws only a

fraction of a milliamp and its absence
compromises some of the chip’s opera-
tion, it may not be worth the bother.

Hardened against the vagaries of the

real world, the chip is designed to
operate across a remarkably wide
VPWR range from 5.5 to 26 V. But, in
fact, the switch inputs themselves can
tolerate even more abuse, living
through extremes from –14 to 40 V
(not to mention 25-kV ESD protec-
tion). Try feeding something like that
to your little MCU if you dare, but
just keep a fire extinguisher handy.

SPI WITH ME

The ’993 relies on the popular SPI-

clocked serial interface to connect to
your favorite MCU. The bus frequency
(SCLK) is up to 6 MHz, and, as I men-
tioned earlier, the voltage thresholds
are determined by V

DD

(see Figure 2).

With dedicated input (SI) and output

(SO) pins, SPI is a full-duplex scheme

transferring a bit in each direction
every SCLK cycle. For the ’993,
each transaction requires 24 bits.
The outgoing bits issue specific
commands, while the returned
bits comprise the 22 bits of
switch state (open or closed) and
two status bits. One, INTFLG, is
a mirror image of the INT pin
state for use in polling situations,
and the other, THERMFLG,
denotes the thermal shutdown
state, which I’ll discuss later.

The chip operates in Normal

and Sleep modes. It powers up
(VPWR) in the former (4 mA), and
stays that way until the MCU
issues a Sleep command. After

sleeping (100 µA), the chip wakes up
on a change of switch state (for the
switches programmed as wake-up
sources) or assertion of *CS, *INT, or
*WAKE. The *CS and *INT wake-up
features work only if V

DD

is applied.

The *WAKE pin works without V

DD

, so

you can use it to enable the V

DD

supply

powering the ’993 and the MCU.

There are also a couple of automatic

wake-up schemes relying on timers
inside the ’993. An interrupt timer
periodically wakes up the chip and
generates an interrupt (INT); it’s pro-
grammable with a period (eight selec-
tions) of 32 ms to 4.096 s.

No, that’s not a misprint: there is no

option to turn it off, and if you use the
Sleep mode, you will get INTs and have
to repeatedly issue the Sleep command. I

V

BAT

SP0

SP1

SG0

SG1

SP12

SP13

SP7

V

PWR

V

DD

V

DD

*Wake

SI

SCLK

*CS

SO

*INT

AMUX

GND

Power supply

LVI

*Enable

Watchdog

Reset

*CS

SCLK

MOSI

MISO
*INT

AN0

MCU

V

DD

MCC33993

V

BAT

V

BAT

Figure 2—

The MC33993 connects easily to any MCU via a hardware

or bit-banged clock serial interface.

Photo 1—

Combining the Sleep mode with automatic

switch scanning yields a good compromise between
power consumption and switch response.

Photo 2—

Take a look at the MC33993 EV board in

action, including the 24 SCLK pulses that go with each
*CS. The PC parallel port bit-banging scheme is kind
of slow, so each *CS cycle takes a few milliseconds
instead of the few microseconds the chip requires.

background image

80

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

suppose this is intended to
have the ’993 play a watchdog
role that might be appropriate
for some applications but
unlikely so for others.

The other timer handles

switch scanning and can be
turned off (no scanning). If
enabled, it will frequently
scan the switch status (range
if 1 to 64 ms), and compare it
against the prior state. If a
change is detected, the ’993
wakes up (i.e., enters Normal
mode) and generates an *INT.
Otherwise, the chip goes back
to Sleep mode and waits for the next
scan-timer wake-up call (see Photo 1).

Note that the entire scan and com-

pare process takes only a couple of
hundred microseconds, so the combi-
nation of Sleep mode and scanning
offers the potential for significant
power savings. Even at the fastest
scan rate (1 ms), the duty cycle is only
one-fifth, so average power consump-
tion would be cut significantly, and
much more so for slower scan rates.

There’s a calibration command to fine-

tune the on-chip timebase. After the cal-
ibration command is received, the ’993
waits for a 512-µs pulse on the *CS line.
The datasheet doesn’t elaborate on the
feature, but you can adjust the timebase
(e.g., to achieve a 4-s rather than 4.096-s
interrupt timeout) by tweaking the
calibration pulse accordingly.

Checking out the ’993 is easy and

cheap thanks to the $99 evaluation kit
(see Photo 2). It’s quite simple, consisting

of little more than the chip
itself, 22 DIP switches, a
couple of LEDs (INT and
WAKE), and a connection for
a PC parallel port. The kit
comes with a cute piece of
software, SPIGen, which
allows you to easily issue
various commands and even
define multicommand
sequences (see Photo 3).

HEAVY METAL

Getting back to the real-

world (i.e., switch) side of the
chip, the ’993 offers interest-

ing features including contact wetting
and an analog mux. Humidity, salt air,
and so on can cause oxidation to form
on switch contacts, causing glitches or
switch failure. Contact wetting refers
to delivering an extra shot of current to
switch transitions to stop the crud before
it spreads. Here’s how it works.

The state of each switch input can be

individually programmed to deliver 2 or
16 mA of current (or go tristate as well).
The wetting feature uses a 20-ms timer

Photo 3—

No need to get bogged down in the bit-by-bit, blow-by-blow details. The EV

kit comes with SPIGen software that makes experimenting with the various commands
easy. The ability to define your own custom command sequences is especially useful.

TO

em

BE

dded

OR

NOT TO

em

BE

dded

Embedded Small World

--

Small Footprint X86 Embedded Modul

es

DM&P Group

ICOP Technology Inc.

USA

Tel: 1-626-444-6666 email:info@icoptech.com

Taiwan

Tel: 886-2-8990-1933 email: info@icop.com.tw

Japan

Tel: 81-3-3265-1508 email: info@icop.co.jp

China

Tel: 86-755-2661-1770 email: info@icop.com.cn

www.icoptech.com

· Supports small footprint headless

DOS

and

Linux

kernels.

· Provides complimentary software utilities and libraries for program developing.
· DSock Library: Sample Codes for BOOTP/DHCP, FTP, SMTP, HTTP, and TELNET Servers.
· Software Utilities are programmable in C, C++ and Assembly Languages.

Design ICOP 386SX Modules into:

è

Point of Sales

è

Information Kiosk

è

Medical Device

è

Automation Control

Customer-made Thin Client

Tiny and Mity SoC Modules

RSIP Server &
Fingerprint Reader

NEW

Power Supply

for Embedded Applications

background image

background image

82

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

that automatically kicks up the current
to 16 mA when a switch input changes
state (i.e., crosses a 4-V threshold). After
the timer expires, current is cut back to
the 2-mA “sustain” level (see Photo 4).
However, the timer for each switch can
be individually disabled, in which case
16 mA will continue to flow.

Here’s where the thermal flag

(THERMFLG) in the status word comes
into play. Clearly, with up to 22 switch
lines carrying 16 mA at up to 26 V, the
potential exists to get hot under the

status register, and generate an interrupt.
The THERMFLG bit is automatically
cleared (updated on the rising edge of
every *CS) and previous current set-
tings are restored after the temperature
cools to a safe level.

The other interesting feature is a 22:1

analog multiplexer that connects any
one of the switch inputs to the AMUX
output pin. The connection is buffered,
and the output is clamped to the maxi-
mum level defined by the V

DD

supply.

THE MORE THE MERRIER

You can expand the ’993’s by using

multiple chips. The SPI interface sup-
ports two ways of doing so: daisy-chain-
ing and individual chip-by-chip access.
The former approach lines up multiple
’993s in a string with each chip’s SO out-
put connected to the next’s SI input. The
first chip’s SI input and the last chip’s SO
output are connected to the MCU. A sin-
gle chip select line from the MCU drives
the *CS pin of all the ’993s. The entire
lash-up appears as one big circular shift
register of 24 stages per chip. Regarding
the software, the length of the basic
transaction is extended accordingly
(e.g., 48 bits for a two-chip setup).

The parallel approach devotes a chip

select to each ’993 allowing individual
access. The INT pins can be combined
or presented seperately to the MCU.
The latter makes more sense in this
case. If they are combined, the MCU
has to interrogate all of the chips to find
the interrupting one, so the advantage
of individual access is wasted.

Another alternative is to just throw

more MCU pins at the problem and dedi-
cate an interface to each chip. There are
different ways to do this depending on
what’s important to you. Dedicated SI
and SO with a common *CS and SCLK
would support synchronous access and
control at highest speed (i.e., 24 clocks
no matter how many chips). Dedicated
*CS (or SCLK) lines would further sup-
port individual access.

If you’re using multiple chips, there

are a few hazards to watch out for. For
example, it’s possible that a switch
change-of-state may occur during the
issuance of the Sleep command (i.e.,
while *CS is asserted). In such a situa-
tion, the chip will not go into Sleep
mode when the command is issued (i.e.,

collar. Just for laughs, if you perform
the calculation, you’ll find that’s more
than 9 W, which is far more than the
chip’s absolute maximum rating (1.7 W
at 25°C) and small plastic package
allow. Believe me, the last thing a car
maker wants to deal with is electrical
gadgets that spontaneously combust!

To that end, the ’993 includes its own

temperature sensor. If things get too hot
for comfort, the chip will automatically
throttle back all 16-mA current sources
to 2 mA, set the THERMFLG bit in the

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

83

*CS deasserted). That means
you could end up with some
chips sleeping and others
remaining awake. It turns out
that you have to issue a
dummy command to wake
the sleeping chips, and then
issue another to read the actu-
al switch states because
there’s a delay (10 to 20 ms)
required after wake-up for
internal voltages to stabilize.

LIGHT VS. SWITCH

In summary, the ‘993 can

deliver 16 or 2 mA (or no cur-
rent, i.e., tristate) as well as the
option of directly measuring
the voltage level (via AMUX)
on a certain pin. This flexibility
enables some alternate applica-
tions that supplement the chips
basic role as a switch master.

For example, 16 mA is more

than enough to drive a typical
LED or power MOSFET (see
Figure 3). It’s a simple matter of
issuing various commands (e.g.,
reconfigure switch_to_ground
and switch_to_battery settings or
enable/disable tristate) to control the
load. Using an external pull-down resis-
tor, you can check for an open load by
tristating the pin. If the load is connect-
ed, the switch input will pull up to
VPWR; however, if it’s open, the resis-
tor will pull it down to ground.

Indeed, 16 mA is enough to drive all

manner of add-ons, such as a logic chip
or even an LCD. You might have an
application that could take advantage of
the ’993 as a virtual power strip that’s
able to control a myriad of loads in addi-
tion to its normal switch-monitoring

to serve a variety of applications.
None of the limitations (e.g.,
unable to turn the INT timer off)
seem like showstoppers, but who
needs the extra headscratching?

The virtue of the strategy is

that the auto biz is the driver
for technology in the deeply
embedded space, much as the
PC market prods the big silicon
microprocessors to the bleeding
edge. Auto apps push the limits
when it comes to dealing with
the harsher realities of life,
offering extended temperature
operation (the ’993 is specified
for –40° to 125°C) and a robust
electrical interface.

The other good news is that

the volume of chips shipped to
the automotive market helps
drive the price. The ’993 is quot-
ed at $1.63, and that’s at intro-
duction and for 1000 pieces,
according to Motorola’s web site.
As time goes on and volume
ramps up, the price will surely
fall. On the other hand, I’d be a
little concerned about shortages

through the peaks and valleys of the
automotive biz. Motorola will have to be
careful to support the little guy when
the Big Three are clamoring for parts.

The ’993 serves to remind us that

there’s more to the story than cram-
ming everything on a single chip.
Remember, the bigger the chip, the
harder it will fall victim to real-world
glitches and gotchas. A little protection,
and a little chip, can go a long way.

I

duties. You can get even more power by
paralleling channels (e.g., 32 mA from
two channels). Just remember to keep
the overall power dissipation within
limits to avoid thermal shutdown.

Another idea is to use the ’993 to sup-

ply power and bias voltage to a sensor.
There’s even a way to hack an ADC for
a resistive sensor using two lines as
current sources and an additional fixed
resistor to establish a reference. This
relies on the fact that the channel-to-
channel current matching is fairly accu-
rate (2% typical, 4% worst case). More
precise factory calibration measures the
actual difference between two particu-
lar channels and stores a calibration
factor in MCU EEPROM.

MIXED SIGNALS

Motorola’s strategy of offering special-

ized automotive chips to the mainstream
market has promise, but I must admit to
some mixed feelings. The downside is
that the ’993 forces you to live with the
decisions another designer made to fur-
ther their and not necessarily your appli-
cation’s cause. The chip is less versatile
than it would be if designed from scratch

RESOURCE

Motorola, Inc., Multiple Switch
Detection Interface

, MC33993/D,

rev. 1, 2002.

Tom Cantrell has been working on
chip, board, and systems design and
marketing for several years. You may
reach him by e-mail at
tom.cantrell@circuitcellar.com.

SOURCE

MC33993 Detection interface
Motorola, Inc.
www.motorola.com

Photo 4—

The contact wetting option provides 20-ms

of high current to counter oxidation of switch contacts.

V

BATT

LO
AD

1.5 k

100 k

SG0

V

PWR

V

PWR

To SPI

+

4-V Ref.

Comparator

AMUX

SG0

SG13

V

PWR

V

PWR

+

SG13

16 mA

2 mA

4-V Ref.

Comparator

To SPI

V

PWR

V

PWR

To SPI

+

4-V Ref.

Comparator

16 mA

2 mA

2 mA

16 mA

SP0

SP0

16 mA

2 mA

Figure 3—

In addition to normal switch duties, clever designers can trick the

MC33993 into handling other tasks, such as driving a power MOSFET or LED.

background image

84

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

IDEA BOX

THE

DIRECTORY

OF

PRODUCTS AND

SERVICES

AD FORMAT

: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.

ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2

″″ ××

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.

Suppliers Directory now available online. Check out our web site

www.circuitcellar.com to see who has what and how to get it!

Insert-ready Single Board Computer modules in sub-miniature

dimensions (as small as 47x55 mm) populated by:

8-bit:

ADuC812

,

AT89C51CC01

,

DS80C390

,

P87C591

,

P89C51Rx2

,

P89C66x

,

P89C51MX

16-bit:

C167CR

,

C167CS

,

XC161CJ

,

XC167CI

,

PXAC3

,

PXAG49

,

ST10F168

,

ST10F269

32-bit:

AT91M55800A (ARM7TDMI core)

,

Elan SC520

,

MPC555

,

MPC565

applicable controller signals extend to standard pin header (2.54

mm) or high-density Molex (0.625 mm) connectors, enabling SBC

to be plugged like a “big chip” into OEM targets

Low EMI design

achieved via GND circuitry, multi-layer PCB, by-

pass capacitor grid and short signal traces achieved via small

footprint and use of 0402 SMD passive components

32 KB to 64 MB external SRAM and Flash (controller-dependent)

CAN, Ethernet, RS-232 and RS-485 interfaces; ADC, DAC

(controller-dependent); freely-available /CS and I/O lines

available in

Rapid Development Kit

including Development Board,

AC adapter, serial cable and SPECTRUM CD with eval software

tools, electronic documentation and demos

Stick It In!

: insert-ready PHYTEC SBC modules accompany you

from evaluation through protyping to end production...

accelerating your design cycle and reducing your time-to-market

www.phytec.com

phyCORE

®

New Generation
Single Board Computer

(800) 278-9913

PHYTEC America, LLC

203 Parfitt Way SW, G100

Bainbridge Island, WA 98110 USA

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

85

to

RS232

to

TCP/IP

TCP/com v2.0,

RS232 to TCP/IP software.

Plus TCP/IP to RS232.
WinWedge, RS232 or TCP/IP

data direct into any Windows

app. - Excel, Access, etc.

Free 30 day evals at

www.taltech.com

R

TM

NEW

tm

tm

PC KEYBOARD EMULATION

Interface Keypads, Switches, or RS-232 to your PC Keyboard Input

MODEL KE24

ONLY $

99

95

• Up to 12 x 12 matrix • Programmable • RS-232 Port • Macro Capability

The KE24 is the ultimate in flexibility. Inputs or serial data can

emulate any of the 101 keys from a standard keyboard.

MODEL KE18

ONLY $

44

95

• Up to 9 x 9 matrix • 2.5" x 3.0" Size • PC Keyboard Port • PCXT, AT Compatible

The KE18 combines a multitude of features with small size at an

economical price. Custom units available.

HAGSTROM

ELECTRONICS

11 Fiddlers Green

Lansing, NY 14882

Toll Free: 888-690-9080

Phone: 607-533-4441 Fax: 607-533-4443

www.hagstromelectronics.com

background image

86

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Mosaic Industries Inc.

tel: 510-790-1255 fax: 510-790-0925

www.mosaic-industries.com

Controller, Operator Interface

and I/O for Any Instrument

Use the QVGA Controller

TM

for machine control, embedded

systems, scientific instruments, and OEM applications -

wherever you need an I/O-rich computer and a smart user

interface!

R

EADY

-M

ADE

G

RAPHICAL

U

SER

I

NTERFACE

•

Bright, High Contrast 1/4 VGA (320x240 pixel)

Electroluminescent (EL) or Monochrome Display

•

High-resolution touchscreen

•

Precoded menu managing software

P

OWERFUL

C

ONTROLLER

•

Programmable in C and Forth

•

Multitasking RTOS

A

LL

THE

I/O Y

OU

N

EED

•

48 Analog & Digital I/O Lines

•

Expansion I/O modules

P

LENTY

OF

M

EMORY

•

Up to 768K Flash, 640K RAM

•

64Mbyte Mass Memory

JK



microsystems

Call

530-297- 6073

Email

sales

@

jkmicro.com

On the web at

www.jkmicro.com

l

Flashlite 186 controller

l

Borland C/C++ ver 4.52

l

FREE Email Tech Support

l

Serial Driver library

l

AC Adapter and cable

l

186 processor

@

33 MHz

l

DOS w/ Flash File system

l

44 Digital I/O lines w/ CPLD

l

Console / Debug Serial Port

l

7-34V DC or 5V DC power

l

Accepts 8MB DiskOnChip

l

512K DRAM & 512K Flash

l

Expansion options with Peripheral Boards

Flashlite

l



2

Serial Ports

l

2 16-bit Timers

l

Watchdog Timer

186

Development

System

$

99

$

69

QTY 1

Development kit includes:

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

87

background image

88

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

sales@sealevel.com 864.843.4343

www.sealevel.com

USB to Serial

• 1,2,4, and 8-port models

• RS-232, RS-422/485, and

RS-232/422/485 versions

• Supports data rates up to 921K bps

Ethernet Serial Servers

• 1,2,4, and 8-port models

• Ethernet 10/100Base-T (autosense)

• RS-232, RS-422/485, and

RS-232/422/485 versions

• Easy-to-use software included

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

89

background image

90

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

91

background image

92

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 157 August 2003

93

Email: sales@picofab.net

background image

Design a Wide-Range RS-232 Concentrator Box

RS-485 Network for Embedded Systems

Microprocessor Glue Logic with Verilog HDL

LCD-Based Color Clock: Tell Time Anytime

I Applied PCs: Speed Racer: Stand-Alone, Track-Timing Pinewood Derby Computer

I From the Bench: Next-Generation Text to Speech: Winbond Makes Strides with the
WTS701

I Silicon Update: ESCape to SF

Preview of September Issue 158

Theme: Internet & Connectivity

94

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

91

Abacom Technologies

85

ActiveWire, Inc.

19

AeroComm, Inc.

42

All Electronics Corp.

90

Amazon Electronics

93

AP Circuits

73

Arcom

7

Atmel

85

Avocet Systems, Inc.

91

Bagotronix, Inc.

90

Basic Micro

91

Bellin Dynamic Systems, Inc.

30

CadSoft Computer, Inc.

87

Carl’s Electronics

27

CCS-Custom Computer Services

92

Conitec

35

Connecticut microComputer, Inc.

84

Cyberpak Co.

1

Cypress MicroSystems

90

CWAV

91

DataRescue

90

Delcom Engineering

84

Deys Electronics, Inc

86

Digital Products

34

Earth Computer Technologies

47

Easy-Radio USA

87

EE Tools

(Electronic Engineering Tools)

35

EMAC, Inc.

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page

90

Embedded Micro Software

74

ESC-Boston

89

eProtos

17

ExpressPCB

85

FDI-Future Designs, Inc.

92

Front Panel Express

92

Futurlec

85

Hagstrom Electronics

15

HI-TECH Software, LLC

80

ICOP Technology Inc.

89

IMAGEcraft

89,93

Intec Automation, Inc

85

Intrepid Control Systems

91

Intronics, Inc.

65

Jameco

64, 86

JK microsystems, Inc.

84

JPA Consulting

27

JR Kerr Automation & Engineering

43

K-Team SA

43

LabJack Corp.

43

Lakeview Research

39

Lemos International

2

Link Instruments

16

Linx Technologies

82

MaxStream

90

MCC (Micro Computer Control)

69

Microchip

92

microEngineering Labs, Inc.

81

Micromint

27

MJS Consulting

86

Mosaic Industries, Inc.

63

Motorola

58

MVS

86

Mylydia Inc.

C2

NetBurner

88

OKW Electronics, Inc.

10

On Time

92

Ontrak Control Systems

66

PCB123

10

PCBexpress

87

PCB Fab Express

C4

Parallax, Inc.

84

Phytec America LLC

87

Phyton, Inc.

93

Picofab Inc.

86

Pioneer Hill Software

86

Prairie Digital, Inc.

93

Pulsar, Inc.

91

Q-Kits

88

R2 Controls

57

R4 Systems Inc.

49

Rabbit Semiconductor

66

Remote Processing

5,25

Renesas Technology Corp.

23

Renesas Contest

90

RLC Enterprises, Inc.

Page

Page

Page

88

RobotBooks.com

77

Saelig Company

3

Scott Edwards Electronics Inc.

88

Sealevel Systems

86

Senix Corp.

95

Sierra Proto Express

84

Signum Systems

86

Softfield Technology Inc.

93

Softools

84

Square 1 Electronics

11

Systronix

85

TAL Technologies

88

TLData Corp.

C3

Tech Tools

89

Techniprise

32,33

Technologic Systems

85

Technological Arts

89

Tern Inc.

91

Triangle Research Int’l, Inc.

69

Trilogy Design

89

Vesta Technology, Inc.

93

Weeder Technologies

93

Xeltek

87

Z-World

88

Zanthic Technologies Inc.

55

Zilog, Inc

October Issue 159

Deadlines

Space Close: Aug 11

Material Due Date: Aug 19

Theme:

Data Acquisition

A

TTENTION

A

DVERTISERS

Call Sean Donnelly to

reserve your space!

860.872.3064

e-mail: sean@circuitcellar.com

B

ONUS

D

ISTRIBUTION

Sensors Expo

INDEX OF ADVERTISERS

background image

For Unparalleled
Quality, Technology,
Delivery and Price

Insist on 2 to 24 layer
PCBs from Sierra Proto
Express

q

u

a l

i t y l e a d

e

r

M

IL

-P-5

5110 ISO

90

0

2

80

0-

76

3-7

503

www.protoex

pre

ss

.c

om

We offer the highest quality, the broadest range of technology (2 – 24 layers), the fastest, most
reliable turns (99% on-time delivery) and a competitive price. And we prove it every day,
with every PCB we ship.

With every multilayer order you receive "Evidence of Quality" which is a
set of 5 reports. Microsection Analysis, such as the one featured here, is
one of those reports, which provides a proof that your board meets or
exceeds your specifications.

Order from us, benchmark our quality, technology, delivery and
service with whoever you are currently doing business with, send us
that report and

receive our special polo shirt commemorating our

17th year of success.

Mention promotion code: PPDB00043.

For proven quality that never costs extra,
put Sierra Proto Express
on your team today.

Call our expert Technical Advisors at

800.763.7503

or visit us at

www.protoexpress.com

Microsection

14 Layer Board

background image

C

ontest closing is a hectic time around Circuit Cellar. Not so much because it’s crazier than any other time, but because contests have

become my personal fiefdom and a lot happens at the last minute. My official title may be Editorial Director, but I have really come to enjoy
being the Contest Administrator, too.

I’ve said this before, and I’ll say it again: contests are a big deal at Circuit Cellar because we do them right, and we do them for mutual

benefit. What’s that mean? Well, one of the reasons you read Circuit Cellar is because we publish real-world embedded applications. When
we run a design contest, we aren’t doing it as some advertising scheme, we’re doing it to build a fire under the design community. Entrants
get an opportunity to walk away with some big cash (there’s $30K in prize money in the Motorola Flash Innovation 2003 Design Contest), and
we get to publish and post some really great projects.

The best part of personally doing the contest job has been communicating with entrants and realizing that contest participation is mutual-

ly beneficial. My incentive is that it is a good way to find authors. Surprisingly, however, by talking to entrants, I am finding out that having
Circuit Cellar publish their project entries has had major benefits for their careers. Dozens of past entrants and winners have written to me
describing how much they enjoy the increased respect at work and in the professional community.

More than a few have said they can attribute a bonus, job promotion, or outright career change to a Circuit Cellar contest. The most recent

example of this is Robert Lacoste. If you’ve been reading Circuit Cellar for a while, you’ll recognize his name from many past contests. If I
remember correctly, he’s won prizes in seven different contests in the last four and half years. A couple weeks ago, Robert wrote me that he
was leaving his job as Director of a large company and starting his own design business (www.alciom.com). His world-wide design reputation,
frequently demonstrated in the pages of Circuit Cellar, along with a network of semiconductor manufacturer contacts (all the contest sponsors)
has provided the perfect incentive to capitalize on everything and go it alone. Given his past performance, I know Robert will do well.

As I write this, the Motorola contest entries are arriving. I know there are a number of repeat entrants like Robert who love the challenge,

but it’s amazing what the new guys think up for projects. It’s a good thing part of the judging criteria is originality. Here are some of the entries
in the in-basket so far: a neat touch-screen controller for LCDs; an acoustic wave soil moisture detection system; a magic-lamp lighting effects
controller, a wireless mousetrap-monitoring system; a microwave radar-guided automobile cruise control system; a blood pressure monitor;
and a number of other equally interesting designs.

I especially appreciate entries that teach me something new. Has anyone besides me never really thought about acoustical cellular automa-

ta parallel processing? Just so you aren’t scratching your head for the two to three months it takes to post contest projects, the closest I can
describe this concept is to think of the game of Life that we all played on early computers. Now, substitute processors with four eight-tone
sound transducers for the individual cells in a large array. The overall sound effect, whether seemingly chaotic or orderly, is governed by the
rules used to generate new cell states in the game of Life. I plan to go back and ask the cellular automata entrant to send me a recording.
This I have to hear.

Fortunately, the evolution in video technology has helped in understanding some of the other projects. More than a few entrants have

included video clips this time around. For example, watching as the Follow-Me Greeter Grandfather Clock turns and follows the direction of
the contestant as he walks through the living room and greets him both coming and going definitely explains the concept better than words.
Of course, there’s also the video showing a PC ventilation-failure detector where the contestant adds a little excitement by using a blowtorch
to simulate an overheated enclosure. Pyrotechnics aside, the expanding concept of contest entry ingredients these days undoubtedly helps
in understanding the project and adds zest to dull schematics and software listings. Of course, our contests have always been about adding
a little zest to the whole notion of embedded design.

Contest Zest

PRIORITY INTERRUPT

steve.ciarcia@circuitcellar.com

96

Issue 157 August 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

by Steve Ciarcia, Founder and Editorial Director

background image
background image

Wyszukiwarka

Podobne podstrony:
circuit cellar1996 08
circuit cellar1994 08
circuit cellar1990 08,09
circuit cellar1992 08,09
circuit cellar1991 08,09
circuit cellar1995 08
circuit cellar1997 08
circuit cellar2001 08
circuit cellar1993 08
circuit cellar2002 08
circuit cellar2000 08
circuit cellar2004 08
circuit cellar1996 08
circuit cellar1994 08
circuit cellar1991 08,09
circuit cellar2002 08
circuit cellar1990 08,09
circuit cellar1994 08

więcej podobnych podstron