circuit cellar2004 05

background image

7

9

25274 75349

0 5>

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)

#166 May 2004

COMMUNICATIONS

Programmable IR Receiver

Ethernet Bootloader

Integrate Bluetooth

Build an I

2

C Slave

background image
background image
background image

Digital Oscilloscopes

2 Channel Digital Oscilloscope

100 MSa/s

max single shot rate

32K samples per channel

Advanced Triggering

Only 9 oz and 6.3” x 3.75” x 1.25”

Small, Lightweight, and Portable

Parallel Port

interface to PC

Advanced Math options

FFT Spectrum Analyzer options

DSO-2102S

$525

DSO-2102M

$650

Each includes

Oscilloscope

,

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

40 to 160 channels

up to 500 MSa/s

Variable Threshold

8 External Clocks

16 Level Triggering

up to 512K samples/ch

Optional Parallel Interface

Optional 100 MSa/s Pattern Generator

LA4240-32K (200MHz, 40CH)

$1350

LA4280-32K (200MHz, 80CH)

$2000

LA4540-128K (500MHz, 40CH)

$1900

LA4580-128K (500MHz, 80CH)

$2800

LA45160-128K (500MHz, 160CH)

$7000

www.LinkIns4.com

Link Instruments

369 Passaic Ave

Suite 100

Fairfield, NJ 07004

(973) 808-8990

Fax (973) 808-8786

Logic Analyzers

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

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

$800

All prices include Pods and Software

background image
background image

I

t is said that communication is the key to any good relationship. The

same is true for an embedded design. Poor communication ability can
spell disaster for an application. Before you start on your next project,
check out the communication solutions in this month’s features. These
authors share the engineering lessons they learned along the way, pro-
viding you with valuable tips that may help you improve your designs.

We decided to start off with something fun. We have a great project

for those of you who spend more time working on your home enter-
tainment system than actually using it. By using a PC-based multime-
dia system, you can turn your living room into a state-of-the-art enter-
tainment center. But, now you have to use a keyboard to control it. For
physicists Sergio and Guido Torrioli, the keyboard wasn’t an annoy-
ance, but a challenge to overcome. They built a programmable IR
receiver to control the system remotely. After you read about this
PIC16F84A-based project, you’ll be ready to upgrade your home enter-
tainment system (p. 10).

Our next project gets you ready to work with Bluetooth. We have

good news for those of you who have shied away from using Bluetooth
because you assumed it would be too complicated. In “Simple
Bluetooth Integration,” Anders Rosvall assures us that integrating
Bluetooth in embedded applications is easier than it looks (p. 22). In
this two-part series, Anders explains how simple integration has
become and provides an application you can work with.

When considering which communication protocol to implement, I

2

C

is definitely a popular choice. But, it does present obstacles.
Fortunately, Anton Kruger has solved a common dilemma of working
with I

2

C (p. 52). Although he was always able to find a variety of

resources for I

2

C master devices, there were few options to choose

from when he wanted to create slave devices. He found that most solu-
tions to build a slave device came with a host of problems. However,
we’re pleased to report that Anders worked out an effective alternative
to the usual methods. The Atmel ATtiny and ATmega processors offer
a fresh solution that eliminates the typical pitfalls associated with con-
verting sensors into slaves. The Atmel processors feature built-in hard-
ware for I

2

C communication, known as the universal serial interface

(USI). Using the USI, it’s easy to create your own I

2

C slave.

In addition to these communication projects, Ingo Cyliax is back this

month with an article on how to enhance your embedded applications
by going wireless. By adding an Ethernet-to-Wi-Fi bridge, you can eas-
ily convert an Ethernet-based application to a wireless one. With count-
less low-cost components to choose from, going wireless with Wi-Fi
gives you the freedom of choice and won’t break the bank, either. Turn
to page 32 to learn more about this simple and cost-effective solution.

4

Issue 166 May 2004

www.circuitcellar.com

CIRCUIT CELLAR

®

EDITORIAL DIRECTOR/FOUNDER
Steve Ciarcia

MANAGING EDITOR
Jennifer Huber

TECHNICAL EDITOR
C.J. Abate

WEST COAST EDITOR
Tom Cantrell

CONTRIBUTING EDITORS

Ingo Cyliax
Fred Eady
George Martin

George Novacek
Jeff Bachiochi

NEW PRODUCTS EDITOR
John Gorsky

PROJECT EDITORS
Steve Bedford
Ken Davidson
David Tweed

ADVERTISING

PUBLISHER

Dan Rodrigues

E-mail: dan@circuitcellar.com

ASSOCIATE PUBLISHER/DIRECTOR OF SALES

Sean Donnelly

Fax: (860) 871-0411

(860) 872-3064

E-mail: sean@circuitcellar.com

Cell phone: (860) 930-4326

ADVERTISING COORDINATOR

Valerie Luster

Fax: (860) 871-0411

(860) 875-2199

E-mail: val.luster@circuitcellar.com

ADVERTISING ASSISTANT

Deborah Lavoie

Fax: (860) 871-0411

(860) 875-2199

E-mail: debbie.lavoie@circuitcellar.com

CONTACTING CIRCUIT CELLAR

SUBSCRIPTIONS:

INFORMATION: www.circuitcellar.com or subscribe@circuitcellar.com
To Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, or
subscribe@circuitcellar.com
PROBLEMS: subscribe@circuitcellar.com

GENERAL INFORMATION:

TELEPHONE: (860) 875-2199 Fax: (860) 871-0411
INTERNET: info@circuitcellar.com, editor@circuitcellar.com, or www.circuitcellar.com
EDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066
NEW PRODUCTS: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066
newproducts@circuitcellar.com

AUTHOR CONTACT:

E-MAIL: Author addresses (when available) are included at the end of each article

CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub-

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

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

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

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

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

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

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

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

For information on authorized reprints of articles,

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

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

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

Entire contents copyright © 2004 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks
of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

CHIEF FINANCIAL OFFICER

Jeannette Ciarcia

CUSTOMER SERVICE

Elaine Johnston

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

Improve Your Communication Skills

jennifer.huber@circuitcellar.com

TASK MANAGER

background image

Their boards come with a

packing slip. Ours come

with a

Microsection

Analysis Report

In today’s competitive climate, offering the
best product at a competitive price is a must
to satisfy your customers. Sierra Proto
Express offers the fastest, most reliable, turns
at the highest quality. And we’ll prove it in
every shipment with our unique Evidence of
Quality reports, so you know your board is
right the first time. One proof of quality is
our Microsection Analysis Report, as
featured here, so you can see the quality
inside your board. And that is just part of
our comprehensive quality tests. It’s in our
process, not in our price. In fact, it is our
commitment to total quality that enables us
to run our operation cost effectively. And
that comes back to you in our competitive
price. Talk to a Sierra Proto Express Account
Manager about our commitment to quality,
our range of technology, and our 99%
on-time track record of delivery. Call
1.800.763.7503 from 6 a.m. to 6 p.m. PST
or email your design to
files@protoexpress.com and receive a quote.
Mention code: PPDC00093

For proven quality that never costs
extra, put Sierra Proto Express on
your team today.

14 Layer Board

Microsection

Q u a l i t y O n Ti m e

Learn more about our unique Evidence of

Quality report that comes with every PCB

at www.protoexpress.com

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

background image

6

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

May 2004: Communications

10

Programmable IR Receiver for PCs

Sergio Torrioli and Guido Torrioli

16

Embedded Java Controllers

D. Jay Newman

22

Simple Bluetooth Integration (Part 1)

Implementing Bluetooth Modules
Anders Rosvall

32

Wi-Fi-Enabled Embedded Control

Ingo Cyliax

36

Ethernet Bootloader

Andrew Smallridge

52

USI-Based I

2

C Slave

Anton Kruger

60

Get Moving with the MC34921 Power System Control IC

Fred Eady

4

TASK MANAGER
Improve Your Communication Skills

Jennifer Huber

8

NEW PRODUCT NEWS

edited by

John Gorsky

9

TEST YOUR EQ

edited by

David Tweed

46

APPLIED PCs

Radio Roundup

Fred Eady

68

FROM THE BENCH

USB in Embedded Design (Part 2)

HIDmaker Converts an Application
Jeff Bachiochi

78

SILICON UPDATE

The Heat is On

Tom Cantrell

FEATURES

COLUMNS

DEPARTMENTS

94

INDEX OF ADVERTISERS

June Preview

96

PRIORITY INTERRUPT
All Washed Up

Steve Ciarcia

Motor Control IC Project (p. 60)

Working with JStamps (p. 16)

Temperature Sensors Overview (p. 78)

background image
background image

8

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

TINY USB MODULE

The new QS Series USB module allows the rapid and cost-

effective addition of USB to virtually any device. Housed in a
compact SMD package, the QS module provides a complete
solution for bidirectional data transfer between USB and
CMOS/TTL-level sources. The module can be directly connect-
ed to any serial device, including microprocessors, RS-232/485
level converters, and Linx wireless RF modules. The QS USB
module requires no external components (except a USB jack),
and it includes all necessary firmware and drivers, freeing you
from complicated programming. Power can be supplied from an
external 5-VDC supply or directly from the USB bus. Both USB
1.1 and USB 2.0 are supported at data rates up to 3 Mbps. The
SDM-USB-QS1-S USB module costs $9.80 in volume quantities.

Linx Technologies, Inc.
(541) 471-6256
www.linxtechnologies.com

Edited by John Gorsky

USB RF MODEMS

The 9XStream-PKG-UA and 24XStream-PKG-UA are USB-

enabled radio frequency modems that allow for quick testing,
monitoring, and control of MaxStream wireless systems
through a laptop or stationary PC’s USB port. These high-
performance FCC- (U.S.), IC- (Canada), and ETSI-approved
(Europe) RF modems provide 140 (900 MHz) or 50 mW
(2.4 GHz) of power output, and are ideally suited for remote
and mobile applications. They boast up to –110-dBm receiver
sensitivity, providing long-range communication.

These modems receive 900-MHz transmissions up to

1500

(457 m) in an urban environment, up to seven miles

(11 km) line of sight, and up to 20 miles (32 km) with
high-gain antennas. These RF modems utilize frequency-
hopping spread-spectrum
technology in peer-to-peer,
point-to-point, point-to-
multipoint, and multidrop
networking configurations.
These RF modems cost
$250 (900 MHz) and $199
(2.4 GHz). Volume dis-
counts are available.

MaxStream, Inc.
(801) 765-9885
www.maxstream.net

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

9

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

An air-driven piston might be a

good way to achieve constant acceleration. If you
have a piston/cylinder with an area of 10 cm

2

(about 1.55 inches squared), how much pressure
is required?

Problem 4

In a single-conversion superhet

receiver, it is often desirable to put the local oscil-
lator frequency above the incoming RF frequency
in order to place the image frequencies farther
away from the IF passband. What effect does this
have on SSB demodulation?

Contributed by David Tweed

Edited by David Tweed

Problem 1

Suppose you have a small pack-

age that needs to be accelerated to 45 m/s
(about 100 mph), but you have to do this on a
rail that’s just 2 m long. The package will be
released at this velocity when it reaches the end
of the rail. Assuming you can find a way to do
this with constant acceleration, how much accel-
eration do you need? How long does it take?

Problem 2

The package in Problem 1 weighs

up to 500 g (just over 1 lb). How much energy
does it take to accelerate it to 45 m/s? How
much power?

background image

referred to as “PS/2 keyboards.” Older
keyboards that use a five-pin DIN
connector are called “AT keyboards.”
The two are similar; the connector is
the only practical difference between
them. This means the two types can
be easily changed with simple hard-
wired adapters. Figure 2 shows the pin
assignments for each connector.

The PS/2-AT keyboard has a scan

code associated with each key. There
are three standard scan code sets named
from one to three. Set two is the default
set. In this article we refer exclusively
to the default scan code set.

After a key is pressed, the associat-

ed scan code is transmitted to the host
PC. When the key is released, a break
code (0xF0) is transmitted followed by
the key scan code. A scan code only
represents a key on the keyboard, and

there is not any relationship
with the ASCII code. The host’s
task is to translate scan codes to
characters or commands.

Most of the keys are represent-

ed by a 1-byte scan code. Other
keys—such as the Insert, Delete,
and Home keys—have a 2-byte
code (extended scan code) in
which the first is always 0xE0.
Photo 1 shows the scan code
associated with each key in
hexadecimal representation for
an English language keyboard.
For example, if you press the

Escape key, the keyboard sends
0x76 to the host. When you

10

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

W

e came up with the idea for a

programmable IR receiver after deciding
to use an old PC as a stand-alone multi-
media player connected to a TV and hi-fi
equipment. The PC is based on a Duron
800-MHz processor, which is suitable for
playing demanding DivX files—the popu-
lar compression video format. We also
wanted the ability to control the system
from a distance while sitting comfort-
ably in our armchairs.

Most PC programs are controlled

with a keyboard, so a cordless keyboard
is a straightforward solution. Even so,
we thought a keyboard would be too
cumbersome. Therefore, we built an IR
receiver that we can place between the
keyboard and PC or even replace the
keyboard altogether (see Figure 1). The
receiver, which decodes a common IR
remote control and sends the proper
commands to the PC, emulates
the keyboard itself.

We used the popular Microchip

PIC16F84A. The firmware was
developed to recognize the com-
mands sent by a remote control
based on the Philips RC5 standard.
The correspondence between the IR
command detected by the receiver
and the command sent to the PC is
mapped in the microcontroller’s
permanent memory. Obviously, the
list of commands could have been
hard-wired; however, we imple-
mented a programming mode in
order to fully customize the
receiver. In this mode, the storing

Programmable IR Receiver for PCs

If you have a PC-based multimedia system in your living room, you can take that wireless
keyboard off your lap. After converting an old PC into a multimedia player, Sergio and Guido
built a programmable IR receiver that controls the PC from a distance. The PIC16F84A-driv-
en system can decode a standard IR remote control and send commands to a PC just like
a keyboard. Relaxing just got easier.

operation of the list of commands that
we want to emulate can be achieved easi-
ly when the receiver is placed in its oper-
ative position between the keyboard and
PC. It is sufficient to run a text editor
program like Notepad and follow the
instructions sent by the receiver through
the keyboard port that appears in the
corresponding program window.

The firmware was the most difficult

aspect of the project because we had
to implement the PS/2-AT protocol
for the keyboard communication and
the RC5 protocol for the remote con-
trol reading. Before we describe the
receiver, we’ll briefly outline the two
standards that we used.

KEYBOARD PROTOCOL

Modern PC keyboards, which use a

six-pin mini-DIN connector, are often

FEATURE ARTICLE

by Sergio Torrioli & Guido Torrioli

Figure 1—

The receiver is placed between the keyboard and computer.

When an IR command is recognized, it sends a command to the com-
puter, emulating the keyboard.

PC

IR Receiver

Keyboard

Remote control

background image

source generates infrared radiation),
the infrared communication is based
on an IR carrier modulated by data
signal. A receiver’s task is to demodu-
late the signal to restore the original
datastream before the process of
decoding. The RC5 standard specifies
36 kHz for the carrier wave frequency.

The RC5 code consists of a train of

14 bits of fixed length. Each bit lasts
for 1.778 ms (i.e., 64 times the carrier
period). The entire train is repeated
approximately every 100 ms.

The code is based on biphase encod-

ing, or Manchester encoding, in which
every bit comprises the two logic lev-
els with a transition in the middle. If
the transition is low-to-high, the coded
bit is 1. If the transition is high-to-low,
the coded bit is 0. Figure 4 shows an
example of an RC5 code word.

The first 2 bits, which are always 1,

are used to calibrate the automatic
gain control in the receiver. The third
bit is the toggle bit, which toggles
every time a key is pressed. This fea-
ture provides an easy way of deter-
mining whether a key is pressed and
held down or pressed and released
continuously. The next 5 bits are used
for the system address so that only the
addressed system responds to the
code. The most significant bit is trans-
mitted first. The last 6 bits are the
command bits that determine which
key has been pressed on the remote
control. Again, the most significant
bit is transmitted first.

HARDWARE

The receiver’s schematic diagram is

simple (see Figure 5). Based on the
PIC16F84A, only five I/O pins are
involved: two for communication
with a keyboard, two for communica-
tion with the host, and one to receive
signals from the IR sensor.

keyboard. The keyboard can begin
transmitting data only when both
lines are high. The host can inhibit
communication at any time by pulling
the clock line low.

When the host wants to transmit, it

first pulls the clock line low in order
to prevent the keyboard from sending
data. It then drives the data line low
and releases the clock. This sequence
is interpreted by the keyboard as
“Request to Send” and then starts
generating clock pulses.

Figure 3 illustrates the host-to-key-

board and keyboard-to-host communi-
cation. During the host-to-keyboard
protocol, the keyboard pulls the data
line low and generates an extra clock
transition to acknowledge the reception
of the data after the parity bit has been
sent and the data line is in an idle state.

RC5 STANDARD

Originally developed by Philips, the

RC5 code is a widely used standard for
infrared remote control in audio and
video systems. In order to ensure
immunity to interference from other
infrared sources (every heat-emitting

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

11

release the key, the code 0xF0, 0x76 is
sent. If you press the Home key, the
keyboard sends 2 bytes (0xE0 and
0x6C). When the key is released, the
code 0xE0, 0xF0, 0x6C is sent.

Keyboards can send or receive con-

trol commands from the host in addi-
tion to sending scan codes. Table 1
contains some of these commands,
including those used in this project.

The electrical interface between the

keyboard and the PC is based on four
lines. The V

CC

and ground lines pro-

vide power to the keyboard. The data
and clock lines make the signal bus
used to exchange commands and data.
They are both open-collector with a
pull-up resistor to V

CC

, so the idle

state of the bus is high, and the host
PC or keyboard can drive them down.

The data transfer is implemented as

bidirectional serial protocol. The key-
board always generates the clock sig-
nal. Every byte is transmitted with
1 start bit (always low), 8 data bits
(LSB first), 1 odd parity bit, and 1 stop
bit (always high). The clock frequency
is between approximately 10 and
20 kHz; it can vary from keyboard to

1

4 2 5

3

Clock

GND

Data

5 V

NC

5

6

4

3

2

1

Clock

GND

Data

NC

5 V

NC

Five-pin DIN (AT)

Six-pin mini-DIN (PS/2)

Figure 2—

AT keyboards and PS/2 keyboards are simi-

lar. The only difference is the connector.

Photo 1—

Each key on a keyboard is represented by a scan code. Most of the keys have a scan code of 1 byte.

Others have a 2-byte code and are called extended scan code.

Table 1—

The keyboard and host can exchange commands.

Host Commands

Description

0xFF

Reset: Reset keyboard. Keyboard responds with ACK (0xFA).

0xFE

Resend: Keyboard retransmits the last sent scan code.

0xF0

Set scan code set: Keyboard replies with ACK (0xFA), and then waits for a

second byte (0x01, 0x02, 0x03) specifying the scan code set to use.

0xF2

Read ID: Keyboard responds by sending two ID bytes: 0xAB and 0x83.

0xEE

Echo: Keyboard responds with an echo (0xEE).

0xED

Set status LEDs: Keyboard responds with ACK (0xFA), and then waits for a

second byte, which controls their status. Bit 0 sets the scroll lock,

bit 1 the number lock, and bit 2 the caps lock. The other bits are ignored.

Keyboard commands

Description

0xFA

ACK: Acknowledge

0xAA

BAT (basic assurance test) successful: Power-on self-test passed.

0xEE

Echo

0xAB, 0x83

Keyboard ID

background image

12

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

The firmware must then be able to

communicate with three different
devices using their own protocol.
Communication with the keyboard
and host is based on the PC keyboard
protocol, and the one with the remote
control, on the RC5 standard.

In our case, communication with

the keyboard is unidirectional, from
the keyboard to the receiver, because
we are not interested in sending com-
mands to the keyboard. To perform
the communication, we implemented
a

receive_key routine, with which

RB1 and RB2 pins (clock and data
lines) are set to input. Data is taken
on the data line at every high-to-low
transition in the clock line. The
resulting byte is then stored in the
read_key register. Conversely, commu-
nication with the host is bidirectional.
This is because the receiver, which is
emulates a keyboard, besides sending
scan codes to the host, must be able to
receive possible commands from the
host and to reply.

The

receive_host and transmit

routines have been implemented in
the code in order to permit the recep-
tion and transmission of data with the
host. The former is designed to receive
1 byte from the host. It first waits for
the RB4 pin (i.e., clock line) to become
high. Then it takes control of this line

As we mentioned before,

the data and clock lines in
the keyboard bus are tied
with a pull-up resistor to 5
V. The pull-up resistors are
located on the host side. We
included two pull-up resis-
tors on the lines facing the
keyboard side. The SW1
switch was included to
bypass the receiver and to
use the keyboard directly
connected to the host. We
suggest using the switch in
this position (i.e., receiver
bypassed) to let the keyboard commu-
nicate with the host during the PC
bootstrap. Note that the host powers
the receiver. It doesn’t need an external
power supply.

The IR sensor is the Sharp IS1U60, a

device designed specifically for remote
control detecting. The circuitry in this
device takes an incoming IR signal with
a carrier at approximately 36 kHz,
strips off the carrier, and provides you
with a clean datastream that repre-
sents the original encoded signal on
the transmitting remote control.

FIRMWARE

You may download the firmware,

which was developed in assembly lan-
guage, from the Circuit Cellar ftp site.
After the BAT command is sent to the
host, the code continuously polls
microcontroller pins RA2 (IR line),
RB2 (data line on keyboard side), and
RB4 (clock line on host side) in order
to reveal signals coming from the IR
remote control, the keyboard, and the
host respectively (see Table 1).

After a signal coming from the IR sen-

sor is detected, the firmware decodes it,
compares it to those in the microcon-
troller’s EEPROM, and sends a corre-
sponding scan code to the host. When
a signal from the host is detected, the
code checks if the host wants to send a
command and, in this
case, sends back a proper
reply. Finally, when a sig-
nal from the keyboard is
sensed, the code checks
whether or not the key
pressed is the Scroll Lock
key. If so, the code enters
Programming mode.

and generates a series of
pulses during which it
reads the RB5 pin (data
line) and stores the read-
ing in the read_host regis-
ter. At the end the rou-
tine, it takes control of
the data line in order to
generate the acknowledge
bit.

The

transmit routine’s

task is to send a byte to

the host. The byte to be
transmitted must be placed
in the scan_code register.

The code first checks if the RB4 and
RB5 pins are high (idle state) and then
sets them to output. Next, it starts
generating a clock signal on the clock
line and driving the data line high or
low, depending on what’s stored in
the scan_code register. Prior to send-
ing the stop bit, the routine calculates
and sends the parity bit as specified by
the protocol.

The management of the bytes to be

sent back in reply to a command
received from the host is achieved by
the

check_host routine. This routine

checks if a “Request to Send” command
is transmitted from the host. As you
know, the “Request to Send” command
consists of lowering the clock line for at
least 100 µs, and then bringing the data
line to low and releasing the clock line.
When this combination is sensed, the
routine receives the command from the
host and transmits a reply byte. For sim-
plicity, the code recognizes only the
Read ID (0xF2) command in which case
the routine replays the 2 bytes—0xAB
and 0x 83 (see Table 1). In all other
cases, the command and 0xFA
(acknowledge) are sent. Note that this
acknowledge command is different
from the case in which the keyboard
generates the acknowledge bit on the
data line at the end of every byte
received from the host.

Communication with

the remote control is
clearly unidirectional
from the remote control
to the receiver. In this
case the

receive_ir

routine decodes the
commands sent by the
remote.

Clock

Keyboard-to-host communication

start bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 parity

Data

stop

Clock

Data

start

bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 parity stop ack

Host-to-keyboard communication

Figure 3—

The keyboard bus consists of clock and data lines. They are both open-col-

lector with pull-up resistors to V

CC

.The colored lines reflect which device drove the lines

low. Blue represents the host and red represents the keyboard.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Start bits

Toggle

System address bits

Command bits

1

1

1

1

0

0

0

0

0

0

0

0

0

0

1.778 ms

Figure 4—

The RC5 standard consists of 14 bits encoded according to the Manchester code.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

13

For simplicity, the routine decodes

only the last 8 bits of the 14 bits con-
tained in the RC5 data frame, in
which the command part is located.
The routine executes a sampling on
the pulse train coming from the IR
detector. When a signal is detected on
pin RA2, it waits for about 60 ms and
then starts polling the pin again. This
will skip the first pulse train in order
to be sure to catch the second pulse
train. As soon as the beginning of the
second pulse train is sensed, it waits
11.11 ms and then starts sampling the
train every 1.78 ms (the duration of a
bit in the RC5 standard) for eight
times. The resulting byte is then
stored in the read_ir register.

A large portion of the firmware is

devoted to the receiver programming.
When you press a keyboard key dur-
ing the polling task, the firmware
checks which key was pressed.

As we explained earlier, when the

Scroll Lock key is pressed, the code
enters Programming mode. In this
mode, the firmware asks you to press a
keyboard key that locates a position in
the microcontroller’s permanent memo-
ry. Sending a sequence of scan codes
that will display a sentence on a text
window on the PC as if that sequence of
keys had been pressed does this. Sixteen
positions in memory, in which we can
memorize sixteen different IR remote
commands, have been allocated. If you
need more positions, maybe a microcon-
troller with a larger memory, like the
PIC16F628, could be used. Sixteen keys
on the keyboard locate these positions.
The keys are the 12 function keys (F1
through F12) and the keys “7”, “8”, “9,”
and “+” on the numeric pad.

After you press a valid key that

locates a position in memory, the
firmware asks you to press a remote key
and then a keyboard key. The remote
key is then recognized and memorized
with the corresponding scan code of
the pressed keyboard key.

The PIC16F84A has 64 bytes of per-

manent memory, which could be
mapped in a 16 × 4 matrix. Each of the
16 columns has 4 bytes, three of which
are devoted to a storing position. The
IR decoded command is stored in the
first byte of a column, whereas the
linked keyboard key scan code is

stored in the third. When a key with
an associated extended scan code is
pressed, because it consists of 2 bytes,
the fourth byte of the column is used
in order to store the extra byte.

Another case in which the fourth byte

of the column is used is when the Shift,
Ctrl, and Alt keys on the left side of the
keyboard are pressed. Note that these
keys are duplicated on the keyboard, but
they are different keys with different
linked scan codes. We made this distinc-
tion because these keys are often used in

conjunction with another key. So, if we
want to store the scan codes related to
the combination of one of these three
keys with another key, we have to choose
those located on the left side of the key-
board. In this case the code asks to press
the second key, and the corresponding
scan code is then stored in the fourth
byte of the column. Press the Escape key
and the code exits Programming mode
and starts polling again.

After the receiver has been pro-

grammed, the presence of a signal com-

background image

been entered, the receiver asks you to
press the remote control keys you
want to memorize. So, you have to
aim at the IR sensor on the receiver
and enter the remote control com-
mand. The last request is to enter the
keyboard key you want to associate
with the previous remote control key.
After this, the receiver restarts the
process of programming and asks for a
new position in memory.

When you want to exit Programming

mode, press the Escape key. The
receiver will be ready to receive the
memorized remote commands and
transmit the associate keyboard code.
So, at least for the printable charac-
ters, you can immediately test the
programming by pressing the remote
control keys and watching the result
on the text window.

This procedure permits the memo-

rization of a single keyboard key. But,
in some cases, some programs could
require the use of a combination of
more than one key, especially in con-
junction with keys like Shift, Ctrl, and
Alt. The receiver is also able to memo-
rize and transmit the combination of
two keys in which the first is one
among the Shift, Ctrl, and Alt keys.
This is done during programming by
pressing the Shift, Ctrl, or Alt keys
located on the left side of the keyboard.
The receiver then asks you to enter a
second key to be used in conjunction
with the first. If you choose the keys

14

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

ing from the IR is sensed (during the
polling task) and decoded. The result-
ing byte is then compared among the
first bytes of each column in the per-
manent memory. Every time that the
comparison is positive, the scan code
stored in the corresponding third byte
is sent to the host PC with its break
code as if we have pressed and released
that key. If the scan code memorized is
the one corresponding to left Shift,
Ctrl, and Alt keys, or is an extended
scan code, the fourth byte is taken into
account and the proper combination of
codes is sent. After the scan codes
have been sent, the firmware reenters
the polling task ready to decode and
send a new command. This means that
if you press and hold a remote control
key the corresponding scan code is
sent continuously until you release it.

RECEIVER PROGRAMMING

Programming the receiver is simple.

You must first run a text editor on the
PC and then press the Scroll Lock key
to enter Programming mode. A receiv-
er programming session is shown in
Photo 2. The receiver displays on the
text window the request to enter a
position in memory.

You have to press one of the func-

tion keys to locate the first 12 posi-
tions (F1–F12) or the four keys on the
numeric pad (“7,” “8,” “9,” “+,”) to
locate the last four positions in mem-
ory. After the position in memory has

PROJECT FILES

To download the code, go to ftp.
circuitcellar.com/pub/Circuit_
Cellar/2004/166.

SOURCES

PIC16F84A Microcontroller
Microchip Technology
(408) 792-7200
www.microchip.com

IS1U60 IR sensor
Sharp
www.sharp-world.com

Guido Torrioli is a physicist with a
strong background in electronics. He is
currently a researcher at the National
Research Council in Rome. You
mayreach Guido at torrioli@ifn.cnr.it.

Sergio Torrioli is a physicist currently
working as a firmware developer and
consultant in Rome. You may contact
him at torriol@inwind.it

located on the right side instead, they
will be memorized alone just like one
of the other keys on the keyboard.

I

Figure 5—

The receiver is directly powered from the host. The SW1 switch allows you to bypass the receiver in

case you want use the keyboard directly connected to the computer.

Photo 2—

A text editor program running on the PC

makes it easy to program the receiver.

background image
background image

which is an eight-channel, 12-bit ADC
that communicates via SPI.

Both of these 3.3-V CMOS con-

trollers can tolerate 5-V signals. This
means they can communicate reliably
with 5-V TTL and 3.3-V CMOS
devices. Unfortunately, the signal defi-
nitions for 5-V CMOS are slightly out
of range. It is best to use buffers when
communicating with 5-V CMOS,
unless those devices are friendly with
3.3-V CMOS. However, I’ve never had
trouble interfacing PIC microcon-
trollers to the JStamp and JStik.

The JStamp is built much like any

of the other Stamp processors. It has a
1

× 2

40-pin DIP format. The JStamp’s

brain is the aJ-80 microcontroller. The
JStamp runs at a maximum of 70 MHz.

The JStik, which is a JSimm format

board measuring 3

× 2.65

, has a few

advantages over the JStamp. It may be
bigger, but it supports two additional
ports: an Ethernet port and the HSIO
port. The JStik is roughly five times
faster than the JStamp when running

at the same speed, mainly
because it has an aJ-100
microcontroller. It runs at
a maximum of 100 MHz.

JTAG INTERFACE

I’m used to using serial

ports to program a con-
troller, but the Systronix
controllers use the JTAG
interface. The JStamp has
several pins that can be
used to connect to the
JTAG connector. (There is

16

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

’ll admit it. I’m used to program-

ming when I have lots of memory.
Although the first computer that I
built had 18 KB of RAM, which was
large for the day, every year computers
gain more memory. I wouldn’t even
think of buying a laptop with less
than 1 GB of RAM now—and perhaps
more by the time this article sees print.

Later, I became interested in embed-

ded systems. The rules changed. I
stepped into a time machine, and sud-
denly I had RAM that could be meas-
ured in kilobytes again, and not many
of those. Even the stamp-type con-
trollers still had extremely limited
memory. Also, most of these micro-
controllers were programmed in
assembly language, C, and BASIC. Yes,
I can handle all of these languages, but
I prefer Java and a bit more memory.

Then a small company called

Systronix came out with the JStamp.
This is an aJile aJ-80 Java processor
put into a 40-pin-wide DIP package
with 512-KB RAM and either 512 KB
or 2 MB of flash memory.
And its native machine lan-
guage is Java bytecodes! So,
I ordered a JStamp+ (the one
with 2-MB flash memory)
and started developing. This
controller is more powerful
than any of the other Stamp
processors I’ve found, and it
is reasonably priced.

Systronix then came out

with the JStik, which uses
an aJ-100 processor that
benchmarks approximately

Before you start piecing together your next robotics puzzle, consider what Jay has to say
about the power of embedded Java controllers. In this article, he introduces you to Systronix
Java controllers and the SimmStick bus they use. He concludes with information about the
code and hardware that he used to create a simple motor controller for R/C servos.

four to five times faster than the aJ-80
and has much more RAM and flash
memory. The JStik also has built-in
Ethernet, two COM ports, a high-
speed I/O (HSIO) port, and the JTAG
connector for programming.

My goal here is to introduce you to

the Systronix Java controllers, the
SimmStick bus used by them, and the
differences between Java 2 Micro Edition
(J2ME) and standard Java. Furthermore,
I’ll explain the code and hardware need-
ed to create a simple motor controller
for R/C servos. I would also like to say
up front that I use embedded con-
trollers for robotics. However, pretty
much everything in this article applies
to other embedded systems as well.

JStamp/JStik

The Systronix controllers have lots

of memory, plus everything else you’d
expect from a microcontroller, except
for A/D converters. Luckily, this is
easily fixed by using one or more ADC
chips such as Microchip’s MCP 3208,

FEATURE ARTICLE

by D. Jay Newman

Embedded Java Controllers

PLL

Reset power

control

aJile Java
processor

core

16-KB SRAM

microcode

32-KB SRAM

data memory

Multiple

JVM unit

Intergrated

memory

controller

Bridge

Interrupt

controller

3 × 16-bit

Timer/counter

Dedicated

8-bit GPIO

UART

16C550 & IrDA

SPI

UART

16C550 & IrDA

Processor bus

Peripheral bus

Figure 1—

The aJile architecture has all the bells and whistles associated with normal

microcontrollers, except an ADC unit.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

17

either totally stand-alone or by using
an alternate connector. Because the
power connectors, the JTAG port, and
the serial ports are built into the JStik,
you can do a lot with the JStik alone.
It is definitely an SBC.

The JStik is programmed just like

the JStamp. Note that it has almost
the same power requirements as the
JStamp, except that at its maximum
speed it requires 310 mA when run-
ning at 103 MHz. This low current
consumption coupled with its power
makes the JStik an excellent choice
for robotics systems.

PROGRAMMING TOOLS

AJile provides a few applications to

program and debug your JStamp/JStik.
These come with the development
versions of the hardware.

Jembuilder takes Java class files and

converts them to a form that can be
loaded into the controller. This is a type
of linker. Charade loads this file and
acts as an interactive terminal/debugger.

JSwat is a debugger. I haven’t used

it, so I can’t comment on it. Although
I admit to occasionally writing buggy
code, I’ve learned other methods of
debugging Java.

In addition, you need a Java compil-

er. Sun’s Java works fine. A text editor
to create the source files is useful,
although some people prefer an IDE.
All of the applications run in Windows.

EMBEDDED JAVA

If you’re used to running Java on a

larger machine, the

connected limited

device configuration (

CLDC) version

of Java is limited. Some things are left

such a connector on the JStamp devel-
opment station.) The JStik has a JTAG
connector onboard.

In order to program and debug the

Systronix controllers, you need either
the Systronix JTAG cable ($50) or
Xilinx Parallel Cable III. I’ve always
used the Systronix one that came with
the JStamp development station; it
connects to a computer’s parallel port.

SimmStick BUS

The SimmStick bus, which was

designed by an Estonian named Antti
Lukats, is based on the old 30-pin SIMM
modules. The bus has a decent number
of signals and is quite useful. Dontronics
is the largest distributor of the boards.

A SimmStick is designed to be an

SBC, using a microcontroller as the
main processor. Systronix refined the
pin definitions for the SimmStick and
have released this as the JSimm. The
JStamp development station uses this
bus, and the JStik is a JSimm board.
The major differences are that
Systronix defined some of the JSimm
signals as JStamp/JStik I/O pins.
Originally, I merely used the
SimmStick bus to carry power and SPI
signals, but I now use other signals.

One interesting thing: with the devel-

opment tools you can turn off the driv-
ers that you don’t need. For example, if
you don’t need to use SPI, you can turn
off the SPI driver and use all of I/O
port C as general I/O. Not only can this
shrink the final code, it allows you to
use the pins you want for anything.

aJile PROCESSORS

In most respects, the aJile 80 and

100 processors work the same way.

However, the aJ-100 has a wider data
path, making it faster.

The processors run Java bytecodes

as their native machine language.
Because Java bytecodes are a higher-
level code than most machine lan-
guages, more can be done in a single
instruction. This tends to make the
aJile processors extremely efficient.

Like most controllers, these contain

internal data memory. They also have
an external memory controller to
access the memory on the JStamp/JStik.
There are three timers, an interrupt con-
troller, two UARTs, and one SPI com-
munication unit (see Figure 1).

JStamp/JStik SPECIFICS

The first Systronix product I bought

was the JStamp+. Although it has the
same footprint as the JStamp, it has
2-MB flash memory instead of 512-KB
flash memory (see Photo 1).

The JStamp has two power-in pins:

one is for regulated 3.3 V, and the
other is for unregulated power. It also
has an on-board switching regulator.
Use only one of these pins, not both.

The JStamp has a pinout that fits in

extremely well with the SimmStick
form factor. The exact details are
available on Systronix’s web site.

Using the JStamp is easy. You can

implement the JStamp development
kit, or you can easily build a circuit
around it. Because you can put 5 V
into the unregulated power pin, the
JStamp can be easily put into most
common circuits. I’m planning on pro-
totyping a board using the JStamp and
a few other components to make a
complete system.

The JStamp can take either regulat-

ed 3.3 V or an unregulated 5 to 14 V.
At the maximum speed (74 MHz), the
typical current consumption is 57 mA
at 3.3 V, or a bit more at 5 V. If using
unregulated power, the JStamp can
supply 100 mA of 3.3-V regulated
power for your applications.

The JStik is a bit of a change from

the JStamp (see Photo 2). Although the
latter is a 40-pin-wide DIP, the former
is a SimmStick board. Not only does
it include a faster processor, but also
more memory, an Ethernet port, and
an HSIO port. It is possible to use the
JStik without a SimmStick backplane,

Photo 1—

Notice the JStamp’s small size. Nevertheless,

it has 512-KB RAM and 512-KB flash memory. This is
the size of the other Stamp processors, but it’s faster
and has more memory than the others.

Photo 2—

The JStik is a true SBC running embedded

Java. I currently use this as the brain of my robot.

background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

19

com.ajile.jem is the lowest level

package. By using the

rawJEM class,

you can deal with memory locations
and registers. The package also con-
tains the

PeriodicThread and

PianoRoll classes, which are used
later in this article.

Because the CLDC doesn’t include

the

Float, Double, and Math classes,

they are added in com.ajile.lang, along
with some

Error classes. com.ajile.

drivers.irq is the interrupt handler
framework. The com.ajile.drivers.flash
package contains the methods needed
to read and write directly to the flash
memory of the JStamp/JStik.

I find the com.ajile.drivers.gpio

package to be the most useful. It is
used to deal with low-level I/O ports
and pins via high-level objects.

The com.ajile.drivers.gptc package is

used to access the general-purpose
timer/counters and the waveform mod-
ule. The waveform module is a low-level
part of the aJile chip, which can be used
to generate arbitrary digital waveforms.

com.ajile.drivers.i2c has a driver to

communicate via I

2

C. com.ajile.drivers.

rtc.DS1305 provides support for the
internal real-time clock chip, while
com.ajile.drivers.RX5C62 provides
support for the calendar chip.

com.ajile.drivers.spi has a driver to

communicate via SPI. The com.ajile.file
system package supports the accessing
of the file systems available to the aJile
chips. (Currently, these are only flash
memory file systems.)

com.ajile.bootloader is an interface

that allows a program to be loaded
into a separate JVM. com.ajile.util
contains a class,

PropUtils, which

allows access to system properties.

com.ajile.microedition.io contains

the

MemoryEfficientConnector

class. This is an implementation of
the java.microedition.io connector
interface. com.ajile.net.util is a pack-
age containing network utility classes.
com.ajile.net.dns provides basic access
to domain name service. And, finally,
note that com.ajile.net.sntp is a pack-
age for dealing with the simple net-
work time protocol.

In order to have the advantages of

preemptive threading, aJile, which
wrote the Java libraries and tools for
these controllers, has provided the

out because they aren’t needed (e.g.,
the entire java.awt.* hierarchy is
gone). However, most of the core
libraries remain, although in a some-
what smaller form. Many of the meth-
ods and classes not needed in an
embedded environment have been
removed. For instance, the main hierar-
chy is reduced to java.io, java.lang,
java.util, and javax.microedition.io.
Each of these packages is pruned to have
only the classes needed for embedded
systems. You can download the latest
version of the CLDC standard from Sun.

The main thing you need to know is

that the JStamp and JStik do not sup-
port normal preemptive threading. For
all normal threads, you must use
Thread.yield(), Thread.sleep(), or some
sort of blocking I/O in order to switch
threads. This makes for a much more
defined real-time behavior when
threading is used.

The other main difference is that

the I/O packages are much more limit-
ed. There are no java.net.* packages.
Replacing this is the javax.microedi-
tion.io package, which deals with I/O
at a somewhat lower level than stan-
dard Java. However, the javax.comm
package works fine when dealing with
the serial ports.

Note that the CLDC is one of the

configurations of Java 2 Micro Edition.
AJile has pledged to eventually pro-
vide the other configuration, but it
isn’t available at this time.

JAVA PACKAGES

Because an aJile processor is a

microcontroller, you need access to
the low-level parts of the controller.
Just as it is necessary to use low-level
registers on standard microcontrollers,
it is necessary to do the same with the
aJile processors. Hence, aJile wrote a
number of packages to deal with the
controller at the device level.

The com.ajile.components package

contains various hardware compo-
nents, including timers, triggers, and
debounced buttons. com.ajile.events
includes events specific to the aJile
processors. The com.ajile.io package
adds

BufferedInputStream,

BufferedOutputStream, and
BufferedReader to the CLDC
java.io package.

background image

20

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

PeriodicThread class to allow
fully preemptive threading for time-
critical items. The

PeriodicThread

can be a bit tricky to use until you get

the hang of it. It uses the

PianoRoll

feature of the controller in order to
run the

PeriodicThread at inter-

vals.

Listing 1—

This code illustrates the use of the

PeriodicThread. I removed the code normally used

for stopping this thread safely because it doesn’t concern the control of servos.

class ServoThread extends PeriodicThread {

private static ServoThread servoThread = null;

private boolean running = true;

private boolean stopped = false;

//There are 200 ticks in 20 ms.

private int maxTicks = 199;

//A place to store the active servos.

private GpioServoMotor[] motors = {null, null, null, null};

private int numMotors = 0;

//Make sure that this class cannot be created by an outside class.

private ServoThread() {

}

//This is the only way to create an instance of this class.

public static ServoThread getInstance() {

if (servoThread == null) {

servoThread = new ServoThread();

//The thread is called once every 0.1 ms, with no leading

//wait, and with a high priority; the thread is then started.

servoThread.makePeriodic(0, 100000, 0, 0, Thread.MAX_PRIORITY

- 2, servoThread);

servoThread.start();

}

return servoThread;

}

//Add servos here. At this time, I’m not concerned with removing

//any servos from my list.

public void addServo(GpioServoMotor servo) {

motors[numMotors++] = servo;

}

//Just go in a continuous loop until somebody wants this to

//stop, perhaps for powering down the robot.

public void run() {

int tick = 0;

int i = 0;

while (running) {

//PeriodicThread.cycle() is similar to Thread.yield(), but it

//causes the thread to start again at the specified interval.

PeriodicThread.cycle();

if (tick == 0) {

//At the start of the cycle, turn on all pulses.

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

motors[i].getPin().setPinState(true);

}

}

else {

//Check for the end of a pulse for each motor.

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

if (motors[i].getTicksPerPulse() < tick) {

motors[i].getPin().setPinState(false);

}

}

}

tick++;

//At the end of a cycle, go back to zero.

if (tick > maxTicks) {

tick = 0;

}

}

stopped = true;

}

}

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

21

MOTOR CONTROLLER PROJECT

Now I’ll describe a simple motor

controller that uses the I/O pins of the
JStamp/JStik and controls four servo-
motors. Because my application (my
robot, Zeppo) uses servos converted
for continuous rotation, I don’t need a
lot of resolution in my motor control.

The full open-source robotics frame-

work is posted at http://enerd.ws/
robots/code/. The code for the motor
controller is taken directly from this
framework. I must warn you that the
framework is constantly evolving, so
the code on the site may be more
recent than the code associated with
this article.

An R/C servo motor (because I’m on

a first-name basis, I call it just a
“servo”) is a standard DC electric
motor with a bit of electronics added.
The electronics are designed to take
pulses generated by an R/C receiver
and convert them into a position.
Normally, the pulses control the posi-
tion of the motor to an angle of

±

90°.

However, I use servos that have been
modified for continuous rotation
(converted servos).

A standard servo will be at 0° or no

rotation with a pulse of 1.5-ms dura-
tion. Positive rotation is achieved with
a pulse duration of more than 1.5 ms.
Negative rotation is achieved with a
pulse duration of less than 1.5 ms.

D. Jay Newman (the “D” is silent)
works for the TLT group at Penn State
University writing programs to aid the
faculty in using classroom-based tech-
nology. In his spare time, Jay keeps
busy constructing robots and writing.
Jay is old enough to have built his first
computer around a 6502 with 18 KB of
RAM—back when that was a large
amount. The JStik that is the brain of
his current robot is much more power-
ful than his first homebuilt computer.
Jay lives with his wife, dog, and an
annoying parrot. You may contact him
at jay@sprucegrove.com.

PROJECT FILES

To download the code, go to ftp.
circuitcellar.com/pub/Circuit_
Cellar/2004/166.

SOURCES

aJ-80/100 Java processors
aJile Systems, Inc.
(408) 557-0829
www.ajile.com

SimmStick Bus
Dontronics
www.dontronics.com

JStamp and JStik
Systronix
(801) 534-1017
www.systronix.com

The typical servo accepts pulses
between 1 and 2 ms. I found that
some converted servos will take puls-
es between 0.5 and 2.5 ms. For best
results, the pulses should be repeated
every 20 ms (see Figure 2).

Many Circuit Cellar authors talk

about their hardware first. I’ve waited
until now because the circuit is ridicu-
lously simple (see Figure 3). I built it on
a SimmStick prototyping board from
Dontronics. It is a sea-of-holes board.

Because servos expect male headers

in groups of three, I used three eight-
pin male headers. Power goes along
one row, ground the next, and the sig-
nals go on the third. I’m only using four
signals at this time, even though I have
eight headers on the board (see Photo 3).

CODE

Listing 1 is the most important sec-

tion of the code, the rest of which you
may download from the Circuit Cellar
ftp site is in the GpioServoMotor.java
file. The code works on the principle
of R/C servo pulses. In order to set the
timing, I divided time into ticks, or
0.1-ms intervals.

The

PianoRoll is a basic part of the

processor’s waveform module. It
starts a basic repetitive timer. The
PeriodicThread uses this time signal.

I chose to use a

PeriodicThread

rather than a timer because, frankly, it
was easier. Because I am controlling
modified servos and electronic speed
controllers, I don’t need the fine con-
trol that timers or direct control of the
waveform module would give me. I
know that I’ll do this at some point,
just not today.

I

Photo 3—

My latest prototype was built with point-to-point

soldering. It also includes an eight-channel ADC that is
controlled by SPI, but that’s a subject for another time.

Figure 3—

This is about as simple as possible for a

schematic. I just connected all the pins of the first head-
er to ground, servo power to the pins of the next head-
er, and the four I/O pins to the third header.

Figure 2—

This is roughly what the pulses should look

like. My program divides time into 0.10-ms intervals
called “ticks.”

background image

easy for engineers to integrate in prod-
ucts. In its early days, the cost of inte-
grating it into a product was extremely
high—typically greater than $150,000—
and that was only for the Bluetooth
portion of a product development. Few
companies have volumes high enough
to amortize such a development cost,
especially not industrial products.

The maturation phase is when the

technology slowly migrates to a few
initial applications and practical field-
tests. General problems are discovered
and the specification is updated and
corrected (in Bluetooth’s case, for inter-
operability problems). The use and
spread of the technology slowly increas-
es in this phase. Companies try hard to
find applications that can be justified
in pure economical terms. Eventually,
the technology becomes widespread.

The decay phase is characterized by

slow decay. This occurs when newer
technology offers advantages over the
old technology.

And now the good news: Bluetooth

definitively is not dead. It had been in
the hangover phase for a while, but
now it is in the maturation phase.
According to the Bluetooth special
interest group (www.bluetooth.com),
1 million Bluetooth products were
shipped each week in 2003. The market
is expected to explode this year. Most
of the shipments are high-volume con-
sumer products, but the most inter-
esting part is that the industrial use of
Bluetooth is booming too.

Remember, Bluetooth was original-

ly developed for connecting mobile

22

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

T

hings are looking bright for

Bluetooth. Or shall I say things are
looking blue? As a devoted electronics
hobbyist who gets happy by just look-
ing at a flashing LED, I stand before
my greatest challenge: convincing my
wife that Bluetooth is essential for
everyday life (more on this later).

In the first part of this series, I’ll

show you how simple it is to integrate
Bluetooth in a design. First, I’ll pres-
ent you with a few new products that
will make your life easier, and then
I’ll take a closer look at their program-
ming interfaces. Additionally, I’ll cover
a couple of problems that have prevent-
ed the spread of Bluetooth technology
beyond high-volume consumer prod-
ucts (e.g., most industrial products are
shipped in fairly small quantities).

I assume that you have a basic under-

standing of Bluetooth. If you don’t,
refer to the excellent material found on
the web sites listed in the Resources sec-
tion at the end of this article.

Note that I will not focus on the

radio portion or how the frequency-
hopping scheme works. Instead, I’ll
concentrate on how easy it has become
to integrate Bluetooth in a product.

TECHNOLOGY HYPE

Success seemed immediate when

the Bluetooth concept was first pre-
sented in 1998; it attracted an amaz-
ing amount of attention. But, because
expectations weren’t fulfilled quickly
enough, interest declined soon there-
after. As a result, it wasn’t so long ago
that some people declared Bluetooth

Simple Bluetooth Integration (Part 1)

It may be easier than you think to integrate Bluetooth technology in your designs. In the
first part of this series, Anders introduces two Bluetooth modules—the ROK104001 and
cB-OEMSPA13i—and sets the stage for an interesting project that he describes in Part 2.

dead. In all fairness, many of the expec-
tations were clearly exaggerated and not
based on reality. Many people tried to
apply the technology in areas and situa-
tions that it was not designed for.

Surprised? Well, based on the histo-

ry of new technology, this could have
been predicted from the beginning.

Most new technologies evolve

through four phases: the euphoria phase,
the hangover phase, the maturation
phase, and the decay phase (see Figure 1).
The euphoria phase is marked by a lot
of initial interest in the new technology
and all its possibilities. There are no
limitations, only opportunities.

During the hangover phase, prob-

lems are discovered and frustration
over undelivered promises sets in. The
main problems for Bluetooth were the
qualification process and the low
abstraction level that the first compo-
nents offered. (Refer to the “Reach the
Market” sidebar for more information.)
Bluetooth was supposed to be easy for
end users to apply, but it was not as

FEATURE ARTICLE

by Anders Rosvall

1

2

3

4

Phases

Interest /Adoption of technology

Figure 1—

Most technology evolves through four phas-

es: euphoria, hangover, maturation, and decay.

Implementing Bluetooth Modules

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

23

one of the internally implemented pro-
files. Besides the profile interface, there
is typically some form of interface for
master/slave handling, controlling
power save modes, and service discov-
ery functions.

The basic goal has been to drastical-

ly lower the complexity of integrating
Bluetooth functionality in a product
and to minimize the administrative
qualification work. The benefits
include cutting the time to market and
minimizing the initial learning curve.

BLUETOOTH MODULES

Two interesting Bluetooth products

were recently released: the
ROK104001 and the cB-OEMSPA13i.
Refer to the Resources section of this
article for the names of web sites that

phones and computers with different
peripherals. Industrial applications
were not even considered as a possibili-
ty. Today, industrial applications are
extremely hot, and it was actually the
industry that first embraced the tech-
nology and started using it. Currently,
there are numerous companies that
focus solely on providing industrial
Bluetooth applications. Many of the
original use cases, or “profiles,” can be
used in industrial applications. Refer to
the “Bluetooth Profiles” sidebar for
more information.

INTEGRATION TREND

One of the larger initial problems

with trying to widen the adoption of
Bluetooth technology was the low
level of abstraction that the first com-

ponents offered. The HCI interface,
which is a low-level protocol, was typ-
ically used. It was simply too much
work and too expensive to get a system
up and running. An upper-layer proto-
col stack had cost between $60,000
and $120,000 in 2000 and 2001. To fur-
ther complicate matters, the qualifica-
tion process and associated administra-
tion were not really in place in 2000.

Today, things are different. The inte-

gration trend is obvious. Several prod-
ucts have been developed that are basi-
cally self-contained. All of the neces-
sary upper-layer protocols are included
and most—and sometimes all—func-
tionality has been tested and is pre-
qualified. Figure 2 illustrates this trend.

The interface to these integrated

modules is, in principle, an interface to

REACH THE MARKET

The world of Bluetooth is full if acronyms, especially

when it comes to the qualification process. Bluetooth
qualification is the certification process required for any
marketed product using Bluetooth wireless technology.
There are some pros and cons associated with the
process. For instance, the process ensures that all prod-
ucts on the market conform to the standard and can
interoperate (remember that interoperability is a prereq-
uisite for success), but that’s at the cost of increased
bureaucracy and prices—not to mention the prohibition
of small-volume products.

All Bluetooth special interest group (SIG) members

have a royalty-free license to use Bluetooth wireless
technology in their products. All Bluetooth products
must be listed on the Bluetooth qualified products list
(QPL). Membership is available at no charge; however,
listing a product in QPL costs approximately $7500 for
free membership companies. Paid memberships have a
discount on this obligatory fee.

There are specially authorized Bluetooth qualification

bodies (BQBs) that have the authority and competence
to evaluate, qualify, and list Bluetooth products on the
QPL. Currently, there are 35 such persons in the world.

Bluetooth products are divided into three subgroups

when listed in the QPL. Bluetooth end products are
products designed for end users. A Bluetooth subsystem,
which is a special kind of Bluetooth end product, is used
only in conjunction with another Bluetooth subsystem.
A typical example is a Bluetooth USB dongle, which
contains the lower layers of the Bluetooth protocol (up
to HCI) and is usable only with a PC containing the
upper protocol layers within the operating system. In
this example, the Bluetooth USB dongle and the PC
with operating system are two distinct Bluetooth sub-

systems. Note that connectBlue’s cB-OEMSPA family is
an example of a Bluetooth end product.

The second group—components—are pretested

Bluetooth components. By building a Bluetooth end
product, or Bluetooth subsystem, on such components,
the design and test work is easier because conforming to
testing requirements can be substantially reduced. This
is the case when using the Infineon ROK 104001
Bluetooth component.

Finally, development tools are products designed sole-

ly for use as test equipment and development tools as
well as for demonstration. Such products do not need to
conform to the Bluetooth system specifications.

The Bluetooth SIG also arranges something called

Bluetooth UnPlugFest, where practical testing sessions
are arranged to ensure practical interoperability between
products from different manufacturers.

It is important to realize that passing the Bluetooth

qualification process is not enough for putting a product
on the market. The major markets in the world also have
governed type-approval requirements (see Figure s1).

Bluetooth product

Qualification program

Regulatory type approval

RF Tests

Product and
profile tests

R&TTE
ETS/EN

FCC

Part 15

Other

national

standards

E.U.

market

U.S.

market

Other

markets

Figure s1—

This diagram should clarify the qualification program and regula-

tory-type approvals.

background image

24

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

publish complete lists of qualified
Bluetooth products. Currently, there are
approximately 1300 qualified products

and the number is steadily increasing.

Infineon’s ROK104001 is a complete

solution that consists of a baseband

with an integrated microprocessor,
radio, flash memory, and firmware
(see Photo 1). Two different firmware

BLUETOOTH PROFILES

What’s a Bluetooth profile? Well, it’s basically the result

of genuine engineering work. The profile concept is used
to minimize (perhaps not completely eliminate) the risk of
interoperability problems between different manufacturers’
Bluetooth products. A number of user models describe dif-
ferent user scenarios and roles where Bluetooth performs
the radio transmission. Different profiles have been devel-
oped based in these use cases. A profile describes how to
implement a specific group of use cases. It also defines
options in each protocol (in the Bluetooth protocol stack)
that are mandatory for the profile, as well as parameter
ranges for each included protocol. Observe that the new
Bluetooth standard, v1.2, includes a number of new profiles.

The profile protocols can be viewed as protocols

placed on top of the basic Bluetooth protocol stack. A
profile can be described as a vertical slice through the
protocol stack. Many profiles build on each other. For
instance, the LAN access profile requires the serial port
profile, as does the dial-up networking profile.

Every Bluetooth unit must support the generic access pro-

file, or GAP. It defines many of the basic Bluetooth func-
tions (e.g., device discovery, security, and name discovery).

There are many profiles that have absolutely no use

in industrial applications. Instead, they are targeted for
specific consumer applications like transferring pictures
from a digital camera, transferring data to a printer, and
sending/receiving faxes. I won’t cover these, but three
profiles are worth mentioning.

SPP

Serial port profile (SPP) emulates a serial cable connec-

tion between two peer devices. Simply put, it transparently
transfers a byte stream from point A to B and vice versa.

SPP has defined the roles DevA and DevB. The former is

the initiator of a connection, and the latter is the recipient
of a connection request. For a device to enable incoming
connections, the DevB role must be enabled in that specif-
ic device. It is possible to have several parallel connections
in a device (i.e., several instances of DevA and DevB).
Figure s1a illustrates the different SPP roles.

DNP

The dial-up networking profile (DNP) allows a device

to access a public telephone network through a gateway.
Actual network access can be through an ordinary
modem or a GSM/GPRS modem.

DNP has defined the roles gateway (GW) and data termi-

nal (DT). Obviously, the GW is the device that provides
access to the network, and the DT is the device that uses
the dial-up services of GW to access the network. The net-
work can be an ISP for Internet access, or it can be a specif-

ic computer with a modem. Figure s1b illustrates the
roles.

To enable incoming connection requests to the DNP,

the GW role must be enabled in that specific device. It is
possible to enable several instances of the GW role in
order to allow several parallel connections through the
GW. A device must take the DT role in order to connect
to other devices supporting the GW role. After it’s con-
nected, the network access is set up using AT com-
mands, just like an ordinary modem.

LAP

The LAN access profile (LAP) is similar to DNP, except

that it is a LAN instead of the public phone network.
LAP has defined the roles LAN access point (LAP) and
data terminal (DT). The former acts like a gateway and
provides the actual LAN access, and the DT device uses
the services provided (see Figure s1c). To enable incoming
connection requests to the LAN Access Profile, the LAP
role must be enabled in that specific device. It is possible
to enable several instances of the LAP role in order to
allow several parallel connections through the LAP. A
device must take the DT role in order to connect to other
devices supporting the LAP role.

The similarities to DNP are striking, but when the

LAP is used, the data transfer takes place over PPP and
TCP/IP, which encapsulate the actual user data. The LAP
provides only a transparent serial channel, much like
SPP. Only PPP is dictated by the profile. TCP/IP is
almost always used on top of PPP.

Note that the LAN doesn’t have to be an actual LAN

(like Ethernet). It also can be a simulated LAN, which is
application-specific.

DevA
Client

DevB

Server

Connect

Data transfer

DT

Client

dial-up networking

profile

GW

Server

dial-up networking

profile

(typically a modem)

Connect

Data transfer

AT commands

AT command

responses

Public network

DT

Client

LAN access

profile

LAP

Server

LAN access

profile

Connect

Data transfer

LAN

(PPP, TCP/IP,

user data)

a)

b)

c)

Figure s1a—

As you can see, there are different SPP roles

. b—

Take a look at the

different dial-up networking profile roles.

c—

The LAP is is similar to DNP. Take a

look at the roles.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

25

options are available: the standard HCI
interface and embedded communication
platform (ECP) firmware with embedded
stack and profiles. (I’ll cover the latter.)
The module, which is prequalified for
Bluetooth specification v1.1 as a compo-
nent, is FCC and ETSI-type approved. It
has 10-m communication range. The
multichip module has land grid array
(LGA) solder joints and measures
15.5 mm × 10.5 mm × 2.0 mm.

The connectBlue cB-OEMSPA family

is also a complete solution that consists
of a baseband with an integrated micro-
processor, radio, flash memory, and
firmware. The firmware includes an
embedded Bluetooth stack with profiles
and associated APIs. The module is
qualified for Bluetooth specification
v1.1 as a product, and it is
FCC and ETSI-type
approved.

The connectBlue module

is available in four versions:
internal antenna (10-m com-
munication range [13i]),
external antenna (10-m
communication range [13x]),
internal antenna (100-m
communication range [33i]),
and external antenna (100-m
communication range [33x]).
The components measure
36 mm × 23 mm × 8 mm
(10-m version) and 42 mm ×
40 mm × 8 mm (100-m ver-
sion). You can connect to
the module via a 2 × 10 pin
2-mm pitch pin header or
via a 1 × 20 pin 1-mm pitch
board-to-board connector
on the rear side (see
Photo 2).

The Infineon and connectBlue mod-

ules have a common origin, and they
are based on the same hardware and
almost the same firmware. Neverthe-
less, they’re built and Bluetooth-quali-
fied in different ways.

The connectBlue module has the

lowest threshold to start interfacing the
module and communicating with it.
No further Bluetooth qualification has
to be made because it is a qualified end
product. The downside is a higher per-
unit cost than the Infineon module.

The Infineon module may be a better

choice for high-volume applications
because of its lower per-unit cost.
Because it is qualified as a Bluetooth
component, the final product must be
qualified as an end product. Expect
prices between $11,000 and $12,000
including the QPL listing cost. Of
course, this qualification cost can be
amortized over a large number of units.

Interested in alternative products? Try

the Simply Blue family (LMX9820)
from National Semiconductor
(www.national.com) and Blue Giga’s
WRAP THOR (www.bluegiga.com).

MODULE INTERFACE

The Infineon and connectBlue mod-

ules have a common origin and share
the same communication interface—
the embedded communication inter-

face, or ECI, which was originally
developed by connectBlue. More infor-
mation is posted on the Infineon web
site (www.infineon.com). Note that
connectBlue’s module has additional
features not found in Infineon’s mod-
ule, but the fundamental parts of the
ECI protocol are identical.

Let’s start with some basic nomen-

clature. Remember that creating
Bluetooth products and applications
is about supporting one or several
Bluetooth profiles. ECI provides
Bluetooth products with an interface
toward a Bluetooth product that sup-
ports a number of profiles.

The ECI protocol defines the ECI

controller and host. The former is the

Bluetooth module that
contains the Bluetooth
protocol stack, including
one or many profiles. It is
the component or product
that you buy and inte-
grate in your product.
The latter is the applica-
tion that utilizes the serv-
ices in the ECI controller.
Basically, it is the pro-
gram that you write in
some application that
makes use of Bluetooth
as a communication
channel.

ACCESSING PROFILES

Figure 3 illustrates the

relation between an ECI
controller and host. The
ECI protocol structure
was designed for several
reasons. Multiple applica-

Application

#2

Upper layer interface

G

A
P

D
N
P

L

A
P

S
D
A
P

RFCOMM SDP

L2CAP

HCI Interface

Host

Host

protocol

stack

HCI Interface

Link manager

RF Radio

Traditional

Bluetooth

module

HCI Protocol

Integration trend

Upper layer interface

G

A
P

D
N
P

L

A
P

S
D
A
P

RFCOMM SDP

L2CAP

Integrated

Bluetooth

module

RF Radio

Link manager

High-level protocol

Application

#1

Application

#2

Module interface driver

Host

Traditional approach

Integrated solution

Application

#1

S
P
P

S
P
P

Figure 2—

Upper layer protocols, which are called “host protocol stacks,” have been inte-

grated in the module. The result is an easy-to-use, high-level module interface.

Photo 1—

The ROK104001 consists of a baseband

with an integrated microprocessor, radio, flash memory,
and firmware. Two different firmware options are
available.

Photo 2—

Like the ROK104001, the cB-OEMSPA13i

contains a baseband with an integrated microprocessor,
radio, flash memory, and firmware. The firmware includes
an embedded Bluetooth stack with profiles and associat-
ed APIs. The module is available in four versions.

background image

26

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

can communicate with several devices
simultaneously (i.e., multipoint func-
tionality). It can also communicate with

other devices using several parallel chan-
nels to each device (i.e., multiple chan-
nels). And finally, an ECI host can uti-
lize several different profiles simultane-
ously (i.e., the protocol is multiprofile).

The ECI interface can be divided

into two distinct parts, as illustrated
in Figure 3. One part handles all the
configuration and control functions.
This is basically an interface toward the
GAP, the service discovery, and security
mechanisms. The other part involves
data transferal, where connections are
requested and accepted and the datas-
treams are controlled. This is basically
an interface toward SPP, and possibly
LAP, because it builds upon SPP.

PROTOCOL STRUCTURE

The ECI protocol structure is based

on packets. There are eight types of
packets: data, request, confirm, result,
command, event, indication, and
response. The packets are transferred
between the ECI host and the ECI

tions in an ECI host can simultane-
ously utilize the functionality provid-
ed by an ECI controller. An ECI host

controller using a transport layer.
Currently, the most common transport
layer is a simple UART, which is
assumed to be error-free. No form of
explicit error checksums exists. A sim-
ple 1-byte packet indicator encapsulates
each packet (see Table 1).

Figure 4 illustrates the packet flow

between and ECI host and ECI con-
troller. Serial data packets can be sent
in both directions. A request packet
asks the ECI controller to perform
some form of operation. The ECI con-
troller responds with a confirm packet.
Note that the request type of packages

ECI

Host

Datastream

and control

Configuration

and control

Transport

protocol

(i.e., UART)

ECI Interface

Serial data

transfer profiles

Base profiles

and functionally

LAN Access

profile

Serial

port profile

Generic

access profile

Lower-level protocols

Service

discovery,

master-slave,

COD

ECI

Controller

…………

Application #1

Application #N

ECI driver

....

Figure 3—

The interface between an ECI host and ECI

controller uses a simple asynchronous UART as the
transport protocol. The ECI communication can be divid-
ed into datastream and control (of the datastream) and
configuration and control (e.g., of power-down modes).

ECI Packet type

ECI Packet indicator

ECI Request packet

0x05

ECI Confirm packet

0x06

ECI Result packet

0x07

ECI Command packet

0x08

ECI Event packet

0x09

ECI Indication packet

0x0A

ECI Response packet

0x0B

ECI Serial data packet

0x0C

Table 1—

A single byte precedes every ECI packet to

signal which packet type follows.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

27

can behave differently depending on
which request is issued. Sometimes
result or event packages are returned.
Command packets are sent from the
ECI host to the ECI controller, but
will not cause the ECI controller to
send a confirmation back to the ECI
host. Indication packets are sent from
the ECI controller to the ECI host.
The ECI host responds to the indica-
tion using a response packet. Event
packets are a way for the ECI con-
troller to signal significant events to
the ECI host. No response is sent back
to the ECI controller.

Let’s take a quick peek at four

interesting protocol fields in ECI
that support the multiple applica-
tions, multiple channels, and multi-
ple profiles functionality advertised
previously. (Note that the fields
illustrate how the ECI protocol can
support multiple host applications,
multiple data channels, and multiple
concurrent services, or profiles. The
first two fields make life easier in sit-
uations when the ECI host has multi-
ple applications.)

The first field is the application ID.

All request packets have this field,
which is supplied by the ECI host.

The resulting confirm packet and pos-
sible result packet will contain the
same application ID. Sometimes it’s

ECI

Host

ECI

Controller

ECI serial data packet

ECI serial data packet

ECI request packet

ECI confirm packet

ECI command packet

ECI indication packet

ECI response packet

ECI
Host

ECI event packet

ECI

Host

ECI

Controller

ECI request packet

ECI confirm* packet

ECI request packet

ECI confirm packet

Serial

data

Requests

Commands

Indications

Events

ECI

Controller

ECI

Controller

ECI
Host

ECI

Controller

ECI

Host

ECI

Host

ECI

Controller

ECI result packet

ECI result packet

ECI result packet

ECI result packet

*Will contain information
about the number of result
packages.

ECI

Host

ECI

Controller

Zero or more

ECI event packet

Figure 4—

Five different communication scenarios exist with eight different packet types. If the ECI controller generates

result packets, they are always preceded by a confirm packet that indicates the number of result packets to follow.

background image

28

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

included in event and indication pack-
ets. The application ID eases applica-
tion programming because confirm,
result, indication, and event packets
can be easily routed to the correct
application (if several exist simultane-
ous in the ECI host).

The second protocol field is the tag

field. All request packets have the tag
field, which is supplied by the ECI
host. The resulting confirm packet
and possible result packet contain the
same tag. At times it is included in

event and indication packets. Note
that the tag can be used as a running
ticket number to ease application pro-
gramming (pairing confirm, result,
event, and indication packets with the
originating request).

Service handle, which is the third

protocol field, uniquely identifies an
enabled service in the ECI controller
(basically a role that has been enabled).
Several services can be active simulta-
neously.

Lastly, the connection handle field

identifies a connection to a remote
device because several can be active at
once. The ECI host receives the connec-
tion handle from the ECI controller dur-
ing the connection set-up phase.

BUFFER HANDLING

Each data packet sent contains a

connection handle to identify the spe-
cific connection. Each connection has
its own flow control that regulates the
packet flow between the ECI controller
and the ECI host. The flow control is
symmetrical (i.e., the flow is controlled
in each direction).

The control mechanism is built based

on how many memory resource-con-
straint embedded systems are designed.
Each recipient has a finite (and known)
number of fixed-size receive buffers. This
number is advertised to the opposite side,
which must always keep count of the
number of available receive buffers at the
other side. The number of available
buffers in the opposite side decreases, of
course, by one every time a data packet
is sent. After the recipient has consumed
a previously received packet, it informs
the sender of this event. This way the
sender always knows if a data packet
can be sent or not.

Note that the recipient doesn’t have

to inform the sender of every consumed
data packet. It can adjust this informa-
tion flow according to other data flow.
It can inform every second time that
two buffers have been consumed.

AT COMMAND VERSION

The ECI protocol is extremely effec-

tive and relatively simple to program.
However, there are situations when it
is difficult to implement.

The Bluetooth modules from

connectBlue have an additional commu-
nication protocol implemented that is
based on AT commands. A product may
already have handling for AT commands
(e.g., to a modem). The ECI controller
switches between Command mode (AT
commands) and Data mode, which is
just a transparent data channel. Buffer
handling is no longer an issue because
hardware flow control is typically used
(RTS/CTS). Refer to the full specifica-
tion listed in the Resources section of
this article for more information on
this topic.

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

31

READY FOR A PROJECT?

The qualification process definitively

sets limits for commercial products,
but there is nothing stoping you from
experimenting with Bluetooth projects
at home. Again, refer to the “Reach the
Market” sidebar for more information.

Many Bluetooth modules have

LGA/BGA-like interfaces and obvious-
ly operate in the gigahertz range, which
poses difficulties for experimenting with
these modules. Luckily, a module
adapter can ease the mounting prob-
lem for LGA/BGA-like modules. Check
out the test socket from Emulation
Technologies
(www.emulation.com/catalog/off-the-
shelf_solutions/sockets/production/blue
tooth/). Alternatively, you can use
modules like connectBlue’s that have
easier physical interfaces.

Now I’m back to where I started the

article. I get happy just looking at a
flashing LED, so I can’t deny that
Bluetooth is a pretty cool technique that
now exists right before my eyes. And
wouldn’t it be cool to automate some-
thing at home with Bluetooth’s help?
Currently, my biggest challenge
(because Bluetooth is no longer a chal-
lenge) is convincing my wife that we
need to automate something. How
about an automatic mailbox checker
that signals after the postman has deliv-
ered something? After all, I can save a
couple of meters every day if I don’t
have to check the mailbox manually.

Seriously speaking, there are numer-

ous household applications that can
benefit from Bluetooth technology. I’ll
say more about this in next month’s
article, where I explain the profiles and
ECI protocol in detail. I’ll also describe
a small project that incorporates on
the prequalified Bluetooth modules
from Infineon and connectBlue.

I

RESOURCES

Bluetooth, www.bluetooth.com.

connectBlue, “Serial Port Adapter: 2nd
Generation AT Commands,”
cBProduct-0211-04[5], 2003.

Bluetooth info, www.mobileinfo.com/

SOURCES

cB-OEMSPA13i
connectBlue
www.connectblue.com

ROK104001 Bluetooth module
Infineon Technologies
www.infineon.com

Anders Rosvall is CTO of Embedded
Artists AB, a company based in
Sweden that provides industrial com-
munication solutions. He has a strong
industrial background and has held
various positions within the ABB

bluetooth/index.htm, www.palo
wireless.com/infotooth/.

ECI Protocol, www.infineon.com.

Group. Anders is also a lecturer at sev-
eral of Sweden’s leading universities.
You may contact him at Anders.
Rosvall@EmbeddedArtists.com.

Author’s Note: I thank Eurodis for
providing Infineon Bluetooth modules
to experiment with. (If you’re inter-
ested, Parallax has a new Bluetooth
product—EmbeddedBlue.)

background image

ded applications as well. Imagine a
portable bar code scanner in a ware-
house that needs to access a database
server on the Internet/Intranet. Some
applications, however, are better served
in Ad Hoc mode. Here two or more
devices will communicate with each
other on a preset channel and an SSID.

As you now know, for Ad Hoc mode,

you need to set the RF channel that you
want to use. For Wi-Fi, you can use chan-
nels two through 13 in the United States.
Other countries allow different channels
to be used. Although Wi-Fi can tolerate
multiple devices on a single channel, you
would like to pick a channel with mini-
mal noise and interference. The channel
does not need to be free, because Wi-Fi
devices can cooperatively use the same
channel without interface with each
other and other devices. It does, however,
affect the throughput and bandwidth that
the application can expect to see.

Wi-Fi devices adjust their communica-

tion speed based on the signal-to-noise
ratio they encounter. If a particular
channel is busy with other devices, the
signal-to-noise ratio will be low, and a
lower communication rate will be used.

You need to assign an SSID in addi-

tion to the RF channel. This is a string
that uniquely identifies each device on a

32

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

H

ave you ever wondered how to

make your embedded application
wireless? Well, if you already have an
Ethernet-based solution, it’s easy.
Simply add an Ethernet-to-Wi-Fi bridge.

In this article, I’ll show you how to

Wi-Fi-enable an Ethernet-based embed-
ded controller using a wireless bridge.
First, let’s cover some background.

WI-FI BACKGROUNDER

Wi-Fi, which is a popular name for

802.11b, is one of the wireless schemes
available in the 802.11 suite. 802.11b
describes the media access and link layer
control for a 2.4-GHz implementation
that can communicate at a top bit rate of
11 Mbps. Other standards describe a faster
implementation (54 Mbps) in the 2.4-GHz
band (802.11g) and a 54-Mbps implemen-
tation in the 5.6-GHz band (802.110). The
adoption of 802.11 has been fast because
it’s easy to use and its performance is
comparable to wired LANs. Things pretty
much look like a wireless LAN.

Wi-Fi is the most common and cost-

effective implementation currently avail-
able. A variety of Wi-Fi hardware exists,
including wireless access points (WAPs)
and various Wi-Fi access devices with

Wi-Fi-Enabled Embedded Control

Looking for an easy wireless solution for your embedded applications? In this article, Ingo
shows you how to Wi-Fi-enable embedded applications with a wireless bridge.

PCI, PCMCIA, CompactFlash, and USB
interfaces. Other Wi-Fi devices include
’Net-based cameras as well as Wi-Fi-
based Ethernet bridges, which act like a
transparent Ethernet-to-Wi-Fi interface.

Wireless networks can operate in one

of two modes. They operate either in a
managed access mode (Infrastructure
mode) or an unmanaged mode (Ad Hoc
mode). The 802.11 standard describes
the details of how devices access each
other in both of these modes.

In Ad Hoc mode, each device sets a

channel number and the service set
identifier (SSID) to communicate with.
If they match, the network interface
devices can talk with each other, much
like they would on a wired LAN, like
Ethernet. This works fine for a few
devices, which are statically configured
to talk to each other.

Infrastructure mode requires an

access point to manage devices that
want to communicate with each other.
Typically, it will dynamically allocate
bandwidth and allow devices to join a
zone, which is managed by the access
point. They can also manage roaming
nodes that may move between zones.
This is the most common way that
notebook computers and PDAs access
the Internet (e.g., at the cafe where I’m
writing this article).

When I bring my notebook to the cafe,

my network card listens for broadcasts
from access points and then announces
itself to an access point. Because the
access is free and unrestricted, after it
has joined the access point, the access
point assigns an Internet address to my
notebook using DHCP and tells my
notebook what gateway and domain
name server (DNS) to use. I can then use
the Internet at will.

You can use this scheme for embed-

FEATURE ARTICLE

by Ingo Cyliax

WGA11B

10BaseT

BL2000

Heater

Temperature

Fan

Temp 26

Set 25

<<>>

Pocket PC

Figure 1—

I implemented a closed-loop temperature

application with a ’Net-based GUI. This block diagram
shows my Wi-Fi-based controller system.

DAC0

ADC0

RAW

OUT1

OUT2

BL2000

10 k

NTC

Heater

Fan

Figure 2—

I Interfaced the thermistor, fan, and heater

to the controller.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

33

tion, a full-size heater that’s appropriate
for your application could be interfaced
using a solid state or mechanical relay.

Use the following equations to com-

pute the minimum resistance to
implement a resistive heater:

You can use a larger resistance in order
to match the power rating of the avail-
able resistor. For example, if you want
to use a 1-W resistor, the minimum
resistance would be the following:

You should choose a resistor that has a
sufficient power rating for this. For
example, if you want to implement a
2.4-W heater, use a resistor that is rated
for at least 2.4 W. You can use a smaller
power rating for the resistor if the object
you’re heating can sink the extra power.

SOFTWARE

The software consists of three logi-

cal components, and it’s divided into
two functions and one library call.
The library call implements the poll
loop that the TCP/IP and web server
needs to process incoming and outgo-
ing packets and the various timers it
needs to function.

The other two functions—

update_

temp() and update_outputs()—do
what their names imply. The
update_temp() sets the desired out-

R =

=

= 144

V

P

2

144

1

R

and

=

= 60

P = 12 0.2 = 2.4 W

12

0 2

.

×

specific channel. There are several spe-
cial SSIDs, such as the “default” and
“none,” which are used by devices to
find access points. Think of the SSID as
sort of a network identifier. Devices
with SSIDs that do not match can’t lis-
ten to each other on the channel.

Use a Wi-Fi-to-Ethernet bridge to

enable your application to work with
Wi-Fi. The bridge translates standard
Ethernet packets into 802.11b pack-
ets, which can be received by another
802.11b device, bridge, or access point.

THE APPLICATION

The highest cost in many embedded

applications is the user interface. It’s
common that adding an LCD and key-
pad can double the cost of a simple
embedded controller. Also, the user
interface may be needed only occasion-
ally, particularly when installing or
configuring the device, which may not
be necessary for day-to-day operations.

One solution for this is to use a net-

work-based interface and some sort of
embedded ’Net-based configuration tool.
With a network interface, it’s possible to
configure the device using either a local
PC via a crossover cable or a LAN.

Another way to do this is to use a

Pocket PC or PDA type of device. These
little machines are ultra portable and
have a small LCD and pen-based inter-
face. Many also have a ’Net browser and
TCP/IP protocol stack. What they don’t
typically have is an Ethernet interface.
They often have only a modem interface
or a socket for a flash memory-based
memory card. Some have a CompactFlash
socket, and manufacturers have come
up with a Wi-Fi card for these sockets in
order to enable wireless browsing.

I’m quite the coffee hound, and

where I live there are several coffee
houses that have free Wi-Fi access. It’s
a lot of fun to bring my Pocket PC with
Wi-Fi card and browse the ’Net while
sipping a cup of coffee. But I digress.

Besides browsing the ’Net wireless-

ly, I have implemented a Wi-Fi-based

embedded controller with a user
interface that can be accessed using
one of the Pocket PC/PDAs with a
Wi-Fi interface using a standard
web browser. No extra software is
required for the PDA/Pocket PC.

The controller could be any

embedded device with an Ethernet
port and an embedded web server. In
this case, I used a Z-World BL2000
controller, which has a 10-Mbps
Ethernet port and embedded
TCP/IP stack/web server. This con-
troller is a SBC with plenty of I/O,
including high-current open-collec-
tor outputs as well as A/D and D/A
channels. I like using this con-
troller for prototyping embedded
applications because of its generic I/O
interfaces. After I have identified
which I/Os I need, it can be implement-
ed in a more application-specific board.

For this application, I wanted to

implement a closed-loop temperature
application with ’Net-based GUI. A
block diagram of the application can be
seen in Figure 1. The temperature sensor
is implemented with a simple thermis-
tor that is interfaced to one of the A/D
channels in a voltage divider configura-
tion driven by one of the D/A channels.

A thermistor-based temperature

sensor was interfaced to ADC0 and
DAC0 in a voltage divider circuit
using a 10-k

resistor (see Figure 2).

At 25°C, the input to ADC0 reads 50%
of the voltage applied with DAC0.

To control the temperature, there

are two outputs. One becomes active
when the temperature falls below a
set point. This is the “too cold” output
and would be used to drive a heater.
The other output becomes active
when the temperature is too hot and
would be used to drive a fan or cooler.

Because the SBC has relatively high

current outputs (up to 200 mA), I can
use them to drive a small 12-VDC
brushless fan and a resistor as a heater.
The resistor would be close to the ther-
mocouple for testing. In a real applica-

Photo 1—

The setup includes a Pocket PC, wireless bridge,

and SBC. There are more wires here than I would like to
see, but they’re manageable.

Listing 1—

Now you too can read and convert thermistor values.

anaOutVolts(0, V1);

//Set output voltage for DAC0

V2 = anaInVolts(0);

//Read voltage from ADC0

R2 = V2*R1/(V1-V2);

//Compute thermistor resistance

T = 1 / (A + ((1/Bth)*log(R2)));

//Compute temperature in Kelvins

background image

34

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

played and used in other parts of the pro-
gram. Average 10 readings before updat-
ing the temperature variable used by the
’Net interface and the output routine.

The output routine simply com-

pares the current averaged tempera-
ture with the set point and sets the

put voltage of the DAC0 using the
BL2000 library routine

dacout(),

which, in this case, is 1 V. The
adcin() library call is used to read the
input voltage, which is the result of a
voltage divider network using the ther-
mistor and a fixed (known) resistor.

Use the following equation to com-

pute the resistance of the thermistor:

R1

is the other resistor in the net-

work. V

DAC

is the applied voltage, and

V

ADC

is the read voltage .

After you know the resistance, you

can use the constants provided for the
thermistor to compute the temperature:

where R

TH

is the thermistor resistance,

alpha

is computed from the datasheet,

and beta is given in the datasheet.

Listing 1 shows the code fragment

necessary to read and convert the read-
ing to a temperature, which can be dis-

T

alpha

beta

=

+

ln R

TH

1

1

×

(

)







R =

V

R1

V

V

DAC

DAC

ADC

×

outputs OUT1 and OUT2 correspond-
ingly. If the integer representation of
the temperature and the set point
match, then none of the outputs are
on. This implements a dead band so
that the controller isn’t constantly
seeking between heating and cooling.

The Internet-based interface is based

on a simple HTML-based web page. A
table construct organizes the display
into three rows and two columns:

Temp: 25

Set: 25
<< >>

The current temperature and set point

are substituted when the page is served
using server site includes (SSI). The
left/right arrows are links that point to
two CGIs, setlower.cgi and sethigher.cgi,
which are mapped as function callbacks

setlower()/sethigher() in the appli-
cation software. The functions simply
increment and decrement the set point
value by one.

The HTML page also contains a meta

refresh tag, which instructs the browser
to reload the same page every 2 s. This

Photo 2—

Check out the web interface on the Pocket

PC. Clicking on the

<<

and

>>

symbols decreases

and increases the set point by 1°C. The display auto-
matically updates every 10 s.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

35

is a simple mechanism for implement-
ing dynamically updating web pages
without resorting to the use of facili-
ties like JavaScript or Java applets:

<META HTTP-EQUIV="refresh" con-
tents="2;URL=." >

The application will run on any web

browser that is pointed to this device.
It acts like a mini web server that
specifically implements this applica-
tion. The SBC has a 10BaseT Ethernet
interface that can be connected to a
hub with a direct cable, a PC via a
crossover cable, or a Wi-Fi bridge.

You will need to modify your net-

work configuration in the tcpconfig.c
module to set up your network inter-
face. In particular, you will need to edit
it to match your IP address, which may
have been assigned to you. If you plan to
use this application on a private net-
work or an ad hoc Wi-Fi network, you
can use any address, as long as the PC or
PDA that wants to access your device
has an address on the same network.

SETTING WI-FI

You first need to configure the bridge

you’re using. The easiest way to set this
up is to use an access point and config-
ure your bridge and PDA/PC to use
Infrastructure mode. I used a Linksys
WGA11B bridge in this application. It is
particularly handy, because you can con-
figure it using a button on the bridge to
select a channel, Infrastructure mode,
or one of three preset configurations.
Another bridge may require you to use a
PC and supplied software to configure
your bridge before using it. Follow the
manufacturer’s directions on configuring
the bridge to use Infrastructure mode if
you want to use it with an access point.

You can also use Ad Hoc mode net-

working. You will need to pick a
channel number (11) and SSID (default)
for your network. It doesn’t matter
what it is, as long as it matches all of
the devices that you plan to use in the
network and there is no conflict with
other Wi-Fi networks in the area.

Next, you will need to configure your

Wi-Fi-enabled display device (PDA/
Notebook). You can do this by configur-
ing your Wi-Fi card (again following the
manufacturer’s instructions) to set

either Infrastructure mode or Ad Hoc
mode and the same channel (11), and
by assigning the same SSID (default) to
it. You also have to set the network
interface to use static IP addressing and
assign an IP address on the same net-
work as the Wi-Fi-enabled thermostat.

And that’s all there is to it. Now, you

can start up Explorer on your Pocket PC,
or whatever web browser runs on your
PDA, and type in the URL to access
the web server in the embedded device.
Photo 1 is a picture of the setup that I
used for this. It shows the SBC, bridge,
and Pocket PC. Photo 2 is a screen
shot of the application running on it.

GOING FURTHER

Using a wireless bridge is a convenient

way to Wi-Fi-enable any embedded appli-
cation that is already Ethernet-enabled.
There are several bridges available. I
found the Linksys WGA11B most useful
because of its simple configuration.

I can think of many really cool appli-

cations. How about a robotics project?
Just add a wireless bridge and off you go.

Security can be a concern in wireless

applications. There are really two issues
here. One is data privacy (i.e., making
sure no one can snoop on your data).
This can be addressed with encryption.
Wi-Fi has an encryption mechanism that
is implemented by all Wi-Fi-compliant
devices. This is called wire equivalent
privacy (WEP). Although it’s useful for
obfuscating the naive eavesdropper
from listening in, it’s not considered to
be strong encryption. You may also
want to use an application-layer
encryption for a stronger encryption
model that gives a little more privacy.

’Net-based applications can use

secure HTTP, which is HTTP protocol
over a secure socket layer (SSL) con-
nection. How this is done is beyond
this article and independent of Wi-Fi
and our use of bridges.

Another issue is protecting your

access points from access. It is con-
venient to use open access points from
the point of configuration, but access
points can be configured to restrict
access. The simplest method is to turn
off broadcasting the SSID, in which case
all nodes that want to access an access
point will have to know a private pre-
determined SSID shared by each

Ingo Cyliax received a B.S.C.E.E. from
Purdue University. He currently works
as an application engineer at Z-World.
Ingo’s interests include photography,
astronomy, aeronautics, embedded
systems, wireless networking, and
hardware design. You may reach him
at cyliax@ezcomm.com.

PROJECT FILES

To download the code, go to ftp.
circuitcellar.com/pub/Circuit_
Cellar/2004/166.

SOURCES

Axim Pocket PC
Dell, Inc.
www.dell.com

WAP11 Instant access point, WCF12
Wi-Fi CompactFlash card, WGA11B
Wireless Ethernet game adapter
Linksys
(949) 261-1288
www.linksys.com

BL2000 Wildcat controller
Z-World, Inc.
www.zworld.com

device on a particular network.

Again, this is pretty weak because

it’s relatively easy to put most wire-
less cards in Monitor mode, where
they will listen to all of the packets.
Besides, with 16 bits, it’s also easy to
cycle through all of the possible SSIDs
to find one that’s active.

Many access points can be config-

ured to allow only devices with a
known MAC (the hardware address of
a node) address to communicate with
it. This is a little harder to spoof, par-
ticularly because you have to change
the hardware address of your network
card in addition to knowing one that
is already in the access table. Finally,
most TCP/IP stacks can detect if there
are multiple devices with the same
MAC address as a diagnostic feature.

There are several other schemes and

methods, some of which are vendor-spe-
cific and involve authenticating access
with an authentication service. Refer
to the access point and bridge vendors’
documentation to see what’s available
and how to enable the features.

I

background image

When combined with a PC application,
the Bitscope could be used as a DSO,
logic probe, logic analyzer, or other real-
time instrument. It appeared to be just
the sort of thing I was looking for.

The original Bitscope interfaced with

the PC via a serial port. Before long, I

36

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

developed an Ethernet bootloader to

implement a rapid development environ-
ment for an Ethernet-enabled, flash
memory-based microcontroller. A couple
of years ago, when I was looking to buy
a low-cost digital storage oscilloscope
(DSO) to support my electronics hobby, I

After reading Norman Jackson’s 1998 Circuit Cellar article about his BitScope, which is a
mixed-signal capture engine, Andrew started working on an Ethernet interface for it—the
LAN interface adapter (LIA). Here he describes the LIA and explains how he came up with
an Ethernet bootloader solution, which basically includes the code working in the PIC, the
controlling host, and an Ethernet connection.

found Norman Jackson’s 1998 article,
“Bitscope: A Mixed-Signal Capture
Engine,” which sparked my interest
(Circuit Cellar 97). The Bitscope is pro-
grammed via a serial port to capture ana-
log and digital data based on user-config-
urable parameters and trigger conditions.

FEATURE ARTICLE

by Andrew Smallridge

Figure 1—

The initial implementation of the bootloader was in the LIA for the Bitscope. Key components include the PIC microcontroller, the Realtek Ethernet controller, and

the RJ-45 isolating transformer/filter/connector.

Ethernet Bootloader

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

37

the term “bootloader” refers to
the code executing in the LIA’s
PIC18F252 microprocessor.
“Programmer” refers to the
programming application run-
ning on the controlling host.

I had several design goals for

the Ethernet bootloader. First,
I wanted plug-and-play opera-
tion so I could program a boot-
loader that was not previously
configured with an IP address. I
also wanted to be able to pro-
gram a remote LIA. I aimed at
using only a minimal amount
of code space, and I didn’t want
to use any of the PIC’s
resources other than the flash
memory, to hold the boot code.

Furthermore, I sought trans-

parency to the user’s code. I also
wanted to be able to report status to
the programming application used for
implementing a reliable service.
Another important goal was to work
with standard Intel hex files. Finally, I
aimed for the ability to upload and
download program and EEPROM data.

At first glance, the requirements of

plug-and-play operation and the ability
to be able to program a LIA remotely
appear to be mutually exclusive. In fact,
the bootloader supports both modes of
operation concurrently. Plug-and-play
operation over Ethernet is achieved via
the use of multicast IP operation
enabling the dynamic discovery and
operation of a LIA on a local network
segment. No “gleaming” is required to
talk to the bootloader. Remote support
is achieved via unicast IP operation,

realized that the serial port was a
bottleneck for the DSO screen
refresh rate. I subsequently spoke
to Norman, the original developer,
to find out if he offered a high-per-
formance version of the product. I
mused how an Ethernet version of
the Bitscope would make for an
extremely versatile test instru-
ment. A networked Bitscope would
break the low-speed shackle
between the controlling host and
Bitscope. I also noted that it would
open the Bitscope to an entirely
new range of applications such as
the ability to support multiple
Bitscopes controlled via one or
more centrally located or geograph-
ically dispersed controlling hosts.

“Why don’t you build one?”

Norman responded.

This led to the development of the

LAN interface adapter, or LIA, which
is pronounced “Leeah.”

The LIA sits between the existing

serial interface of the Bitscope and the
IP world; crudely put, it is a protocol
translator. Applications communicate to
the Bitscope via the LIA and the host’s
IP stack. The LIA and the Bitscope are
both based on PIC microprocessors with
embedded USART. When a LIA is con-
nected to a Bitscope, the LIA automati-
cally reconfigures the Bitscope’s USART
to talk at 1.25 Mbps.

The circuit diagram for the LIA is

shown in Figure 1. The key components
are the Realtek RTL8019AS Ethernet
controller, the Microchip PIC18F252
microcontroller, the YCL FTC111-01
RJ45 with embedded filter, and the RS-
232 interface. Note the use of an inverter
on the RS-232 TX output and a discrete
RX input stage instead of the more con-
ventional MAX232 type interface. This
was done to enable the interface to oper-
ate at 1.25 Mbps and still be compatible
with the electrical interfaces found on
PCs, notebooks, and other devices.

The RX output ranges from 0 to 5 V,

whereas RS-232 requires, as a mini-
mum, an output swing from –3 to 3 V.
Nevertheless, I have used this interface
successfully on a wide number of
devices. If you plan to interface to lega-
cy RS-232 devices limited to 115 Kbps
or less, then you may well want to use
a MAX232 or similar solution. If you

intend to drive the serial interface at
high speed (1.25 Mbps or faster), then be
warned that the cable length must be
extremely short. In fact, at 1.25 Mbps
no cable can be used between the LIA
and the Bitscope because the capaci-
tance of the cable significantly affects
performance. Still, that’s not bad
when you consider that the Bitscope
was originally designed for 56 Kbps.

The Bitscope powers the LIA via

spare pins on the RS-232 DB-25 connec-
tor. This turned out to be a key issue in
working out how to support a remote
code upgrade for beta units in the field.

The initial LIA was built on Vero-

board with an off-the-shelf NE2000-
compatible NIC card. As development
progressed, unused components were
stripped off the NIC card until finally
only the Realtek Ethernet controller
chip and some discrete components
remained. Photo 1 shows the original
prototype and the finished LIA.

A bootloader was required to facili-

tate rapid application development and
support remote upgrades for develop-
ment units. The challenge was imple-
menting a bootloader to facilitate
remote code upgrade without having to
supply additional hardware to power the
LIA. The solution was to implement a
bootloader over the Ethernet interface.

The bootloader solution includes

the loader code resident in the target
PIC, the controlling host (the host
running the programming application),
and an Ethernet connection. Note that

Photo 1—

There is a contrast between the finished LIA and the original

breadboarded prototype and the stripped-down network interface card
(NIC). As the prototype was developed, unnecessary components were
stripped from the NIC card.

Program

memory

LDR Reset vector

Bootloader program

0×0008

0×7000

0×7FFF

User memor

y

space

Figure 2—

As you study the memory map for the boot-

loader in the PIC microcontroller, keep in mind that the
bootloader does not use the PIC’s internal data EEPROM.

background image

38

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

es control to the application code via
the remapped reset vector.

The bootloader and the code do not

operate concurrently. This explains
why the loader does not require any of
the PIC’s resources other than the
consumed program memory.

The bootloader accepts commands

from the Programmer using multicast
and unicast IP packets. The user data-
gram protocol (UDP) is used between
the bootloader and the programmer.
The IP datagram service provides a good
fit for exchanging Intel hex file records
(lines in the hex file); however, UDP is
an unreliable service, which means that
the application (both the bootloader and
the programmer) must implement its

enabling a LIA on the other side of the
world to be remotely programmed.
Flexible operating modes, embedded diag-
nostics, and reliable service challenge the
third requirement—the need to minimize
the memory footprint of the loader to
maximize the available user code space.

BOOTLOADER MEMORY MAP

The bootloader code resides in the

upper 4 KB of the program memory
space. Because this program memory
is flash memory-based, user-config-
urable optional parameters are stored
in this space.

The EEPROM memory space internal

to the PIC is preserved unchanged by the
bootloader. The bootloader transparently
uses the PIC’s reset vector (i.e., the lower
8 bytes of program memory). The reset
vector is transparently mapped into an
8-byte block within the bootloader’s
code space. The code must implement a
GOTO instruction (a long jump) in the
first eight bytes. The bootloader code
includes a

RESET instruction immediate-

ly following the remapped vector block.
If the program fails to implement a

GOTO

instruction in the first 8 bytes, then the
RESET instruction is executed. Figure 2
shows the loader’s memory map.

BASIC OPERATION

The bootloader code in the PIC and

programmer application uses flags to
control the bootloading process. Two of
these flags determine the boot-up behav-
ior of the PIC: The pending reset vector
indicates that the reset vector has not
yet been received. The invalid user code
space flag indicates that an Intel end-of-
file hex record has not yet been received.

The LIA’s bootloader code is executed

automatically as a result of a power-on
reset, a reset command, or a jump to
absolute address 0000h. The bootloader
is now in Bootloader Discovery mode. If
either of the two critical flags is set, the
loader will automatically enter Loader
Command mode. This generally indi-
cates that the user code space is empty
or has been previously invalidated.

If neither critical flag is set, the

loader waits 5 s and looks for a com-
mand from the programmer via the
Ethernet interface to put the LIA into
Loader Command mode. If no com-
mand is received, the bootloader pass-

own error detection, reporting, and,
where applicable, retransmission.

The bootloader implements an incre-

mental programming mechanism. This
means that it will program only the
bytes specifically contained in the
record to be programmed. Code changes
down to a single byte granularity are
supported, and the remaining program
memory space contents are preserved.

PROGRAMMING APPLICATION

Photo 2 is a screen shot of the LIA

loader utility. The LIA’s bootloader
has been captured and the hex file
HEAD.ASM has been programmed into
the LIA via the bootloader. The status
information is displayed in the right-hand

Reset

Reset

Ethernet

controller

First time

execution?

Initialize Ethernet

controller MAC

address

Set up Ethernet

controller multicast

address mask

Extract LIA_ID

from MAC

address

Stop timer

User code

space valid

Timer

expired?

Package

received?

Service

Ethernet

controller

Jump to user’s

reset vector

Start 5-s

timer

Generate and

save MAC

address

Service

Ethernet

controller

ARP

request?

ICMP

Echo?

UDP

packet

for LIA?

Save source UDP port,

IP address MAC address

Valid

bootloader

packet?

Read

command

?

Erase

Commad

?

Invalidate

Commad

?

Continue

Program

command

?

ARP

Reply

ICMP
Reply

LIAID =0

?

Valid

LIA_ID

?

Send
status

Dump flash

memory

Erase flash

memory

Stop timer

invalidate

flash memory

Program

flash memory

Initialize

PIC

Figure 3—

This is the bootloader flow diagram for the PIC microcontroller.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

39

memo pane. Note the LIA_ID
in the Configure LIA drop-
down menu box. This selects
the target bootloader (which
LIA is to be programmed). The
LIA response memo pane is
usually empty; it is used to
display error messages.

There are several steps for

downloading code to a LIA
via the bootloader and pro-
grammer application. First,
power cycle or reset the target
device to be programmed. This puts
the bootloader in Bootloader Discovery
mode and enables the bootloader to
respond to discovery packets from the
programming application.

Second, click the Locate LIA button

to initiate device discovery to find all
devices currently in Bootloader
Discovery mode. The first device to be
discovered will have its LIA_ID displayed
in the Configure LIA drop-down control.
If multiple devices are discovered, then
the target device can be selected in the
Configure LIA drop-down box.

Within 5 s of the first step, click

the Program Mode button. This sends
the Loader Command mode command
to the LIA, identified in the Configure
LIA control, to capture the bootloader.
After it’s captured, the target device
remains in Loader Command mode,
where the flash memory and EEP-
ROM memory of the target device can
be read, erased, and programmed.

Next, select the desired read, erase, or

program operation. Note that to program
the bootloader from a hex file, you must
first select the source file using the File
button. The identified file and path will
be displayed in the file window. The hex
file is opened when the Program button
is clicked and closed at the completion
of the programming cycle. The next time
the Program button is clicked, the source
file is again opened. This is important
because it means that the bootloader is
always being programmed with the
current contents of the source file.

The edit control Record to Program

area can be used for sending individual
records to the bootloader. The Overwrite
LIA button is used to invalidate the
user’s program memory space without
erasing the user’s program. A LIA in this
mode will stay in Bootloader Discovery

mode after being reset without passing
control to the user’s program.

After the LIA has been successfully

programmed or read, click the Reset LIA
button. This will issue a loader reset
command to the bootloader. Following
this, the LIA executes the bootloader
code and waits for 5 s to receive the
Loader Command mode command. If this
command is not received and the critical
flags are clear, then the loader passes
control to the application program.

The programmer application was

written in Delphi for the Windows
environment. The application should
compile unchanged with Kylix for
Linux, but I have not tested this. The
application uses the freeware Indy con-
trol TIdUDPClient for reading and writ-
ing packets to the network. The Indy
software is licensed under the Indy
Modified BSD license, which is includ-
ed in the files for this project. The Indy
package is installed as standard in
Delphi Enterprise addition 6 and 7. For
Personal Delphi, you must download
the package at www.nevrona.com/indy.

The programmer and bootloader are

implemented in a client/server
arrangement. The programmer (client)
issues commands to the bootloader
(server), which executes the com-

mands and returns status
information for each com-
mand. The programmer appli-
cation is multithreaded,
implementing a read thread
for processing packets
received from the bootloader.
The main thread handles
packets sent to the
Bootloader. The programmer
application uses a timer con-
trol as part of the error-detec-
tion and processing mecha-

nism for the

READ, ERASE, and PRO-

GRAM commands.

Listing 1 is a code extract for the

Program Button and the error-handler
ProgramSupervisor responsible for
error detection and correction of the
programming process. When Program is
clicked,

BProgramClick is executed.

This procedure opens the source file,
initializes the timer, sends the first line
of the hex file to the bootloader, and
saves a copy of the record as the current
record. In normal operation, a status
packet is returned by the bootloader and
processed by the receive thread. If the
status of the received packet indicates a
successful program record status, the
timer restarts and the next record of
the file is sent to the bootloader. This
process is repeated until the entire file
has been sent and the final record is
successfully acknowledged.

In the event that no status is

returned for the current record, the
timer will expire, passing control to
the

ProgramSupervisor procedure.

The consecutive error counter vari-
able (CEC) will be incremented. If this
CEC value is below the maximum
consecutive error threshold, the timer
restarts and the previously saved cur-
rent record retransmits.

Photo 2—

This is the programmer application for uploading and downloading

code to the target device.

Command

Value

Payload

Comment

CP_Status

0

0

Show status

CP_SetIP

1

4

Set IP address

CP_Invalidate

2

0

Invalidate user program area

CP_LDR_Mode

3

0

Put LIA into loader state

CP_New_Code

4

11–43

New code to store

CP_Dump

5

0

Dump user memory and EEPROM

CP_Erase

6

0

Erase program memory and EEPROM

CP_Erase_PGM

7

0

Erase program memory only

CP_Erase_EE

8

0

Erase EEPROM only

CP_Reset

9

0

Reboot the LIA

Table 1—

The command code and associated data is transferred from the programmer to the bootloader.

background image
background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

43

LIA BOOTLOADER

Figure 3 is a simplified rep-

resentation of the bootloader
code operation. The target
PIC18F252 processor does not
support a read/modify/write
operation in flash program
memory space. So, in order to
write a new value to the flash
program memory, you must
first erase the location to be pro-
grammed. An added complexity
is that the processor erases
memory in 64-byte blocks.

In order for the bootloader

to support incremental pro-
gramming, several steps are
performed. First, the record to be pro-
grammed is examined to determine
the base address of the destination
64-byte memory block in the program
memory space. Then, the 64-byte
block is copied to RAM (shadow RAM
in the code listing). Next is a calcula-
tion of the offset of the record to the
first location to be modified in the
shadow RAM. The data from the
record is inserted into the shadow
RAM. Finally, the 64-byte page in
flash program memory is erased and
reprogrammed with the contents of
the shadow RAM.

The subroutine responsible for exe-

cuting the

New_Code (program flash

memory) command and implementing
the described programming algorithm
is posted on the Circuit Cellar ftp site.
For a PIC18F252 processor, a data
record (type 0) only makes sense in
the context of the last type-4 record
processed. The type-4 record is used to
determine if subsequent data records
are destined for the program memory,
the EEPROM, the configuration bits,
or the processor ID bits. The
Program_Flash subroutine supports
writing to the program memory and
flash memory.

PACKET FORMATS

Packets sent from the programmer

to the bootloader can be sent to the
unicast address of the bootloader or
the multicast address. IP packets can
be unicast for point-to-point commu-
nications, broadcast to all devices on a
subnet, or multicast to a targeted sub-
set of devices. Devices interested in

receiving multicast packets will con-
figure their network interfaces to
accept specific multicast MAC layer
addresses. These MAC layer addresses
map to corresponding IP multicast
addresses. The bootloader configures
the Realtek Ethernet controller chip
with a multicast filter mask in order
to accept multicast packets destined
for the multicast address 230.10.10.11.

Unicast packets sent by the applica-

tion programmer will have the time-
to-live (TTL) field set to 255. Network
routers along the path between the
source and destination decrement this
value by one. If, as a result of decre-
menting the TTL field, the outcome is
zero, then instead of forwarding the
packet out of the des-
tination interface, the
router will discard the
packet. This is the
mechanism IP net-
works use to prevent
packets looping forever
in the network. For
unicast packets, this
means the packet can
traverse up to
254 routers.

For multicast pack-

ets, the programmer
application sets the
TTL field to one. The
first time a router tries
to forward the packet,
the TTL field is decre-
mented to zero and
the router discards the
packet. This mecha-
nism limits bootloader

multicast packets to the local
IP network segment. Multicast
therefore provides a mecha-
nism to support plug-and-play
operation. You do not need to
assign an IP address to the
bootloader to be able to com-
municate with it over an IP
network. The TTL is used to
limit the traffic to the local
segment. The multicast mecha-
nism allows multiple bootload-
ers on the same network seg-
ment. This is accomplished

using the LIA_ID, which is
derived form the MAC address
of the bootloader.

The network header portion is a

conventional UDP packet structure
(see Figure 4). The destination IP
address is either the unicast IP address
of the LIA or the multicast IP address
230.10.10.11. The destination UDP
port number for the bootloader is
0x4000. The programmer command is
carried in the data portion of the UDP
packet. This comprises a 7-byte com-
mand header and an optional variable
length payload.

LIA_TAG is a fixed pattern used to

protect against the remote possibility
that another device on the network is
using the same IP address and port
number. If the key field of the incom-
ing packet does not match, the record

Ethernet

IP

UDP

Command header

Data

CRC

Header (7 bytes)

Command payload (0 to 43 bytes)

Network headers

Programmer command

Field

Length Description

LIA_TAG

2

bytes 5AA5

LIA_ID

2 bytes

Unique 2-byte LIA identifier

Sequence

2

bytes Incremental

sequence

number

Command

1

byte

Command payload

0 to 43 bytes

Figure 4—

Packets sent from the programmer to the bootloader are struc-

tured like this. The programmer command packet comprises a fixed 7-byte
command header and optional command payload.

Ethernet

IP

UDP

Status header

Data

CRC

Header (19 bytes)

Dump record (0 to 43 bytes)

Network headers

Bootloader status

Field

Length Description

LIA_TAG

2

bytes 5AA5

Target_ID

2

bytes 0×0000

Sequence

2

bytes Command

sequence

number

Command

1

byte

LIA

command

byte

Product_ID

1

byte

LIA

product

identifier

0×01

HW_version

1

byte

Major/minor

4

bits

each

SW_Version

1

byte

Major/minor

4

bits

each

LIA_ID

2 bytes

Unique 2-byte LIA identifier

IP_addr

4

bytes User-configurable

IP

address

LIA_State

2

bytes LIA

status

word

Data_Seq

1

byte

Next

data

sequence

number

to

be

used

for

data

traffic

INHX32 record

0..43 bytes

Variable command payload

Figure 5—

Note how the structure differs for status packets sent from the boot-

loader to the programmer. The bootloader status packet comprises a fixed
19-byte status header and optional payload field. The payload field is used by
the read command to upload the user code and EEPROM contents from the
target device to the programmer.

background image

44

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

is discarded. The bootloader also
checks to ensure that all command
structures are valid.

The LIA_ID field is the last two

byes of the bootloader’s MAC address.
The bootloader generates a pseudo-
unique MAC address the first time it
is powered. This MAC address is
stored in the bootloader’s program
memory space. Subsequent powering
up of the LIA will use the MAC
address stored in the bootloader’s
program memory space. This LIA ID
mechanism enables multiple LIAs to
share a common network segment
and enables each LIA to be uniquely
programmed by the programmer
application.

All bootloaders will respond to a

status request if the target LIA_ID
field is set to 0000. When the boot-
loader responds, it puts its LIA_ID
into the corresponding field. This is
the mechanism used by the program-
mer application to discover all boot-
loaders on the network segment.
Other than the status command, the
bootloader will ignore all commands
that do not specifically match the
bootloader’s LIA_ID.

The sequence field is incremented

by the programmer application. It is
used by the bootloader to detect lost
command packets. Sequence numbers
and acknowledgement timers are
used to detect and recover from lost
packets.

Regarding the payload, note that

two commands use the optional pay-
load field. The Set_IP address com-
mand contains a 4-byte IP address to
be assigned to the bootloader. This IP
address is stored in the bootloader
program memory space, and it perma-
nently overwrites the default IP
address. The New_Code command
contains an Intel INHX32 record (i.e.,
a line from the hex file produced by
an assembler that will be a type-0,
type-1, or type-4 record).

Figure 4 shows the programmer

payload structure for packets sent
from the programmer to the boot-
loader. Each command is comprised of
a 7-byte command header.

Table 1 gives a breakdown of the

10 commands supported by the boot-
loader and the length of the optional

Listing 1—

This code snippet is for the program button (

BProgramClick) and the background program

supervisor code (

ProgramSupervisor) for the programmer application. Note the use of the timer by

BProgramClick. ProgramSupervisor is invoked by the timer expiring indicating a failure condition.

procedure TForm1.BProgramClick(Sender: TObject);

var

error_flag : boolean;

begin

Timer1.Enabled := false;

Timer1.OnTimer := ProgramSupervisor;

Timer1.Interval := ProgramTimerInterval;

error_flag := false; // Indicate no errors condition

// Open the file containing the records to be processed

{$I-}

AssignFile(InFile, SourceFile);

Reset(InFile);

{$I+}

if IOResult = 0 then

begin

SourceOpen := true;

if not eof(InFile) then

begin

MemoWrite(Form1.Memo1, ‘Programming from ‘ + SourceFile);

Readln(InFile,Last_Data_Sent);

SendRecord(Last_Data_Sent);

ShowAddress(Title + ‘ - Programming ‘, Last_Data_Sent);

Timer1.Enabled := true;

Send_Error_Count := 0;

DisableButtons;

end else

begin

MemoWrite(Form1.Memo1, ‘No records found in file ‘ + SourceFile);

Error_Flag := true;

end;

end

else

MemoWrite(Form1.Memo1, ‘File ‘ + SourceFile + ‘ not found’);

if error_flag then

if SourceOpen then

begin

{$I-}

CloseFile(InFile);

{$I+}

SourceOpen := false;

end;

Form1.Caption := Title;

end;

procedure TForm1.ProgramSupervisor(Sender: TObject);

var

i, flags : integer;

begin

// Control passes here on a missing acknowledgement

// from the device being programmed

// increment the consecutive error count

// if cec < max CEC, then resend last record

// Or else display error message and abort programming

Form1.Timer1.Enabled := false;

inc(Send_Error_Count);

if Send_Error_Count < Max_CEC then

begin

SendRecord(Last_Data_Sent);

ShowAddress(Title + ‘ - Programming ‘, Last_Data_Sent);

Timer1.Interval := ProgramTimerInterval;

Timer1.Enabled := true;

end else

begin

Single_Record := false;

MemoWrite(Form1.Memo1, ‘FAILED - Comms Timeout Error Programming LIA’);

Form1.Caption := Title;

i := FindLIA(Form1.CLIAselect.Text);

(Continued)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

45

payload field. Most commands are
self-explanatory. Additional informa-
tion can be found in the source code
for the programmer application, which
you may download from the Circuit
Cellar

ftp site.

The

Invalidate command sets a flag

in the bootloader code, which pre-
vents the bootloader from passing con-
trol to the program. Effectively, your
program space has been invalidated
but not erased. It is possible to reverse
the invalidated status by sending a
single type-1 (end-of-file) record to
the bootloader with the New_Code
command.

The

LDR_Mode command (Loader

mode) captures the bootloader to pre-
vent it from passing control to the
application program at the end of the
initial 5-s period from reset. In this
mode, the programmer application
controls the bootloader. The capture
does not invalidate the code. If the
LIA is reset in this mode, then after
5 s, control will once again pass over
to your program, provided your code
space is valid.

The

Dump command uploads the con-

tents of your program memory and
EEPROM memory space to the pro-
grammer application. The bootloader
uses the same INHX32 Intel hex
record format.

All commands result in a status

packet being sent to the programmer
application, indicating the success or
failure of the command (see Figure 5).
Lack of status information is inter-
preted by the programmer as a lost or
missing command acknowledgement.
This results in the application pro-

gram reissuing the previous command.
In the worst-case scenario, this means
that the bootloader may program the
same record (line of the hex file).

The status record reflects the com-

mand status header information to the
programmer application as well as
some additional fields. The data
sequence number is used for lost pack-
et detection for the dump command.
The application program currently
uses this information to report error
status and terminate the dump com-
mand, but it does not automatically
issue another dump command.

INTEL HEX RECORD STRUCTURE

The following is the structure of

Intel hex file records:

:AABBBBCCDDDD..EE

where the colon indicates the start of
the current record. “AA” is the num-
ber of data bytes in the record. “BBBB”
is the target address of the first byte in
this record, and “CC” is the record
type. “00” is the data record. “01” is
the end-of-file record. “04” is the lin-
ear address record. “DD” is the data,
and “EE” is the checksum calculated
across the record (excluding the “:”
character).

BOOTLOADER LIMITATIONS

The LIA registers are not preserved

by a reset, and there is no support for
WDT. Furthermore, your program
must execute a

GOTO instruction with-

in the first 8 bytes. Finally, keep in
mind that the bootloader ignores con-
figuration and ID records.

PERFECT TOOL

The Ethernet bootloader is a great tool

for developing those projects that start
with the question, Wouldn’t it be
great to reach this over the network?
Developing Ethernet-enabled microcon-
troller projects is much easier today than
when I started with the LIA. Microchip
offers a free IP stack for use with
Microchip PICs; it also has a good proof-
of-concept kit with the PICDEM.NET
board. Having said this, note that the
LIA bootloader does not use any of the
Microchip stack because the bootloader
is optimized for space, while the stack is
optimized for performance. For this rea-
son, I did not open any of the bootloader
APIs for use by target applications.

I

Author’s Note: I would like to thank
Microchip’s Tom Bianchi for the loan
of a PICDEM.NET board to port the
bootloader to that platform. I would
also like to thank Norm Jackson and
Bruce Tulloch at Bitscope Designs for
their support in developing the LIA.

SOURCES

PIC18F252 Microcontroller, PIC-
DEM.NET Ethernet development
module
Microchip Technology, Inc.
(480) 786-7200
www.microchip.com

RTL8019AS Ethernet controller
Realtek Semiconductor Corp.
886 3 578 0211
www.realtek.com.tw

PROJECT FILES

To download the code and addition-
al files, go to ftp.circuitcellar.com
/pub/Circuit_Cellar/2004/166.

RESOURCE

BitScope information,
www.bitscope.com.

Andrew Smallridge is an accredited
Cisco Certified Internetworking
Expert (CCIE) and a keen electronics
enthusiast. He earned a degree in
Electronic Engineering and a post-
graduate diploma in Computer
Science. You may contact him at
asmallri@hotmail.com.

Listing 1—

Continued.

if i <> -1 then

flags := (ord(LIA_List[i].LIA_Status[0]) shl 8) +

ord(LIA_List[i].LIA_Status[1])

else

flags := 0;

EnableButtons(flags);

if SourceOpen then

begin

{$I-}

CloseFile(InFile);

{$I+}

SourceOpen := false;

end;

end;

end;

background image

46

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

t’s time to work some more RF

magic. So get that pointy wizard cap
out of the closet and fetch that magic
wand hidden in your dial caliper case.
You may want to pull out your Western-
style Stetson, too, if you have one.

You already know that the wizard

gear is necessary to work with RF. But
what do a wizard’s cap, a sorcerer’s
wand, and a Stetson cowboy hat have
in common? Well, I associate RF with
the word “radio.” And, being a 1950s
baby, a big old Stetson hat is synony-
mous with the word “cowboy.” When
cowboys get together and bring along
horses and cows to poke in a competi-
tive environment, it’s called a “rodeo.”
I don’t have any cows and bulls to
poke, and I didn’t ride into town on a
horse, but for the past month or so I’ve
been ridin’ the range and have man-
aged to corral a few embedded data
radios along the way. Now that you
cowpokes are present, we can saddle up
on our microcontrollers, put on our
cowboy and wizard hats, and rope, ride,
and wrangle some radios in the Circuit
Cellar

embedded radio rodeo.

I pulled together a collection of

embedded radio equipment from vari-
ous manufacturers to give you an idea
of what’s available these days, and I’ll
point out the features contained with-
in the new embedded RF technology.
A collective representation of all of
the radio rodeo participants is shown
in Photo 1. Now let’s take a look at
all of the embedded radio goodies I
rounded up in the Florida room (in
alphabetical order).

rate range having its own encoding
scheme. Hamming and Manchester
encoding are present when the XTR-
903-A4 is used at 9600 bps. Manchester
encoding alone is used when the
XTR-903-A4 data rate is increased to
19,200 bps and a scrambling technique
is used for 38,400-bps radio links. If
your application doesn’t need the
speed, the 9600 bps radio link is opti-
mal because it provides a higher level
of data protection and longer range (up
to 200 m in open air with an omni-
directional antenna).

The data rates are selectable using

the XTR-903-A4’s SP1 and SP2 control
pins. The pins can be tied permanently
or controlled via a host microcontroller.

While I’m on the subject of configu-

ration pins, the XTR-903-A4 can be
put into Power Down mode by the

Radio Roundup

APPLIED PCs

by Fred Eady

ABACOM XTR-903-A4

The Abacom Technologies XTR-903-

A4’s claim to fame is based on its
size, ease of use, and programmability.
Measuring in at 23 mm × 33 mm, it is
almost as thin (5.5 mm top to bottom,
excluding the mounting pins) as the PCB
it’s built on. The digital heart of the XTR-
903-A4 is an Atmel ATmega8(L) micro-
controller, which allows the XTR-903-A4
to communicate with an embedded host
using simple TTL RS-232 signaling. All
of the communication protocol stuff you
would normally have to write is already
coded into the XTR-903-A4’s microcon-
troller. My XTR-903-A4 is a 433-MHz
model, but you can get XTR-903-A4s
that operate at 868 and 900 MHz.

The XTR-903-A4 operates using fre-

quency modulation (GFSK) at 9600,
19,200, or 38,400 bps, with each data

Fred spent an entire month accumulating and categorizing embedded radio equipment. Has
he become obsessed with collecting RF technology? It’s a bit too early to label him a certi-
fied radiophile, so give him a chance to explain what he’s been up to. Who knows, perhaps
his explanation will inspire you to incorporate some wireless gadgetry in your next design.

Figure 1—

The XTR-903-A4 hardware interface is dead easy because the blinking lights are optional.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

47

host microcontroller using the
PWRDN pin. The XTR-903-A4 draws
just under 10 µA in this mode.

To keep things really simple, the

XTR-903-A4 uses a set of unique AT
commands to select one of 10 channels
between 433 and 434 MHz and set the
module’s RF output power. An AT
command to monitor channel activity
and signal strength is also incorporated.

XTR-903-A4 transmission and

reception synchronization is automat-
ic thanks to the embedded ATmega8(L).
All you have to do is feed data to the
XTR-903-A4’s serial interface without
any regard for data length. The XTR-
903-A4 doesn’t do any data buffering,
nor does it add a CRC or any other
form of checksum data to the transmit-
ted data. A preamble is automatically
inserted at the beginning of a transmis-
sion to allow the remote XTR-903-A4’s
receiver to synchronize. The inclusion
of the preamble induces a data trans-
mission latency of about 20 ms, which
means you should allow 20 ms for
transmit-and-receive switching in your
application code. The logic inside the
XTR-903-A4 also automatically
appends an end-of-transmission data
sequence to the transmitted data packet.

My set of XTR-903-A4 embedded

radios didn’t come with an evaluation
board. So, using the straightforward
technical detail included in the XTR-
903-A4 documentation, I easily craft-

ed my own set of XTR-903-A4 evalua-
tion boards (see Photo 2 and Figure 1).

I selected the PIC16F84A as the host

microcontroller because it doesn’t
require a lot of effort to employ, can
operate at the 3-VDC level required by
the XTR-903-A4, and is superbly sup-
ported on the programming side by PIC-
START Plus, MPLAB, and the CCS C
compiler. As you can see in Listing 1,
the inclusion of the Atmel microcon-
troller in the XTR-903-A4 circuitry
makes it easy to code host microcon-
toller transmit and receive routines.

MaxStream 9XStream

My first impression of the

9XStream came when my UPS driver
handed me the 9XStream evaluation
kit box. It was a big box, and I figured
it held either a complicated data radio

kit or lots of goodies to support a sim-
ple, well-equipped embedded data
radio rig. Before installing the CD-
ROM-based documentation and con-
figuration program, I rummaged
through the evaluation kit to see if I
was going to have to go the Florida

Photo 1—

Here’s a glimpse of all of the radio partici-

pants. Each data radio has its own personality. That’s a
good thing because having a variety of differing features
allows you to select the right radio for your application.

Photo 2—

I used the PCB construction detail contained

within the XTR-903-A4 documentation to fabricate this eval-
uation board. What you don’t see are all of the SMT transis-
tors, resistors, and capacitors that support the status LEDs.

Listing 1—

A simple RS-232-capable microcontroller and some just as simple code are all it takes to put the

XTR-903-A4 on the air.

#include <16F84A.h>

#use delay(clock=20000000)

#fuses NOWDT,HS, PUT, NOPROTECT

#use

rs232(baud=9600,parity=N,xmit=PIN_A2,rcv=PIN_A3,bits=8,stream=to_

radio)

#byte PORTB = 0x06

// Ping-pongs 0x41 between unit 1 and unit 2, and complements

port B on both units with each transmission.

void main()

{

// Common code for both units

int8 data;

set_tris_a(0xFB);

set_tris_b(0x00);

// Unit 1 code

while(1)

{

putc(0x41);

while(!kbhit());

data = getc();

if(data == 0x41)

PORTB = ~PORTB;

}

// Unit 2 code

while(1)

{

while(!kbhit());

data = getc();

if(data == 0x41)

{

PORTB = ~PORTB;

delay_ms(1000);

putc(0x41);

}

}

}

background image

48

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

room library and meditate with the
9XStream documentation.

Three of what seemed to be commu-

nications interface adapters caught my
eye. The first adapter pulled from the
shipping foam was pink and imprinted
with the word “LOOPBACK.” Heck, I
know what a loopback adapter is. No
worries here, I assured myself.

Then, I asked myself what I’d do

with a loopback adapter in a wireless
network. OK. Next adapter. This
black adapter was labeled “Null
Modem Adapter.” I’m batting a per-
fect 1000 because I can also tell you
what a null modem adapter is used
for. Again, I asked myself what I’d do
with one in this environment.

I shrugged off the self-inflicted ques-

tioning and moved on to the third and
final adapter, which was white and iden-
tified as “Null Modem.” The tag on
the plastic bag also pointed out that
this adapter was a female-to-female
null modem adapter. Hmm. I pulled
out the black null modem adapter again
and noted that both of its interfaces
were male. As you can imagine, I was
ignorant at this point, and this group of
out-of-place adapters really had me
swinging. What in the world am I going
to be looping back? I wondered. What
am I going to do with “null modeming”
in a set of wireless data radio modules?

Fortunately, the rest of the parts

and pieces made a bit more sense to
me. The following were easily identi-
fiable: a couple of nine-pin male-to-
female signal cables for attaching to
PC serial ports, two 9-VDC wall
warts, and a pair of male and female
nine-pin to RJ-45 adapters to allow the
use of Cat 5 cabling as data cable. The
neatest cable I found adapted a stan-
dard 9-V battery to the wall wart
power receptacle on the evaluation/
development board. I figured that the
examination of the actual data radio
electronics would give me some clues
as to what to do with those crazy
communications adapters.

I decided to begin by examining a

9XStream evaluation board. The RS-
232/485 circuitry looked standard
enough, as did all of the pinouts for
interfacing to the actual 9XStream
data radio module.

DIP switch settings determine if

you have to incorporate parity or run
RS-232, two-wire RS-485, or four-wire
RS-485. 9XStream RS-485 termination
options are also DIP switch-selectable.
The remainder of components on the
evaluation board consists of a low-
power, low-dropout voltage regulator
and supporting circuitry, a configura-
tion push button, and an ATtiny26
microcontroller. Hmm.

The 9XStreams that I dug out of the

box are compact data radios that oper-
ate in the 900-MHz band at 9600 bps.
The 9XStream’s RF circuitry is con-
fined to a shielded enclosure with an
ATmega32(L) being the most promi-
nent part mounted outside the shield.

After I assembled the 9XStream radios

and evaluation boards, I connected them
to separate PCs in the Florida room.
Instant gratification: the radios worked

perfectly together right out of the box.
The next step was to sort through the
9XStream documentation to try and fig-
ure out what to do with the adapters.
The documentation on the CD-ROM is
extremely detailed and complete.

The 9XStream can be programmed

using 9XStream-unique AT-type com-
mands or via the X-CTU program,
which is on the CD-ROM. The AT
commands that can be issued fall into
four categories: diagnostic services,
networking services, command mode
operations, and serial interfacing. The
X-CTU interface automates the AT
command configuration process and
includes extra services like range test-
ing and an ASCII terminal interface.

While experimenting with the X-CTU

application, I came across a section in
the advanced 9XStream documentation

that solved the communications adapter
mystery. The pink loopback adapter is
used to loop received data back into the
transmitter during range testing. Using
the pink loopback adapter converts the
stationary remote radio into a repeater
that simply echoes the data sent from
the 9XStream radio you’re walking away
with during the range test. The black
null modem adapter is used to connect
the 9XStream’s DCE interface to anoth-
er target DCE interface. The white
female-to-female null modem adapter
replaces a set of 9XStream data radios
and can be used to connect and test the
DTE interface cables that connect the
9XStream to each respective host.

Now that everything has been identi-

fied and categorized, what does it take
to connect the 9XStream to an embed-
ded host? The answer is simple: three
wires. From the 9Xstream’s perspec-
tive, they are data in (DI) from the host,
data out (DO) to the host, and clear to
send (CTS). All else is automatic. The
9XStream adds a factory-assigned vendor
ID number (VID), a channel number
(ATHP), a module address (ATDT), and a
packet serial number (PSN) that identi-
fies each packet in front of the data
received from the host. A 16-bit CRC
is appended to the outgoing packet.

There are also 9XStream pins that

provide optional features such as
power-down, reset, and module status
that can be used by the host and host
application. The 9XStream has a use-
ful range of up to 1500

with a stan-

dard whip antenna. If your 9XStream
radios are configured with special
high-gain antennas, you can obtain
signal ranges of up to 20 miles line of
sight. Using the DCE-to-DCE adapter,
I 9XStream-enabled an EDTP Easy
Ethernet ASIX board, which happens
to have an on-board PIC microcon-
troller supporting a simple three-wire
RS-232 DCE interface (see Photo 3).

easy-Radio MODULE

While ridin’ the range, I managed to

rope a few easy-Radio data radios con-
sisting of a 433-MHz pair, a 900-MHz
pair, and a 900-MHz frequency-hopping
pair. The 433- and 900-MHz modules
are identical. The only way to tell the
easy-Radio modules apart is to read their
brand—ER400TRS for the 433-MHz

Photo 3—

Here’s an example of “drop in” RF. The

EDTP Easy Ethernet ASIX board can now add wireless
to its Ethernet and I²C connectivity resume. All I had to
do to wireless-enable the Easy Ethernet board was
change the data rate in the PIC firmware.

background image
background image

50

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

modules and ER900TRS for the 900-
MHz modules. Both frequency ranges
of the easy-Radio module pairs can be
plugged into a common set of evalua-
tion boards, which are included in the
easy-Radio evaluation kit.

I managed to take the “easy” out of

the new easy-Radio evaluation boards
by making assumptions and not paying
attention to the documentation. The
frequency-hopping easy-Radio modules,
which are marked as ER900FHTRS, are
larger than the non-hoppers because of
some extra pins on the hopper radios. If
you’re a Circuit Cellar regular familiar
with your back issues, you know that
I’m not new to easy-Radio technology
(“RF Made Simple,” Circuit Cellar,
issue 160, November 2003).

In fact, some of the legacy easy-

Radio equipment is still on the Florida
room’s shelf. The legacy and new easy-
Radio evaluation boards provide a
socket position that accepts the slight-
ly larger hopper radios. Of course, if it
fits, plug it in. Right?

Hours later, after trying all sorts of

things, I could not get the new hoppers
to talk to each other. I turned to the
easy-Radio documentation out of des-
peration. I noticed that my new evalu-
ation boards were void of the valid sta-
tus LED. I unboxed my old down-level
hopper evaluation boards and lo and
behold there it was, the extra valid
indicator LED. I started comparing the
ER900FHTRS sockets on each evalua-
tion board and found that the antenna
pin for the legacy hopper modules on
the new evaluation board had to be
grounded, which is a subtle hint that
you shouldn’t be using the new evalu-
ation board to test down-level hopper
easy-Radio modules.

I can get around that, I thought, so I

flexed what I surmised to be the new
hopper’s antenna pins to fit into the
antenna pins on the smaller module
socket behind the hopper socket. I
could see the trace to the antenna from
the smaller socket pin behind the hop-
per’s socket, and I thought this would
make things all better. Ha! Nothing
changed. Still no signal.

Further investigation of the

ER900FHTRS version 2.00 Quick
Start Guide pointed out that what I
thought to be the antenna pin on the
new modules is indeed a ground pin.
Aha! So that’s what that pair of
antenna coax leads are for.

As it turned out, the new

ER900FHTRS hoppers have an antenna
receptacle cut out in the side frame of
the easy-Radio hopper module that
accommodates the coax antenna lead
that came with the easy-Radio hopper
evaluation kit. What was not obvious
to me will be obvious to you if you
take a look at Photo 4.

The smaller 433-MHz easy-Radio

modules plugged right in and worked
right out of the box. If I had slowed
down and done some reading, I would
have had the same success with the
easy-Radio frequency hopper mod-
ules. In addition to the new antenna
connection, the new easy-Radio
ER900FHTRS radios can operate in
Client/Server mode at 38,400 bps.
An improved version of the easy-
Radio configuration software on CD-
ROM also comes with the new evalu-
ation kits.

RADIOMETRIX SpacePort

Atmel has been well represented in

the embedded radio controller role
thus far. The Radiometrix SpacePort
data radio prevents a shutout and incor-
porates a PIC16F876 to invoke its RF
features. From what I could glean from
the SpacePort documentation, the PIC is
the radio packet modem (RPM). A fast
radio packet controller (FRPC) works in
conjunction with the RPM and resides
under the shield with the SpacePort’s RF
circuitry. It’s just a guess, but looking
at the SpacePort documentation, the
FRPC is most likely a PIC16F84A run-
ning at full speed (20 MHz).

My SpacePort module (SPM) evalua-

tion kit came with a pair of SPM2-433-
28 433-MHz radio modules and a pair
of matching evaluation boards. Options
can be exercised to get the SpacePort
modules configured for the 869- and
900-MHz bands. There are a bunch of
configuration options that can be dialed
into the SpacePort, and the configura-
tion parameters are set using a simple
terminal program like HyperTerminal
or Tera Term Pro. Photo 5 is a shot of
what my SPM spit out when I jumpered
it into Setup/Configuration mode.

As you might ascertain from the

SPM configuration entries, the
SpacePort is packet-oriented and
designed to work well in addressable
wireless networks. To that end, the
SpacePort performs error checking,
packet acknowledgement, and retrans-

Photo 4—

The coax attachment feature is nice

because you aren’t tied down to placing an antenna
connector pad on your final PCB.

Photo 5—

The SpacePort SPM2-433-28 is an internation-

al kind of data radio. Note the FCC airspeed setting. If
you’re wondering, the radar setting is for range testing.

Photo 6—

The SD-202 gets it power from the EDTP

Easy Ethernet ASIX via a DC power cable assembly
that comes with the Bluetooth radios. Mark, the
machinist that fabricates all of my weird metal and
plastic stuff for my Circuit Cellar articles, is also using
Bluetooth modules in his machine shop to communi-
cate with a prototype project he is working on.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

51

mission functions to help guarantee
the integrity of data flowing on the
wireless links. The SpacePort’s maxi-
mum acknowledged throughput is
28 kbps. Unacknowledged throughput
is rated at a maximum of 55 kbps.

The SpacePort only requires a sim-

ple three-wire interface to a control-
ling host: transmit data (TXD), receive
data (RXD), and clear-to-send (CTS).
However, particular attention has been
directed toward providing plenty of
visual feedback relative to the condition
of the wireless link and the data flow-
ing across it. Figure 2 is a pretty good
representation of how the SpacePort
module can be deployed; it closely fol-
lows the way the SPM is implemented
on the SpacePort evaluation board.

INITIUM

No, I haven’t forgotten my ABCs. The

Initium Promi-SD202 is a Bluetooth
product, and I didn’t want to mix the
bulls with the broncos. I’ve been experi-
menting with some Bluetooth nodes and
have used them to replace RS-232 cables
between gadgets in the Florida room.

The Promi-SD202 is a class 1 Blue-

tooth transceiver powered by a 5-VDC
power source that can be attained from
a PC USB port, an optional wall wart,
or a direct connection to the host power
subsystem using a supplied DC power
cable. It can operate at data rates rang-
ing from 1200 to 230,400 bps, and it
connects to the host via an integral
nine-pin RS-232 DCE interface. The
effective range is approximately 100 m.

Getting on the air with the Promi-

SD202 modules was a breeze. A con-
figuration program is included with
the module pair that permits you to
select data rate, connection, and secu-
rity options. There are four modes of
operation defined in the configuration
program. Mode 0 is used to initially set
up the SD202 modules, which involves
selecting over the air data rates and dis-
covering other Bluetooth modules that
are connectable and within range.

I wanted the SD202 module pair to

always connect at power-up, so I used
the mode 0 functions to allow the
modules to learn about each other
(device address, device name, class of
device, etc.) and establish an initial
connection. Both SD202 modules auto-
matically store the Bluetooth device
address of its latest counterpart,
which allowed me to set one module
to mode 1 and the other to mode 2.

Mode 1 instructs the SD202 to con-

nect only to the last connected device,
while mode 2 tells the companion
module to accept only a connection
from the last device it was connected
to. After the initial connection is com-
plete and the modes are set, the
Promi-SD202 modules can be used as
100-m virtual data cables between
machines and various RS-232-
equipped gadgets in the Florida room.

I’m always testing the RS-232 inter-

faces on the Easy Ethernet devices that I
ship. Using Bluetooth instead of a cable
removes the distance restriction when a
unit goes back to the bench for testing.
I Bluetooth-enabled an EDTP Easy
Ethernet ASIX using the black male-to-

male null modem adapter from the
9XStream evaluation kit (see Photo 6).

GIT ALONG LITTLE DOOGIES

We’ve ridden and roped every data

radio that we’ve brought with us.
Now it’s time to gather all the livestock
and move on. If every segment of tech-
nology worked as hard to make its
products as easy to use and assimilate as
the embedded data radio folks do, we
would already have a colony on Mars.

All of the embedded data radio units

I mentioned are designed to be
dropped into your final product with a
minimum of wand swinging. Visit
each manufacturer’s web site, and
you’ll find lots of additional informa-
tion to help you incorporate wireless
into your next design. Using them in
your projects allows you to wear your
pointy RF wizard hat to anybody’s
rodeo with pride because you will have
helped to prove that RF doesn’t have to
be complicated to be embedded.

I

Figure 2—

To make implementing the SpacePort as simple as implementing the XTR-903-A4, you can use any microcon-

troller, eliminate the RS-232 driver, pull your 5 VDC from an existing power source in your project, and chuck the LEDs.

Fred Eady has more than 20 years of
experience as a systems engineer. He
has worked with computers and com-
munication systems large and small,
simple and complex. His forte is
embedded-systems design and com-
munications. Fred may be reached at
fred@edtp.com.

SOURCES

XTR-903-A4 Transceiver module
Abacom Technologies
www.abacom-tech.com

EDTP Easy Ethernet ASIX board
EDTP Electronics
www.edtp.com

XStream Wireless development kit
MaxStream, Inc.
www.maxstream.net

easy-Radio
Low Power Radio Solutions Ltd.
www.lprs.co.uk

SpacePort and Promi-SD202
Lemos International Co., Inc.
www.lemosint.com

PICSTART Plus and MPLAB
Microchip Technology, Inc.
www.microchip.com

background image

external interrupt to monitor the
activity of the I

2

C bus and software.

[1, 2]

However, many devices have built-

in hardware designed for I

2

C commu-

nication. The universal serial interface
(USI)—which is a flexible subsystem
found on the ATtiny26, ATtiny2313,
and ATmega169 processors—provides
the hardware for serial communica-
tion, including three-wire SPI and I

2

C.

It features a data received interrupt
and a two-wire start condition detec-
tor that can generate an interrupt.
Furthermore, the USI can wake up the
processor from Sleep mode. In this
article I’ll show you how to use the
USI to create an I

2

C slave.

I

2

C PROTOCOL

The I

2

C bus is a two-wire interface

that uses a serial clock (SCL) and a seri-
al data (SDA) line. I

2

C devices have open

drain/open collector drivers with a set of
external pull-up resistors. When the bus
is idle, I

2

C devices turn off their drivers

and the resistors pull the SCL and SDA
lines high. Because of the open
drain/open collector nature, any device
can pull the SCL or SDA lines low.

An I

2

C master initiates a transmission

by generating a start (S) condition on the
bus; it terminates a transmission with a
stop (P) condition. The bus is considered
busy (and owned by the master that
generated the start condition) between
the start and stop conditions.

A start condition occurs on a high-

low transition of the SDA line while
the SCL line is high. A stop condition
occurs on a low-high transition when
the SCL line is high. A repeated start

52

Issue 166 May 2004

www.circuitcellar.com

T

he Inter-IC, or I

2

C bus, which was

created by Philips nearly 20 years ago,
is a well-understood, relatively simple
bus that is now widely used in embed-
ded applications. Its appeal lies in the
fact that it is a two-wire interface
(TWI) that conserves I/O pins.

The bus follows the master-slave

paradigm. Slave devices have unique
addresses on the bus. A master device
takes control of the bus and sends
control information to the slave
device. The slave acknowledges, and
the master can then read from or write
to the slave. When the communication
is complete, the master releases the
bus. Furthermore, there are many I

2

C

peripherals available (e.g., EEPROMs,
serial RAM, serial ADCs, serial DACs,
and I/O expanders), and they become
slave devices in embedded applications.

You’ll find an ample amount of

resources available with respect to the
I

2

C master side. Many microcon-

trollers have built-in I

2

C hardware,

most compilers have libraries for
implementing an I

2

C master, and

there are many bits of source code on
the ’Net in different programming lan-
guages and for different microcon-
trollers. But there are fewer options
available for those of you who want to
create your own slave I

2

C device.

Imagine that you have a sensor that

you want to turn into an I

2

C slave

device. One solution is shown in
Figure 1. A Phillips PCA9564 parallel
bus-to-I

2

C controller takes eight paral-

lel lines from the microcontroller and
converts it into a bidirectional I

2

C.

This chip provides the same function-

USI-Based I

2

C Slave

ality as the older PCF8584, but it is
faster and uses less power. The paral-
lel interface of the PCA9564 can run
up to 50 MHz; on the I

2

C side, it can

approach 360 kHz. Another option is
to use an I

2

C I/O expander chip such

as the PCF8574, which is simpler to
work with but provides only quasi-
bidirectional functionality (which
may be fine for some applications).

Regardless of which chip is used,

the resulting slave ignores commands
sent to other I

2

C devices. A master

can send data bytes to the device, and
it appears at the chip’s data pins,
which interface with a microcon-
troller that performs the core task.
These hardware solutions provide the
I

2

C electrical interface, hardware to

select a bus address, and hardware to
recognize when a master talks to it.

The problem is the 8-bit parallel

interface between the microcontroller
and the dedicated I

2

C controller or I/O

expander. There are also control sig-
nals, and you can quickly run out of
microcontroller pins on smaller
devices. As opposed to a full hardware
solution, you can implement an I

2

C

interface essentially in software, using
a combination of a microcontroller’s

FEATURE ARTICLE

by Anton Kruger

Implementing an I

2

C interface doesn’t have to be a hardware-heavy endeavor; you can

combine a microcontroller’s external interrupt and software. The USI subsystem found
on the ATtiny26 enables serial communication. In this article Anton explains everything
you need to know, including the software specifics, to create a USI-based I

2

C slave.

Microcontroller,

microprocessor,

or ASIC

PCA9564

Master

8 bits

Control

signals

SDA

SCL

Figure 1—

With dedicated hardware like the Philips

PCA9564, you can create a fast I

2

C slave. However,

this requires 8 bits of parallel I/O and control lines
between the PCA9564 and the microcontroller.

background image

slave receiver. A receiver must ACK
each byte it receives by keeping the
SDA line low during the ACK pulse. If
the receiver (master or slave) wants to
end reception, it generates a NACK.

A master may take control of the

I

2

C bus and send configuration infor-

mation to a slave. It can then switch
the data direction and become a master
receiver before issuing a stop condition.
The master does this by generating a
repeated start condition and transmit-
ting the slave address with the eighth
bit clear, signaling to the slave that it
wants to read from it. Figure 2 illus-
trates this; it is a conversation between
an I

2

C master that sends 1 control byte

to a slave. After it is configured, it reads
2 data bytes from the slave.

The conversation between the I

2

C

master and slave has several parts.
The first involves the master sending
a control byte to the slave. First, it
generates a start and then writes the
8-bit slave address with the eighth bit
clear (see 1–2 in Figure 2). This
informs the slave that the master will
be writing to it. Following this, the

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

53

slave acknowledges by keeping the
SDA line low when the master makes
the ACK clock pulse (see 3 in Figure 2).
Then the master sends the 8-bit control
byte to the slave, which acknowledges
by keeping the SDA line low when the
master makes the ACK clock pulse.

In the next part, the master retains

control of the bus and changes the data
direction. The master issues a start.
Because this is issued before a stop, it
is a repeated start. Next, the master
writes an 8-bit slave address with the
eighth bit set. This informs the slave
that the master will read from it. The
slave acknowledges by keeping the
SDA line low when the master makes
the ACK clock pulse.

In the final part, the master reads

from the slave. After the slave sends a
byte, the master acknowledges. Then
the slave sends another byte. Next,
the master NACKs by keeping the
SDA line high when it makes the
ACK pulse. The slave sees the NACK,
and knows that the read operation is
over. Finally, the master generates stop.

CLOCK STRETCHING

The master controls the bus insofar

as it generates the start and stop con-
ditions and the clock pulses. A slave
normally leaves the SCL line alone.
Sometimes a slave needs to wake up
after a start or perform some relatively
lengthy task before being able to
respond to a master. The I

2

C protocol

allows slaves to insert wait states by
pulling the SCL line low. This is
called “clock stretching.” With the

(Sr) condition occurs when a start con-
dition occurs between a start and stop
condition. These are the only times
when the SDA line is allowed to
change while the SCL line is high. At
other times, I

2

C devices change the

SDA line when the SCL is low, and the
data is considered valid and should be
kept stable when the SCL line is high.

Communication on the bus is with

9-bit packets: 8 bits are addresses or
data followed by the ninth acknowledge
bit. The master generates all the clock
pulses. After a master has taken control
of the bus, it addresses a slave by clock-
ing the 8-bit slave address out onto
the SDA line and slave receivers on the
bus clock in the address. The slave that
recognizes its address pulls down the
SDA line for the duration of the next
(ninth) pulse the master generates.

A low SDA line during this

acknowledge pulse constitutes an
acknowledge (ACK) by the slave
receiver. If the slave is busy or not on
the bus, it leaves the SDA line high.
This is called a “not acknowledge,” or
NACK. If the master sees a NACK, it
can abort the transfer with a stop con-
dition or issue a repeated start and try
again without relinquishing the bus.
The master also issues a repeated start
when it wants to change data direc-
tion but maintain control of the bus.

The eighth bit of a slave’s address

determines the data direction. If the
bit is clear (0), the master will write to
a slave that acknowledges. A master
may send control bytes to configure or
data (e.g., an EEPROM) to a slave.
When the eighth bit in the slave
address is set (1), the master reads
from a slave. Both masters and slaves
can be receivers or transmitters. When
a master sends data to a slave, it is a
master transmitter and the slave is a

S

Address

*W

A

Data

A

Sr

Address

R

A

Data

A

Data

*A

*P

Master writes to slave

Master reads from slave

Master

Slave

1

2

3

4

5

6

7

8

9

10

11

12 13

A = Acknowledge (ACK)
*A = Not acknowledge (NACK) S = Start

P = Stop

Sr = Repeated start

Figure 2—

In this conversation between I

2

C master and slave, the I

2

C master writes 1 byte, generates a repeated

start condition, changes data direction, and then reads 2 bytes from a slave.

Data b

u

s

USICR

USISIE

USIOIE

USIWM1

USIWM0

USICS1

USICS0

USICLK

USITC

USISR

USIDR

USISIF

USIOIF

USIPF

USIDC

4-bit Counter

10

[1]

TIM0 OVF

3
2
1
0

3
2
1
0

D Q

LE

Bit 7

Bit 0

PB1

PB0

Two-wire clock

control unit

PB2

Clock

hold

DO
(Output only)

DI/SDA
(Input/open drain)

SCK/SCL
(Input/open drain)

2

Figure 3—

Through the judicious use of the USI on the ATtiny26, the number of lines of code for an I

2

C slave can

be small and efficient.

background image

(mode 10), the start detector is active.
In the second mode (mode 11), the
start detector and overflow counter are
active. The latter is the most flexible
mode. When the USI detects a start con-
dition, it sets a flag and can generate an
interrupt. It also wakes up the processor
if it’s in Sleep mode. When a counter
overflow occurs, a flag is set, and it too
can generate an interrupt. Both start
detect and counter overflow pull the
SCL line low. The master is not able to
pull the line high to generate a clock.

It is the combination of the start

condition detector, the shift register,
and the 4-bit counter with overflow
flag and interrupt capability that
makes the USI system flexible. The
USI behavior and state is controlled
and tracked using the USI control reg-
ister USICR and the USI status regis-
ter USISR. To implement an I

2

C slave

interface using the USI requires
manipulation of these registers and
the USI data register USIDR.

Through the judicious use of the

hardware, the number of lines of code
for an I

2

C slave is small and efficient.

For example, to generate an ACK, the
slave has to keep the SDA line low for
the duration of the acknowledge pulse
the master generates. The snippet in
Listing 1 relies on the fact that port
B.2 is the SCL line.

Listing 2 shows the preferable

method. First, load the counter with the
value 14. Because the counter counts
transitions, the acknowledge pulse from
the master increments it twice, caus-
ing it to overflow. The SDA line is also
connected to bit 7 of the USI data reg-
ister USIDR, so if you load it with zero
and turn on the SDA driver, it will pull
the SDA line low. This approach uses
the hardware to its fullest; it is com-
pact, fast, and has the added benefit that
when the counter overflows, the USI
hardware automatically pulls the SCL
line low, inserting a wait state.

USI-BASED SLAVE

Figure 4 shows the hardware for an

I

2

C slave using the ATtiny26. It uses the

ATtiny26’s built-in ADC and creates an
I

2

C A/D converter. The ATtiny26 can be

configured to have 11 10-bit, multi-
plexed, single-ended channels or eight
differential channels. There are many

54

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

detects an I

2

C start condition. It

wakes up the processor, and you can
configure the USI to generate an inter-
rupt. The 4-bit counter can be discon-
nected or configured to take its input
from the SCL line (port B.2). When its
input comes from the SCL line, the
counter counts the number of SCL
transitions, not the number of pulses.
When the counter overflows on the
transition from 15 to 0 (i.e., after eight
clock pulses), it raises its overflow flag
USISR.6 and can generate a counter
overflow interrupt. When the overflow
flag is raised, it stays raised until it is
explicitly cleared (by writing 1 to it).
Additionally, when the flag is raised,
the SCL line is pulled low, which
locks the I

2

C bus and prevents the

master from clocking the SCL line.

The 8-bit USI data register USIDR

contains the incoming and outgoing
data; it is a shift register with its input
(bit 0) connected to the SDA line (port
B.0). Note that its output (bit 7) is
connected through a delay element to
the SDA line. Both the counter and
shift register are clocked simultane-
ously via the same clock source.

By setting the USIWM1 and

USIWM2 bits in the USI control regis-
ter USICR, you can select one of two
possible TWI modes. In the first mode

SCL line low, the master can’t gener-
ate clock pulses and this locks the I

2

C

bus. The USI slave implementation
described here uses this aspect of the
I

2

C bus. This is automatic and built in

the USI hardware.

A word of caution is in order:

libraries that properly implement I

2

C

master software should monitor the SCL
line. In reality, I

2

C devices implemented

in hardware are normally fast, and most
I

2

C slave devices don’t insert wait states.

An I

2

C master can get by without moni-

toring the SCL line. This is reflected in
some I

2

C libraries: they don’t check for

wait states. Rather, they happily pump
out the data on the SDA line while
clocking the SCL line. This can cause
confusion unless you’re aware of it.

AVR USI

As you can see in Figure 3, the AVR

USI schematic includes a 4-bit counter,
8-bit shift register/data register (USIDR),
status register (USISR), and control regis-
ter (USICR). For a detailed description of
the USI and the meaning of the bits and
flags in the registers associated with it,
refer to Atmel’s site. Here, I will focus
only on the aspects relevant to imple-
menting an I

2

C slave using the USI.

The USI contains a hardware start

detector that raises a flag when it

Figure 4—

The hardware for an ATtiny26-based I

2

C slave implements a multichannel ADC. The only hardware

required is the ATtiny26, a crystal, and C

1

through C

4

. For flexibility, the circuit incorporates in-circuit programming,

which the ATtiny26 supports. When the ISP programmer pulls the RESET pin (10) low when it starts programming, the
CD4066 analog switch is wired to disconnect the chip’s MOSI and SCL lines from the external SDA and SCL lines.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

55

A/D converters with I

2

C interfaces, so

this circuit is not that useful. However,
it’s easily adapted for many other pur-
poses by replacing the ADC routine
with an application-specific routine.

I wrote the software with the

CodeVisionAVR compiler, but it should

be straightforward enough to port to
other compilers or assembly language.
This I

2

C slave will accept a control byte

that determines which of the ATtiny26’s
ADCs to use by setting the appropri-
ate bits in the ATtiny26 ADMUX reg-
ister. When the I

2

C slave is read from,

it does a conversion and returns the
value. Listing 3 illustrates how a mas-
ter would communicate with the I

2

C

slave. You may download the software
from the Circuit Cellar ftp site.

A global variable,

_i2cstate,

keeps track of the state of the I

2

C

slave. Has it recognized its address on
the I

2

C bus? Is it being written to? Is

it being read from? And so on.

After resetting and initializations,

the processor goes to sleep. When the
USI hardware detects a start condi-
tion, it sets the start condition flag and
pulls the SCL line low (preventing the
master from clocking in the address).
Next, the start condition ISR is activat-
ed. In anticipation of the 8-bit address
that will follow, it loads the counter
with zero and connects the input of the
SCL line to the counter. It then clears
the start condition detected flag, which
releases the SCL line. On each of the
next eight clock pulses, the shift regis-
ter shifts in the value on the SDA line.
The counter increments on each of the
16 transitions (two per clock pulse).
When it overflows, the 8-bit address is
in the USI data register. The overflow
sets the overflow flag, pulls the SCL
line low (preventing the master from
clocking the SCL line), and activates
the overflow ISR.

Up to this point, the USI hardware

has done all the hard work: it detects
the start condition, wakes the proces-
sor, and reads in an 8-bit address. The
task for the overflow ISR is a simple
one: check the 8-bit address in the
shift register against the slave address.
If it matches, it sets the global vari-
able

_i2cstate and generates an I

2

C

ACK. Like before, when the overflow
flag is set, the USI hardware pulls the
SCL line low, which prevents the
master from clocking the line.

The start condition also wakes up

the processor and it enters the loop in
main. In the loop, it checks the bits in
the

_i2cstate variable and takes

appropriate action. If its address did
not follow the start condition, it goes
back to sleep. If it did see its address,
it checks the R/*W bit. If it is being
written to (R/*W equals zero), it reads
in 1 byte and makes an ACK.

The number of bytes read (if any)

and what the slave does with the

Listing 3—

This code snippet illustrates how an I

2

C master communicates with the slave (see Figure 3).

#define SLAVE 0xaa

// Address I

2

C device in Write mode, and then send a

configuration byte (select DAC number 4).

i2c_start();

if (!i2c_write(SLAVE)) {

printf(“Error (1): Device did not ACK\r\n”);

goto L10;

}

if (!i2c_write(4)) {

printf(“Error (2): Device did not ACK\r\n”);

goto L10;

}

// Change data direction. This signals slave to start D/A.

Give it 150 us to complete.

delay_us(10); // Breathing room.

i2c_start(); // Repeated start.

if (!i2c_write(SLAVE |1)) {

printf(“Error (3): Device did not ACK\r\n”);

goto L10;

}

delay_us(150); // Wait for conversion to finish.

// Read 2 bytes. Don’t ACK the second byte from the

slave, this will tell the slave to quit sending.

b1 = i2c_read(1); // Read and ACK.

b0 = i2c_read(0); // Read and NACK.

L10: i2c_stop();

printf(“Values: %d %d %d\n\r”,b1,b0,(int)(256*b1+b0));

Listing 1—

This snippet shows one method of making an ACK.

DDRB.0 = 1;

// Port driver on.

PORTB.0 = 0;

// Pull SDA low.

while (PINB.2 != 1)

// Wait for SCL to go high.

;

while (PINB.2 == 1)

// Wait for SCL to go low.

;

PORTB.0 = 1;

// Let go of SDA (makes it go high).

DDRB.0 = 0;

// Port driver off.

Listing 2—

A preferred way to ACK, this method uses the USI hardware. It is fast, compact, and automati-

cally inserts a wait state on the bus.

USIDR = 0x00;

// Clear USI data register.

DDRB.0 = 1; // SDA driver on (SDA = USIDR.7).

USISR = 0b01001110; // Clear overflow flag, value = 14.

USICR = USICR | 0b0001000; // Enable counter clock.

while (!USISR.6) // Wait for overflow.

;

USICR = USICR & ~0b0001000; // Disable counter clock.

DDRB.0 = 0; // SDA driver off (free SDA).

background image

56

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

information depend on the applica-
tion. This particular slave reads 1 byte
and assigns it to the

dac variable,

which is the ADC port the master
wants to read from. If the slave is
being read from (R/*W equals one),
the slave sends 2 bytes. The master
should ACK every byte except the last
one, which it NACKs. Again, the
number of bytes that a master will
ACK depends on the application.

In Listing 3, the master requires

2 bytes that make up the result of the
A/D conversion. The master can con-
vert this to the voltage using the fol-
lowing equation:

where ADC equals 256 × b

1

+ b

0

, and

b

1

and b

0

are the bytes the slave returns.

V

REF

is the voltage reference used by the

ATtiny26. The ADC initialization post-
ed on the Circuit Cellar ftp site makes
V

REF

equal to 2.56 V. This is nominal,

however, and, according to the
ATtiny26 datasheet, the actual value
could be in the 2.5- to 2.7-V range.

GOTCHAS

The Atmel USI module is flexible

and easy to work with. With a decent
compiler, you can write an I

2

C slave

in a straightforward manner in C
rather than assembly language.

You must be careful though. If you

read over the ATtiny26 documenta-
tion, you’ll learn that performing a
read-modify-write operation on USISR
register, which involves using the SBI
or CBI instructions, will clear pending
interrupt flags. Atmel recommends
altering register contents by using
only the assembly language

OUT

instruction.

Thus, when you write the follow-

ing:

USISR = USISR | 0b01000000;

in C, the compiler should generate
code (assuming R16 contains the
contents of USISR) such as

MOV R30,R16 //Move USISR

contents to R30.

ORI R30,0x40 //Set bit 6.
OUT 0xE,R30 //Update USISR.

V

ADC

IN

=

V

REF

×

1024

rather than:

SBI 0xE,6 //Set bit 6 in USISR.

How a particular compiler trans-

lates a statement such as the next one
depends on the compiler.

USISR = USISR | 0b01000000;

You have to look at the assembly lan-
guage listing the compiler generates.
The CodeVisionAVR compiler seems to
favor the shorter, more efficient SBI/CLI
instructions. This is generally good
because you want fast and compact
code. In this case, it could lead to
dropped interrupts. However, if the C
language statement changes more than
1 bit, the CodeVisionAVR compiler falls
back to an

LDI/IN, ORI/ANDI, OUT

sequence. Thus, one method of ensur-
ing that the compiler uses the longer
but safer set of instructions is to always
change more than 1 bit in USISR.

Another approach is to use snippets:

tmp = USISR;
USISR = tmp | 0b01000000;

The compiler is coaxed into generat-
ing an

OUT instruction. This is where

embedded programming differs from
other types of programming: sometimes
you just have to know what the com-
piler does with those high-level instruc-
tions. There is no substitute for looking
at the assembly language instructions.

Another approach is to drop down

to assembly language. To do so, use
the

#asm and #endasm keywords.

Efficiency is another issue that

deserves consideration. With a 4-MHz
clock speed, the code presented here
provides performance that would be
acceptable in many situations. For
instance, when the processor is awake,
the start condition detect ISR completes
about 10 µs after a start on the I

2

C bus.

At 14.75 MHz, it takes about 3 µs.

A higher clock speed means more

power consumption, but this may not be
important. Even when power is an issue
in an application where the I

2

C slave

sleeps 99% of the time, a little extra
power consumption when it’s awake
may not matter. A higher clock speed is
not the only way to improve the per-

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

59

PROJECT FILES

To download the code, go to ftp.
circuitcellar.com/pub/Circuit_
Cellar/2004/166.

REFERENCES

[1] H. Krobath, “Seven-Segment LCD

Uses Two-Wire Interface”, EDN,
September 4, 2003.

[2] D. Caban, “Software Implementa-

tion of the I

2

C Protocol,” Circuit

Cellar Online

, March 2002.

[3] J. Irazabal and S. Blozis,

“AN10216-01 I

2

C Manual,”

Philips Semiconductors, 2003.

RESOURCES

Atmel Corp., “ATtiny26, ATtiny26L,”
rev. 1477E, 2003.

I

2

C bus information, www.semi

conductors.philips.com/buses/i2c/.

formance. Roughly half of the time is
spent on saving and restoring the proces-
sor registers at entry and exit of the ISR.
You can speed things up considerably by
only saving and restoring the registers
that are actually used. Listing 4 shows
how this is done for the CodeVisionAVR
compiler, where only

R30 and SREG are

saved and restored because they’re the
only ones used in this ISR. This is deter-
mined by examining the assembly lan-
guage listing generated by the compiler.

PROPER LICENSING

The software currently can’t handle

the occurrence of a stop condition. But
this is easily added because the USI sta-
tus register (USISR) contains a flag (bit 5)
that is set when a stop condition
occurs. For example, you could add code
that checks the flag after each transmit-
ted and received byte. When the flag is
set, transmission or reception is abort-
ed and the processor is put to sleep.

Finally, there are legal issues to con-

sider. Phillips controls the allocation of
I

2

C slave addresses. It’s the company’s

“position that all chips that can talk to
the I

2

C bus must be licensed. It doesn’t

matter how this interface is implement-
ed.”

[3]

So, if you want to create a slave

device for commercial use, it should
be licensed through the company.

I

Anton Kruger holds a Ph.D. in Electrical
and Computer Engineering from the
University of Iowa. He is a research
engineer at IIHR—Hydroscience and
Engineering at The University of
Iowa—where some of his work

SOURCES

ATtiny26 Microcontroller
Atmel Corp.
www.atmel.com

CodeVisionAVR C compiler
HP InfoTech S.R.L.
www.hpinfotech.ro

PCA9564
Philips Semiconductors
www.semiconductors.philips

Listing 4—

Using the CodeVisionAVR’s

#pragma savereg

preprocessor directive, you can save and

restore only those registers an ISR actually uses. This can substantially reduce the execution time. Other C
compilers have similar functionality.

#pragma savereg-

interrupt [USI_STRT] void usi_start_isr(void)

{

#asm

push r30

in r30,SREG

push r30

#endasm

// Rest of ISR code.

#asm

pop r30

out SREG,r30

pop r30

#endasm

}

#pragma savereg+

involves developing scientific instru-
ments that incorporate embedded
controllers. You may contact him at
anton-kruger@uiowa.edu.

background image

60

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

A

couple of nights before I started

this article, I had received a call from my
machinist buddy Mark. For those of you
who have taken the time to read my
previous columns (I thank you), you’ll
remember Mark as the guy who runs
a local machine shop that puts lots of
specially machined metal and compos-
ite material in the life science experi-
ments that fly on NASA’s orbiters. Back
in the fall of 2002, while in the throes
of preparing an article on Gecko motor
drives (“Geckodriving Your Motor
Control Applications,” Circuit Cellar
issue 148, November 2002), Mark and
I put the Gecko drives to work on a
real workaday CNC machine in his
shop. Recently, Mark rebuilt the
Gecko-driven CNC machine’s preci-
sion mechanisms and installed a new
PC-based control unit.

I met Mark years ago during my stint

as a consultant. He had a motor control
application problem, and I was hired to
write the code for what became affec-
tionately known to the project team
as the “Grinder Buddy.” As Mark and
I worked day and night on the Grinder
Buddy, we became friends. Seeing that
Mark had some embedded electrical
interest in his mechanical CNC cre-
ations, I supplied him with a functional
surplus oscilloscope, a DVM, and a
logic probe. Well, that was like giving
water to a Gremlin.

Mark’s phone call was a request for

help. He was “programming” a Basic
Stamp unit to monitor the fault lines

working on. I thought I needed some
type of mechanism to support the
MC34921 article, so Mark and I ban-
tered about ideas for at least an hour.
Because the idea behind the MC34921
is to inexpensively control small
motors, Mark thought I should field a
$4.95 Mars rover project. After we
both stopped laughing, I came up with
an idea that was just about as ridicu-
lous. I proposed that we take a tour of
the local toy store, collect cars and
tanks, and combine their motors and
bodies into a custom MC34921-based
vehicle. As the evening progressed, so
did the absurdity of our project ideas.

With the light of morning came men-

tal clarity and the realization that you
wouldn’t want another robot or remote-
controlled tank. I had a 64-lead LQFP
motor controller IC and 34 datasheet
pages that needed to be converted into
something you can use in a real project
of your own. So, instead of giving you
another make-this-robot article, I decid-
ed to provide you with a MC34921
development kit. The result of my
effort is shown in Photo 1. Let’s begin
by examining the MC34921 IC.

MC34921

The MC34921 power system control

IC is designed to drive up to three
small DC motors. Don’t let the LQFP
package size fool you. The MC34921
is packaged with an open heatsink pad
on its backside. The datasheet states
that with proper heatsinking, the

Get Moving with the MC34921 Power System
Control IC

FEATURE ARTICLE

by Fred Eady

on the three Gecko drives (x-, y-, and
z-axes) embedded in his newly refur-
bished CNC machine. He used his
oscilloscope to look at the Gecko fault
lines and found them to be extremely
dirty and glitchy. The Gecko fault lines
do double duty as inputs and outputs.
Because everything except the Basic
Stamp circuit was working as designed,
we figured that the periodically repeat-
ing glitches on the oscilloscope emanat-
ed by the fault lines were not the
result of noise, but were actually the
result of normal operating conditions.

A Gecko motor driver fault latches

the Gecko fault line low. Mark’s
Stamp program was randomly picking
up the repeating low-going spikes on
the Gecko motor fault line and falsely
indicating a motor driver fault. So, we
devised a simple Basic Stamp program
to filter the spikes and look for a
steady low on the Gecko before indi-
cating a motor driver fault.

In the process of writing the Basic

Stamp code, I was also working on this
article and had in my possession a pretty
nifty little motor controller IC from
Motorola. In the meantime, Mark
turned on the CNC’s main breaker for
another test and found that the z-axis
Gecko was not responding. After some
quick troubleshooting, we decided that
the Gecko drive had come to the end of
its life, and we retreated to Mark’s office.

The discussion turned from the

burnt Gecko to the Motorola’s
MC34921 motor controller that I was

Motorola’s MC34921 is an inexpensive solution for controlling small motors. At first, Fred
was going to incorporate the device in a generic robotics project that you could work on in
your downtime. However, he soon switched gears, thinking it better to cover a development
kit that you can immediately put to use.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

61

MC34921 can drive motors at currents
up to 4.5 A. One of the three motor
drivers can be configured to drive a
step motor with up to 2 A of current.
Let’s walk through the features of the
MC34921. I will proceed counter-
clockwise through Figure 1, which is
your guide.

The first motor driver is motor driv-

er C, which can be configured as a step
motor driver or a DC motor driver.
The motor configuration is performed
using the MC34921’s integral SPI port.
When motor driver C is set up for Step
Motor mode, the high-side MOSFET
outputs (HSOUT1 and HSOUT2) can
be used as general-purpose high-side
outputs. The step motor is driven
using the SA and SB motor drivers.

When motor driver C is configured

for DC motor operation, the high-side
outputs (now DC motor drivers
CDCMA and CDCMB), in combination
with the SA pins that are now comple-
mentary CDCMA and CDCMB DC
motor drive pins, drive the DC motor.
That leaves the low-side MOSFET pins

(LSOUT1 and LSOUT2) available for
general-purpose, low-side outputs in DC
Motor mode. Motor driver C can supply

±

600 mA to a DC motor while in DC

Motor mode. In Step Motor mode,
motor driver C can source or sink up to
375 mA per energized output.

All of the MC34921’s motor drivers

are PWM-controlled. Motor driver C
gets its PWM signal from the CDCP-
WM line in DC Motor mode. In Step
Motor mode, motor driver C gets PWM
input from CPWMA for the SA outputs
and CPWMB for the SB outputs. To use
motor driver C as a step motor con-
troller, the B+ voltage must be equal to
or greater than 18 VDC, and less than
or equal to 20 VDC. The MOSFET out-
puts and the step-motor SA and SB out-
puts are controlled by manipulating
bits in the SPI motor control frames
sent to the MC34921 from a control-
ling microcontroller.

Continuing the counterclockwise tour

of Figure 1 brings you to motor driver A.
As you can see, motor driver A is a sim-
ple DC motor driver. Like all of the

MC34921’s DC motor drivers, a PWM
signal and direction bits in the SPI
motor control frame control the opera-
tion of the attached DC motor. APWM
is the PWM entry point for motor driver
A, and motor outputs ADCMA and
ADCMB provide the drive voltage for
the attached DC motor. The PWM sig-
nal frequency used to drive motors
attached to motor driver A should lie
between 20 and 40 kHz.

The DC motor driver bridge direc-

tion can be abruptly reversed, which
causes a reversal in current that pro-
vides a braking action for the attached
DC motor. Also, there are pull-down
resistors on the motor driver A PWM
inputs to safeguard the motor in case of
a connection failure at the motor driver
PWM input. High-side and low-side cur-
rent limiting and thermal shutdown pro-
tection are also built into motor driver
A. The maximum output current rat-
ing for motor driver A is 3.3 A.

Your next stop is motor driver B.

Everything that I said about motor driv-
er A applies to motor driver B, with the
exception of the maximum motor driver
output current. Motor driver B provides
a maximum of 2.5 A. It receives PWM
input on the BPWM pin and drives the
DC motor using voltages provided by
the BDCMA and BDCMB pins.

The MC34921 monitors itself inter-

nally and shuts down everything
except the RST circuitry when its
operating temperature exceeds 140°C.
The MC34921’s RST line is an open-
drain configuration; it allows the
MC34921 to be reset by, or initiate a
reset to, an external device such as a
microcontroller.

The MC34921 will remain in reset

as long as the B+ voltage is below the
minimum voltage level. The datasheet
states that any B+ voltage level above
9 VDC is sufficient to take the MC34921
out of reset. I found that it really takes
about 15 VDC of B+ voltage to wake
up my MC34921.

The MC34921 maintains an inter-

nal oscillator that runs at a nominal
200 kHz. The 200-kHz oscillator
clocks the VB charge pump that pro-
vides the high-side drive voltage for
the MC34921’s internal DC motor
H-Bridges and the external GATEOUT
signal. VB gets its input voltage direct-

B+

560 µF

7, 20, 21, 28, 29, 62 51 52

53

54

MISO MOSI SCLK *CE

56, 57

Serial I/O

I/V

Converter

46 ENC_FILTB
47 ENC_FILTA

A/D

Converter

and

multiplexer

45 AN3/ANALOGIN_B
44 AN2/ANALOGIN_A
43 AN1/ANALOGOUT_B
42 AN0/ANALOGOUT_A

Analog

encoder

SS DC motor driver

CDCMA/HSOUT1 63
CDCMB/HSOUT2 61

B+

*SA/CDCMA 3

*SA/CDCMB 4

*SB/LSOUT1 5
*SB/LSOUT2 6

CPWMA/CDPWM 55

CPWMB 58

Active clamp

Step

motor driver

B+

Motor driver A

B+

Motor driver B

APWM 59

ADCMA

14, 15

ADCMB

18, 19

BPWM 60

BDCMA

34, 35

BDCMB

30, 31

Oscillator

Thermal

shutdown

Gate driver

Supervisor

circuity

B+

3.3-V

Switching

regulator

10 3.3-V Switch100 µH +3.3 V

+

330 µF

11 3.3 V

12 V

CORE

SUPPLY

10 µF

13 V

CORE

V

CORE

SELECT

2

V

CORE

Linear

regulator

36 5-V Select
37 5-V Switch
38 5-V Supply
39 5 V

5-V

Dual-mode

regulator

Charge pump

gate voltage

generator

50 *RST

27 Gateout

22 V

B

23 CP2

26 CP1

0.1 µF

+

10 µF

B+

GND

1, 8, 9, 16, 17, 24, 25,
32, 33, 40, 41, 48, 49, 64

DGND

Figure 1—

There are lots of things going on inside the MC34921 in addition to the circuitry and logic that drive

motors. This IC not only provides the smarts, it provides the power as well.

background image

62

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

ly from the B+ line. My MC34921 sup-
plies 29.5 VDC at the GATEOUT pin
from an 18-VDC B+. The voltage at
the GATEOUT pin is controlled by a
bit in the SPI motor control frame.
GATEOUT is designed to drive an
external N-channel MOSFET.

In addition to controlling DC motors

and providing MOSFET gate drive volt-
ages, the MC34921 performs voltage
regulator duty. The first of three
MC34921 voltage regulator modules is
the 5-VDC regulator module, which
can operate as a switcher or a linear
voltage regulator. Like the VB charge
pump, the 5-VDC regulator feeds from
the MC34921’s B+ voltage. The 5-VDC
regulator can be employed only if B+ is
less than 20 VDC. In Linear mode, the
5-VDC regulator module must use an
external power resistor between B+ and
the 5-V SUPPLY pin to dissipate some
of the power off chip. Allowing the 5-V
select line to use the internal pull-up

resistor to assume a logic high state
and tying the 5- and 5-V switch lines
together select Linear mode.

My MC34921 development board

design uses the 5-VDC regulator mod-
ule in Switching mode. As you can see
in Figure 2, the 5-V select line is
grounded and a standard buck converter
component arrangement (recovery
diode, inductor, and output capacitor) is
employed. The buck regulator’s MOS-
FET switch is internal to the MC34921,
and the on-chip 200-kHz oscillator
provides the buck regulator’s clock.
The MC34921’s 5-VDC switcher is
rated at 600 mA.

The next regulator module is the

VCORE linear regulator, which feeds
from the MC34921’s 3.3-VDC regula-
tor output and can supply up to
300 mA of output current. Tying
VCORE SELECT to ground yields a
1.5-VDC VCORE regulator output. If
the VCORE SELECT pin is tied to

3.3 VDC, the VCORE output voltage
is 1.8 VDC. Floating the VCORE
SELECT pin results in 2.5 VDC at the
VCORE regulator output. I grounded
the VCORE SELECT pin on my
MC34921 development board and left
a trace to cut if another voltage is
required. The VCORE regulator on my
version of the MC34921 development
board powers nothing.

My counterclockwise tour is almost

finished. The next stop is the 3.3-VDC
switching regulator module. There is
only one configuration choice for the
3.3-VDC regulator module. The
MC34921’s 3.3-VDC voltage regulator
is a buck switcher that supplies up to
2.5 A of current.

The RST supervisory circuitry

monitors the voltages on all of the
MC34921’s voltage regulators and issues
a reset when any voltage falls below
fault levels. At initial power-up, the
MC34921 sequences the startup of the

Figure 2—

Using the RS-232 interface allows the motors to be controlled serially, and it provides a path for the motor status information to flow back to the end user.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

63

5- and 3.3-VDC voltage regula-
tors. The MC34921 checks off
one more requirement for a
successful exit of reset when
the 5- and 3.3-VDC regulators
come up to voltage.

If you have to know where

your motors are, the MC34921
includes an analog encoder
interface, which is intended
for use with an analog quadra-
ture encoder such as Agilent’s
HEDS-9710/9711. The HEDS
encoders supply a quadrature
output current that the
MC34921 converts to a volt-
age, which is then converted
to a set of digital encoder sig-
nals that is transferred inside the SPI
motor control frame.

To accomplish this, the MC34921 is

equipped with an I/V converter that
uses resistors across the AN2 and AN3
analog encoder inputs to force the prop-
er bias point on the encoder. The feed-
back resistors attached to the encoder
filter pins (ENC_FILTA and ENC_FILTB)
are sized to ensure a

±

2.5-V output volt-

age swing for the full encoder current
waveform. If you take the values
shown in Figure 2 and do the math,
my encoders produce a

±

49-µA signal.

The MC34921 datasheet states

specifically that to obtain an encoder
bias point of 1.35 V, the resistor across
the analog inputs to ground must be
1.17 times the value of the feedback
resistor. Doing that math yields a

value of 59.7 k

. The next

1% value up is 60.4 k

Ω,

and that’s what I’ve used
on my version of the
MC34921 development
board. To tweak things,
the MC34921 has a vari-
able gain amplifier posi-
tioned between the output
of the analog input stage
and the internal ADC.

Our counterclockwise

look at the MC34921 ends
with a familiar SPI inter-
face. What else would you
expect? Remember, this is a
Motorola article. Let’s walk
over the SPI wires to the

other side of the development board.

OTHER SIDE OF THE SPI

The MC34921 takes commands

from an ATmega16 running at full
bore (16 MHz). The ATmega16’s only
support is a companion Sipex
SPP233ECT RS-232 converter IC and a
Reset button. The only hard-wired
connections between the ATmega16

Photo 1—

I chose the ATmega16 as the MC34921 controller because I could easily

attach a JTAG ICE to the AVR. All of the AVR and MC34921 signal and driver pins
are terminated at headers. Using the female headers allows for the use of precut
solid wire like the kind used on solderless breadboards.

background image

emit PWM signals for the motors you
wish to drive. Getting the ATmega16 to
perform PWM duty is easy. Listing 1
contains sample PWM code.

The ATmega16 is equipped with an

on-chip, 8-bit SPI interface. However,
it is useless here because the MC34921
wants to see 16 bits of SPI data. I was
forced to use the MC34921’s SPI timing
diagram and write a custom bit bang
SPI routine to affect the MC34921-to-
ATmega16 SPI interface.

If you’re not an SPI guru, Atmel’s

AVR320 application note is a good
starting point for understanding what’s
behind writing SPI code. I used precut
wire that is normally used for solder-
less breadboard connections to con-
nect my software-assigned ATmega16
SPI interface to the MC34921’s SPI
pins. I also made a connection from
the ATmega16’s OC1A PWM output
to the MC34921’s APWM input pin. I
installed the JTAG ICE on the
ATmega16’s PORTC JTAG pins and
powered the JTAG ICE from the 5 VDC
supplied by the MC34921.

The hardware for this project is sim-

ple, but I ran into some real potholes
while developing my motor skills. So,
for the rest of the article, I’ll share my
MC34921 start-up experiences with
you.

Let’s start with what it takes to

drive a little Radio Shack DC motor
using the MC34921’s motor driver A.

DRIVING CONDITIONS

Figure 3 is a bit-by-bit layout of the

SPI command frame that flows from the
ATmega16 to the MC34921. In addition
to the bits in the motor-control frame,
the ATmega16 must be instructed to

64

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

and the MC34921 are
5 VDC and ground.
The MC34921’s 5-VDC
regulator supplies the
ATmega16’s 5 VDC. I
purposely brought all
of the MC34921 and
ATmega16 pins to
header points to allow
for freedom of connec-
tion between the
MC34921 and
ATmega16.

The ATmega16 AVR

ISP programming head-
er is absent because I
used the AVR JTAG
ICE to debug and pro-
gram the MC34921
development board’s
ATmega16. Note that I
used male headers on
the JTAG interface pins to accommo-
date the AVR JTAG ICE’s header.

I’ve already covered the MC34921

development board hardware. Let’s
move on and look at what it takes to
drive some motors.

Bit 0

Bit 1

Bit 2

Bit 3

Bit 4

Bit 5

Bit 6

Bit 7

Bit 8

Bit 9

Bit 10

Bit 11

Bit 12 Bit 13

Bit 14

Bit 15

config

start

A/Da0

A/Da1

A/D

a2

GAT EOUT

Bdca

Bdcb

Adca

Adcb

A/Cdca

*A/Cdcb

B

*B

OUT1

OUT2

Bit

Bit name

Bit description

0

config

The input frame can be either a configuration frame or

a normal frame. Bit 0 determines the type of frame being

received. Bit 0 = 0 is a normal mode input frame.

1

start

The A/D conversion start bit causes the ADC to sample the input(s) specified by bits A/Da[2~0] (bits[4-2]) and
begin an analog-to-digital conversion. This bit is ignored if a conversion is already in progress.

4–2

A/Da[2~0]

A/D conversion target channel. Thes e bits determine which inputs to the ADC are to be converted.

5

GATEOUT

Assertion puts VB

on the GATEOUT pin. Dea ssertion connects the GATEOUT pin to ground.

7–6

Bdcb, Bdca

Motor driver B direction bits. Outputs follow these bits

,

regardless of the PWM value, when they are equal (i.e., 00 or 11).

9–8

Adcb, Adca

Motor driver A direction bits. Output s follow these bits, regardless of the PWM value, when they are equal (i.e., 00 or 11).

11–10 A/Cdcb, *A/Cdca

(Note 26)

Motor driver C direction bits. Outputs fo llow these bits, regardless of the PWM value, when they are equal (i.e., 00 or 11).

13–10

A, *A, B, *B ,

(Note 27)

15–14

OUT2, OUT1

Inverted step motor outputs. The corresponding output is on when the bit is asserted.

High-side or low-side output control. Bit 4 of the Configuration mode input frame determines which output is
controlled. The output turns on when the corresponding bit is asserted.

Figure 3—

Be careful here because the A and B motor direction bits are swapped. I’m still trying to figure out the logic in that.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

65

must send 0x0080 to the MC34921 to
drive the DC motor attached to motor
driver A clockwise. Listing 2 shows
how it’s done.

The command must be sent MSB first

following the lowering of the CE signal.
The MC34921 latches in the motor con-
trol frame 16 SCLKs after the CE line
goes low. If you have a PWM signal
flowing from the ATmega16 to the
MC34921 APWM pin, the small Radio
Shack motor will spin in a clockwise
direction at a speed dictated by the duty
cycle of your PWM signal. Making the
motor direction bits equal stops the
motor. So, writing a 0x00C0 or 0x0000
to the MC34921 will stop the DC motor
being driven by motor driver A.

To move the motor in a counter-

clockwise direction, all you have to
do is send 0x0040 to the MC34921.
Listing 3 shows you just how easy it is
to move the motor clockwise, stop it,
and then move it counterclockwise.

MOTORING WITH MOTOROLA

By the way, the morning after Mark

found a shorted filter capacitor across

My first motor driver mistake was to
ignore the importance of getting the
MC34921 successfully out of reset.
The trick is to be patient and watch
the clock (i.e., SCLK). The SPI SCLK
signal is used by the MC34921 to
time the reset process after the 5- and
3.3-VDC voltage regulators have
come online. Note that 128 SCLKs
are needed to assure that the reset
process has completed, which results

in the RST line being driven high.

The ATmega16 generates the SPI

SCLKs. Simply taking the SCLK line
high and then back low affects an SCLK
cycle. The MC34921’s SPI interface
operates at extremely high speeds.
This makes it easy to meet the tiny
setup and hold times using your bit-
bang SPI interface.

After you are sure that the

MC34921 has left the reset state, you

Listing 1—

The code wakes up the AVR PWM subsystem and feeds PWM signals out of the AVR OC1A

and OC1B pins. You can get the rest of the firmware story by downloading the sample MC34921 driver
code from the Circuit Cellar ftp site.

void timer1_init(void)

{

TCCR1B = 0x00; //Stop

TCNT1H = 0x00;

TCNT1L = 0x00;

OCR1AH = 0x01;

OCR1AL = 0x7F;

OCR1BH = 0x00;

OCR1BL = 0x7F;

ICR1H = 0x03;

ICR1L = 0xff;

TCCR1A = 0xA0;

TCCR1B = 0x11; //Start timer

}

background image
background image

www.circuitcellar.com

Issue 166 May 2004

67

the MC34921, you can build that
$4.95 Mars rover yourself.

Visit the Circuit Cellar ftp site for a

copy of the MC34921 development
board PCB layout. Note that the PCB
layout is in ExpressPCB format, which

CIRCUIT CELLAR

®

the z-axis Gecko’s power lines, he
replaced it, and the CNC ran flawless-
ly with the new Basic Stamp program.
It’s all good news with the Motorola
MC34921 development board as well.
Now that you know your way around

Listing 3—

Moving motors with the MC34921 is as easy as stuffing some bits into the motor control frame

in Figure 3, waking up the AVR PWM generator as shown in Listing 1, and delivering the command with
the code in Listing 2.

motoframe = 0x0000;

while(1){

send_frame(motoframe | A_CW);

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

{

for(y=0;y<0x7F;++y){}

}

send_frame(motoframe | A_STOP);

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

{

for(y=0;y<0x7F;++y){}

}

send_frame(motoframe | A_CCW);

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

{

for(y=0;y<0x7F;++y){}

}

send_frame(motoframe | A_STOP);

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

{

for(y=0;y<0x7F;++y){}

}

}

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 code and PCB
layout, go to ftp.circuitcellar.com/
pub/Circuit_Cellar/2004/166.

RESOURCES

Atmel Corp., “AVR320: Software
SPI Master,” 1108A, 1998.

Motorola, Inc., “Power System
Control IC (Preliminary Infor-
mation),” MC34921/D, June 2003.

means you can submit it as is to
ExpressPCB to get my version of the
MC34921 board, or you can alter it
and submit it to have your own cus-
tom MC34921 board manufactured.
After you have your MC34921 devel-
opment board assembled and fired up,
download the AVR ATmega16 code to
exercise that set of Radio Shack
motors you just bought.

I

SOURCES

HEDS-9710/9711 Encoder
Agilent Technologies
(650) 752-5000
www.agilent.com

ATmega16 Microcontroller and
AVR JTAG ICE
Atmel Corp.
(408) 441-0311
www.atmel.com

MC34921 Development board PCB
ExpressPCB
www.expresspcb.com

MC34921

Motorola Semiconductor, Inc.
(847) 576-5000
www.motorola.com

SPP233ECT RS-232 Converter IC
Sipex Corp.
(408) 934-7500
www.sipex.com

Listing 2—

This is really just a modified SPI driver routine. The data must be 16 bits in length and sent

MSB first. I used a simple mask-then-shift algorithm to flip the bits out of the AVR user-assigned MOSI pin.

void send_frame(unsigned int frame)

{

unsigned char x;

clr_sclk_pin;

spi_mask = 0x8000;

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

//Ensure reset condition

{

set_sclk_pin;

nop;

clr_sclk_pin;

}

set_sclk_pin;

nop;

clr_ce_pin;

clr_sclk_pin;

do{

clr_mosi_pin;

if(spi_mask & frame)

set_mosi_pin;

set_sclk_pin;

nop;

clr_sclk_pin;

spi_mask /=2;

}while(spi_mask);

set_ce_pin;

}

background image

68

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

M

any of you will say they were

too young, that they were struck
down in the prime of their lives. What
a shame, you’ll say. They hadn’t even
reached the age of 50.

Are serial and parallel ports dead? I

believe that nothing can really die
unless it’s forgotten. All of us have fami-
ly and friends who have passed on, but
we keep them alive by sporting their
pictures on our walls, visiting gravesites,
talking about them, and memorializing
them in various public and private ways.

I remember the rumblings that TV

would kill radio. (I can’t imagine riding in
my car without tunes.) But today’s tech-
nology continues to assure radio’s success
via satellite. Although my kid’s kids prob-
ably won’t even know what serial and
parallel ports are, that’s at least a decade
away. Although it’s getting tougher to
foresee what the future holds, I doubt that
they will totally disappear anytime soon.
It’s more likely that they will become
obsolete because of nonsupport in much
the same way DOS has been neglected
(although still used by some).

“If it ain’t broke, don’t fix it.” I’m a

big believer in that statement. But I also
understand that much of the world
economy’s growth is based on the
development of new technology and the
harnessing of its potential. If we stand
still, we run the risk of falling behind.
Do you want to run that risk?

BECOME A USB CONVERT

If you aren’t convinced that you need

USB after last month’s column, you’re
standing still. Last time, I briefly dis-
cussed the reasons for the development
of USB and how you can benefit from its

ing a new processor for your design.

HARDWARE CHANGES

The most visually dramatic changes

to a project are physical ones. The area
needed for a USB interface is consider-
ably less than that of serial and parallel
ports. Besides the connector size shrink-
ing to about 25% of a DB25, only a few
discrete parts are needed instead of level
shifters or buffers. You can free up a few
square inches of real estate on your PCB.
Furthermore, you can really luck out if
the manufacturer of your microcontroller
makes a version with a USB peripheral.
More and more manufacturers are jump-
ing on this bandwagon. If not, you may
be able to add a USB interface chip (e.g.,
the Philips ISP110x) to your micro,
assuming it has the horsepower and
buffers to support all of the necessary
USB functions. The great part about
using a micro integrated with USB is that
all the low-level stuff is done for you.

USB hardware handles detecting and

decoding incoming packets. It determines
which transactions to ignore (no match-
ing address) and which to react to, flag-
ging the type for endpoint 0. Incoming
data is stored in the appropriate buffer or
flagged as an error. The number of bytes
received and the data-toggle state is
stored. The hardware calculates and com-
pares CRC values, and takes the appro-
priate action on errors. It automatically
sends any necessary handshaking to the
host and triggers an interrupt for the
firmware to take action. Outgoing data is
encoded for transmission along with the
byte count and data-toggle code.

The hardware also calculates a CRC

and appends it to the data packet. After

USB in Embedded Design (Part 2)

FROM THE BENCH by Jeff

Bachiochi

implementation. You observed the phys-
ical attributes of the USB connection
and how a USB device makes itself
known to the host through enumera-
tion. Furthermore, I explained how
tiered interconnections allow the host
to communicate with each USB device
on a one-to-one basis using data packets
stuffed into 1-ms frames. I also intro-
duced a previously designed X10 project.

X10 uses the AC power lines in your

home to transmit control codes to spe-
cially designed outlets that respond to
the codes. X10 codes can turn on and
off appliance modules (relay-based).
They also turn on and off—as well as
dim and brighten—lamp modules
(triac-based). These modules can be
purchased in an AC outlet form factor
or as plug-in modules.

The project consists of a serially con-

nected dongle, which translates serial
X10 commands into the appropriate con-
trol signals to drive a TW523 isolated
power line interface. A PC application
feeds user-selected X10 commands, as
TX serial data, to the dongle while mon-
itoring the RX serial input for X10 com-
mands received from the power line.

Any X10 command can be sent by

transferring 3 bytes (HouseCode,
UnitFunctionCode, and RepeatCode) to
the dongle over the serial interface. An
X10 command seen by the TW523 on
the power line is returned to the appli-
cation by the dongle transferring 2 bytes
(HouseCode and UnitFunctionCode)
back via the serial interface.

To replace the serial interface with a

USB equivalent requires hardware and
software design changes. These changes,
which are not minor, may require choos-

Jeff makes converting to USB an attractive option with HIDmaker, a highly efficient program
that does all the work for you. Creating USB software has never been easier.

HIDmaker Converts an Application

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

69

may be used to sending data
whenever necessary to the
application. Under USB rules,
the host must ask for data
before a device can send it.
You’re in trouble unless you
have the resources to hold the
data until it’s asked for.

Last month I covered the

designed data throughput of
USB. Now is a good time to
cover the four types of trans-
fers (control, interrupt, bulk,
and isochronous) because each has
different throughputs (see Table 1).

The all-important enumeration

process is handled with control trans-
fers. The host allocates between 10%
and 20% of a frame to control transfers.
Although all enumeration begins with
endpoint 0, control transfers are not
limited to endpoint 0 or enumeration.
A control transfer can be used at any
time as defined by any class (or vendor).

Don’t be fooled by its name, the

interrupt-type transfer does not cause
an interrupt; instead, it is guaranteed to
occur within a certain amount of time
(more like interrupt latency). The inter-
rupt transfer is used where you don’t
want to miss a key press, mouse move,
or any other real-time interaction
event. (The Windows predefined HID
driver supports this mode.) This type of
transfer also requires separate in and
out pipes for data. Although attempts
by the host are guaranteed, it’s up to
the device to be ready and to ensure
any throughput. The latency time is
defined in the device’s descriptor table.

Bulk transfers are similar to inter-

rupt transfers, except there is no guar-
antee on when the data will start or
finish. They are plugged into frames
whenever there is room. This type of
transfer also requires separate in and
out pipes for data. With no USB traf-
fic, a bulk transfer can fill the full
frame. However, if other USB transfers
fill the frames, a bulk transmission is
held off. Bulk transfers are generally
limited to functions that aren’t time
critical (e.g., printing and file transfers).

The isochronous transfer is similar to

an interrupt transfer in that there is a
guarantee. Here the isochronous trans-
fer requests a specific bandwidth. The
host must calculate what bandwidth it

has to offer before it can accept and
configure an isochronous pipe. Success
depends on which other devices are
already on the bus. This type of transfer
also requires separate in and out pipes
for data. You can see that allocating
bandwidth ensures the data gets there;
however, there is no plan for resending
corrupted data. Therefore, this type of
transfer is used where the application
can tolerate small errors (streaming
audio). The bandwidth requirements are
defined in the device’s descriptor table.

DEVICE CLASSES

If you could gather all the USB

devices out there (as well as those that
haven’t been designed yet) and separate
them into groups with similar charac-
teristics, you could define classes of
devices, which would include the fol-
lowing: the HUB device, audio device,
chip/smartcard interface device, com-
munication device, content security
device, device firmware upgrade,
human interface device (HID), IrDA
bridge, mass storage, printer, and imag-
ing. The list is continually growing.

As you can imagine, generic drivers

don’t hack it for most peripherals. There
is the necessity for special drivers to be
written to handle each of these devices,
even those within the same class. After
the host has received a device descriptor
table through enumeration, it can search
its .INF (or other files) for a matching
class and device driver. If necessary,
the host asks you for the appropriate
drivers. (That’s if the device is new to
the system.)

Windows has a generic driver for

the HID class. (Try searching for hid-
dev.inf; it can be viewed with
Notepad.) Because HIDs have a gener-
ic class driver, designers can make

receiving a handshake from the host,
it triggers an interrupt for the firmware
to take action. I’m sure you’ll concede
that this functioning is something to
be avoided if possible. You can side-
step this entirely by designing with a
microcontroller that has USB support.

SOFTWARE CHANGES

Data transmission via a serial port

requires the conversion of data through
hardware or software into asynchro-
nous or synchronous bitstreams. The
two devices are configured for the same
data format so that what goes in one
end comes out the other end. They
may use hardware, software, or no flow
control. These factors must be agreed
to prior to any communication; for the
most part, they cannot be identified
through the connection itself.

Data transmission via parallel ports

moves data in byte-sized transfers using
eight parallel data paths. Although poten-
tially 10 times faster than serial, hard-
ware handshaking is done on a byte-by-
byte basis, which slows everything down.

The original parallel port is unidirec-

tional and—discounting the 5 bits of
status inputs, which are often used for
inputting nibble data—is not meant to
be a bidirectional device. This led to the
bidirectional port (SPP), the enhanced
parallel port (EPP) for speedier nonprint-
er devices, and the extended capabilities
port (ECP) for speedier printing devices.
Which do you have? Truth be told,
unless you are using an older system,
you probably have support for all of
them, but it is still half-duplex.

Although similar to synchronous seri-

al, a USB host can obtain everything it
needs to know about a device through
the connection. Therefore, you don’t have
to know anything about a device just to
make a connection to it. It’s easy for you
(as a user), but tough on the designer.

A special device descriptor is the

key to each device. This is the biggest
stumbling block for a designer. The
hardware handles much of the work.
For the most part, after putting
together the device descriptors, it is
simply a mater of managing your data
in and out of the endpoint buffers.

Handling this data takes some

thought, however, particularly because
of the way USB operates. Your project

Table 1—

A wide range of throughput is available depending on

the bus speed and transfer type that you select for your design.
Note that bulk and isochronous types can’t be used with the low-
speed bus interface.

Transfer

Maximum data transfer rate per endpoint

type

(KB/s) (data payload/transfer = maximum
packet size for the speed)

Low speed

Full speed

High speed

Control

24

832

15,872

Interrupt

0.8

64

24,576

Bulk

N/A

1216

53,248

Isochronous N/A

1023

24,576

background image

70

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

their lives less complicated
by trying to design for this
class.

HUMAN INTERFACE
DEVICE

As its name suggests, a

HID has to do with devices
that interact with you. This
covers numerous input and
output devices (e.g., key-
board, mouse, steering
wheel, rumble pack, and joy-
stick). Many monitors have
an embedded HID device,
which is used for screen
configuration rather than
video. In actuality, a device
does not need to interface
with you to be a HID. If your device’s
data requirement fits within the HID
class’s specifications, you’re golden.

My conversion project fits within

this specification. I needed to be able
to transfer 3 bytes out of the PC to
the interface or 2 bytes into the PC
from the interface.

X10 transmissions are slow because

they are based on 60-Hz zero-crossings.
X10 commands require about 0.5 s
(22 60-Hz cycles) to be completed on
the power line, so you don’t need to be
worried about exceeding available
frame times. As far as sending data
from the PC, the interface is designed
to transmit an acknowledgement of
received data (loop back); therefore,
loss of data because the interface is
busy is handled by the host application
expecting looped-back data.

On the interface side, I

had to create the appropriate
descriptor tables and change
the interface application
code to make use of the
USB hardware in the micro.
Assuming the generic HID
driver is usable on the host
(PC), I had to change the
data exchange routines in
the application from serial
to USB.

HIDmaker

Trace Systems looked into

the future and built a prod-
uct to get you up and run-
ning quickly with USB.

ufacturers to follow.) It’s a
perfect fit for this project
because I originally used a
PIC (and PicBasic) for the
device and Visual Basic for
the application.

Photo 1 shows the opening

HIDmaker screen. The pro-
gram is set up in the familiar
Wizard style. After you add
the required information to
each page, click the Next
button to move on. You can
save the project file and exit
any page. Loading the project
file brings you back to where
you left off.

To begin the HIDmaker

process, select a device type.

This tells HIDmaker how complicated
your new device is. The device in this
project is simple. More complex
devices have multiple, independent
types of functionality (a combination
keyboard/mouse).

On the second page, you name your

project and select a location for the
files that HIDmaker will produce. You
also add information like the vendor ID
and project ID, which are required by
Windows to identify your device. Any
device sold commercially must have a
vendor ID from USB Implementers
Forum.

Notice the various boxes labeled

“Use in F/W.” If checked, the optional
information can be placed in device
firmware by HIDmaker to be discov-
ered through enumeration by the host.

HIDmaker offers two

types of help. The “I need
more help...” button pro-
vides context-sensitive help
for using the controls that
are currently visible on the
screen. The USB Advisor
button gives advice about
appropriate inputs, what the
inputs mean, and how they
relate to the process.

The third page gets down

to the nitty-gritty. I’ve
already indicated that this
is a normal device. As such,
it has a single configura-
tion. As you can see in
Photo 2, most entries
already have selections;

HIDmaker was designed for use with
the HID class, so no device driver pro-
gramming is required. You get all the
benefits of USB with less work than
RS-232 serial because it does the hard
work for you!

HIDmaker creates two documented

programs—one for the PC and one for
your microprocessor—that already
communicate with each other using
USB. The programs, which are built
around the data that you describe, are
written for Microchip USB PICs in
your choice of environments: PicBasic
Pro, Microchip MPASM, CCS C, or Hi-
Tech PICC. On the PC side, HIDmaker
supports Visual Basic 6, Delphi, and
C++ Builder. (These environments are
the first to be supported by HIDmaker
with other microcontrollers and man-

Photo 2—

Most projects can use the normal device selection. They need a single

interface defined. Complex devices require you to define an interface scheme for
each configuration.

Photo 1—

HIDmaker simultaneously generates programs for the peripheral device

and the PC. The programs can communicate with each other over the USB via the
HID class. Even complex interfaces can be modeled with HIDmaker.

background image
background image

72

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

these are the most common usages,
but alternatives can be selected.

If you want the USB interface to sup-

ply power to the device, you must also
indicate the device’s current consump-
tion. Because the total current avail-
able through the USB interface is limit-
ed, the host uses this value during enu-
meration to determine if there is avail-
able current to allocate to the device.

As you know, low-speed devices are

limited to two kinds of transfer types,
control and interrupt. I chose to use
interrupt transfers to ensure periodic
transfers. Because I need data to go in
both directions, I choose EndPoint1 IN
and EndPoint1 OUT. The host creates
separate pipes (virtual connections)
between it and the device endpoints
based on this information. Note that
you also get to indicate how often you
want each transfer to take place.

Only one more bit of information

must be defined: the data that will be
transferred. Clicking on the Define Data
button brings up the fourth and final
page (see Photo 3). The data for this
project consists of three values going to
the device (using out endpoint 1) and
two values going to the PC (using in
endpoint 1). This page has three buttons
on the left and a large drawing area. Use
this page to create data items—one for
each variable used in each pipe.

The two lower icons on the left—

Physical Collection and Logical
Collection—help you indicate which
data items are grouped together. They
can be placed in the drawing area as
placemats for the data items. For
instance, you may want to use two
Logical Collection placemats, one for
the three out data items and one for
the two in data items. These don’t

actually affect how the
data will be defined;
they merely aid in doc-
umentation. For each
item of data, click the
Data Item button and
place an icon in the
drawing area. Now all
that’s left is to define
each item.

When the mouse hov-

ers over a data item, a
pop-up shows a descrip-
tion of the item’s con-

figuration. By double-clicking on the
item, you’ll see that data item’s
editable properties (see Photo 4). I
changed each data item’s name to the
variable name I use in the applications
(again, to help with documentation).

The data type must be selected based

on the endpoint, either input or out-
put, for this project. The usage info
consists of a combination of two num-
bers: a Usage Page number and a Usage
ID number, which is the number of an
item in the Usage Page. A Usage ID
represents some particular function or
feature of a device, and the Usage Page
is a collection of Usage IDs that belong
in the same category. The HID usage
table’s specification defines and docu-
ments nearly 1600 combinations of
Usage Page and Usage ID. Click the
Browse Usages button to pick from a
list of all the standard usages that were
recently defined as well as a modest
number of Vendor Defined usages.

It is important that every data item

you define has a distinct Usage ID;
this is the only way that the HID
class, as implemented by the
Microsoft Windows HID API, can
identify and locate
your data items. I
chose to use the ven-
dor-specific User Page
(0xFF, the default) and
User ID’s 0x00–0x04
for the five data items.
Notice that you can
define the maximum
and minimum values
for each data item.
This, in turn, deter-
mines the number of
bits necessary to define
your item.

My HouseCodeIn/Out items require

8 bits. The UnitFunctionCodeIn/Out
and RepeatOut items only require
5 bits each. (The transferred USB data
packet contains data items packed
together to save every bit possible.)

Although this project is fairly sim-

ple and the default values are used in
most cases, you can see that the data
properties offered are both flexible and
complex. HIDmaker’s guidance isn’t
fully appreciated until you look at the
output generated by compiling and
building sample applications based on
all the input that you complete.

HIDmaker DEVICE OUTPUT

After you have fully defined your

device, its data, and its interface,
HIDmaker can work its magic. Select
the environments that you want
HIDmaker to generate output for (I
used PicBasic Pro and Visual Basic),
and in seconds you’ll receive a list of
all the output files for both the periph-
eral and the host. You can peruse the
files before exiting HIDmaker. You
may download the files from the
Circuit Cellar

ftp site.

On the peripheral side, HIDmaker

generates two main files (nine files in all
for this project). First, descript.asm holds
all of the descriptor tables defined from
the information entered in HIDmaker.
Then there is USBX10_M.bas, which is
this project’s PicBasic Pro application
file. The following four files are project-
independent. Three Microchip files—
usb_ch9.asm, usb_defs.inc, and hid-
class.asm—support the PIC USB parts.
One file, usbdesc.asm, lists a number of
include files specific to PicBasic Pro.

The descript.asm file, which is cer-

Photo 3—

Data items can be placed in logical or physical collections.

Collections aid in understanding how the data items are used but do not
affect how the data is actually handled.

Photo 4—

Although each data item must be fully defined, many default selec-

tions can be used. Take some time to make sure your data will be handled
with the respect it deserves.

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

75

tainly the most important, contains
all of the tables the host reads during
enumeration to gain the ultimate
knowledge of your device. For this par-
ticular project, it contains a device
descriptor table, configuration descrip-
tor, interface descriptor, HID descriptor,
endpoint descriptor (for EndPoint1In),
endpoint descriptor (for EndPoint1Out),
and report descriptor. That’s not to
mention the string descriptors as
defined in HIDmaker (e.g., language ID,
manufacturer, product name, serial
number, and other option strings).

Using Microchip’s IDE and PicBasic

Pro, I compiled the project files into a
hex file, which is used to program a
PIC16C745. Let’s take a quick look at
what HIDmaker built for this simple
application.

HIDmaker creates a USB interface

capable of moving defined data. In this
case it does this by setting up an appli-
cation to pass three data items from
the host and collect two data items
from the device using a USB connec-
tion. After some initialization, the
application proceeds to a main loop
where the

USBIN command checks to

see if there is any out endpoint 1 data
available. If so, it retrieves and unpacks
the data. Otherwise, it goes on.

In the second part of the loop, the

out endpoint 1 data items are set to
test values (initially defined in the
define data section of HIDmaker), and

a flag is set to indicate
that data is ready to send.
The data is packetized
and the

USBOUT com-

mand is executed, which
sends the data to the USB
in endpoint 1 buffer if it
is free. (Otherwise, it
tries again.) Then it’s
back to the main loop.

Notice that this application passes

data but there is no apparent check on
the data. This could be easily modi-
fied in this case so that the data that
comes in is used for the data that goes
out. But this is not necessary because
there are ways to see the data inside
the PIC. At this point, if everything
was done correctly, the PIC with the
necessary USB circuitry will enumer-
ate when it’s plugged into a USB port
on the PC (see Figure 1).

HIDmaker HOST OUTPUT

On the host side, HIDmaker creates

three main files and a bevy of support
files (11 files in all for this project).
USBX10_M.frm is the main program
module. Adding this form to a project
enables the HIDagentX object, which
is used for a USB interface. It is simi-
lar to using an MSComm object for a
serial interface.

The USBX10_L.cls class module

library file handles the variables and
functions that make direct interfacing

with the HID system calls unnec-
essary. The OneHidVar.cls class
module file represents one USB
HID data item or variable with all
its attributes. Additional modules
are created by HIDmaker,
PC_Consts.bas (a file of expected
device strings) plus error checking,
and context help support files.

You can create a project .EXE file

for the HIDmaker-created applica-
tion using Visual Basic IDE, or you
can run it in Debug mode from the
IDE. Photo 5 gives you a quick pic-
ture of what is going on. The appli-
cation will not run if it doesn’t find
a matching device enumerated on
the USB bus. Assuming it does, the
application pops up a window and

shows that it has found a device.
You can use the Send All Reports
and Read All Reports buttons to

test the communication to and from
the attached device. The transferred
data, which is hard coded into both
applications (the host PC and the
device microcontroller), originates from
the HIDmaker define data steps.

Unless you can see into the microcon-

troller, you won’t know if the correct
data has arrived. However, you will see
the data arriving from the device dis-
played in the host application program.
At that point HIDmaker has proven its
success. You can take these applications
and integrate them with your own code.
But wait, HIDmaker is still of use.

OPTIONAL TOOLS

Remember how I said that you

couldn’t see inside the micro? Well, if
Microchip had its act together, they
would have the USB devices available
in flash memory and the ICD in-cir-
cuit debugger could be used to look at
the microcontroller’s registers.

Trace Systems has added hooks

within its code to allow messages to
be output through a serial port on the
microcontroller. (Isn’t it ironic to use a
serial port to debug its replacement?)
You can use this technique to log mes-
sages (including any values) at any
point in the application, so you can
see the values received from the appli-
cation. In fact, if for some reason your
device doesn’t enumerate correctly,
this can provide you with feedback
about the failure’s location.

Enumeration failure can be the

biggest source of headaches for a
designer. Although HIDmaker gener-
ates working code for you, if enumera-
tion fails, HIDmaker offers suggestions
about potential problems.

USBwatch is a terminal-style applica-

tion that interprets tokens sent by the
microcontroller out of the debugging
serial port. Tokens are used to reduce
serial traffic to a minimum. The

Figure 1—

The PIC16C745 microcontroller has USB support

for version 1.1. The interface is simple and can be powered
from the USB bus. The microcontroller can apply an internal
phase-locked loop to operate at 24 MHz using an external
6-MHz crystal.

Photo 5—

HIDmaker creates device and PC applications that complement

one another. Here the PC application demonstrates that it has succeeded
in providing a working USB connection by allowing you to pass your
defined data to and from the PC.

background image

76

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

USBwatch application expands the
tokens back into real English text. Note
that there are a number of indicators
above the text window in Photo 6. These
help determine the status of enumera-
tion and the present endpoint in use.

From the PC side, you can investi-

gate all USB devices using the
AnyHID application, which shows all
of the USB devices (except hubs and
the system’s keyboard and mouse).
When you choose a
device, AnyHID will tell
you all about it by read-
ing the descriptor tables
from the selected device
(see Photo 7). Because
the descriptors contain
information about each
data item, AnyHID is
presents you with the
opportunity to configure
a data packet to send to
the device and to receive
and interpret requested
data.

TIME TO CONVERT

HIDmaker’s micro-

processor test applica-
tion code is well docu-
mented and uses embed-
ded comments to sug-
gest where you might
add your application

code. PicBasic’s

USBIn1 com-

mand retrieves any received
USB output data packet
while HIDmaker’s code
unpacks the data and sets
the HandleEp1Rcv flag when
data is available to you from
the host. In a similar fashion,
you set the EP1XmtDataReady
flag when you have data to
send to the host. HIDmaker’s
code packs your data and uses
the PicBasic

USBOut1 com-

mand to send USB packets to
the host when it requests data.

On the PC side, I opened

my serial-based application in

Visual Basic. All of the mod-
ules and class modules that
HIDmaker created for the
test application are added to
the project. The MSComm
object on my main form

(Form1) was replaced with the
HIDAgentX object. The
FRMPROPS.FRM form was deleted
because this is the MSComm popup
form that allows you to set the serial
port properties. The project was saved
as USBX10.

Next, the code in the USBX10_M.frm

form that produced the test applica-
tion form had to be eliminated or the
necessary code had to be copied from

the USBX10_M.frm form to Form1. I
chose the latter.

Gone are four routines that deal with

the serial port, opening and closing the
serial port, and sending characters to
and getting characters from MSComm.
In their place HIDagent’s routines
become the low-level engine that does
all the hard work of opening HID
devices, accessing HID data items, and
packing and unpacking reports. After
HIDagent has detected, identified, and
bound itself to an enumerated device,
its runtime events become accessible.

The

Sub ReadRpts() routine peri-

odically transfers data items from an
input report. I placed code within this
routine to test for new data, manipu-
late it, and perform an update on the
form using the received X10 command
(new data). To send an X10 command, I
used the

CmdSendX10_Click() event

to assign values to the data items
before requesting a

WriteAllReports.

SALVATION AT LAST

The finished application shows little

sign of change (see Photo 8). Two areas
of concern popped up while using
HIDmaker to help convert the applica-
tion. First, thanks to Microsoft’s wis-
dom, all data is treated as signed unless
specifically told not to. This results in a
popup asking if this should be ignored

each time the program is
executed. The Windows
routine is avoided by set-
ting the Scale mode to a
value of one (unscaled
conversion only) in the
OneHidVar.cls class
module file.

The second area has

to do with the way I
designed the USB device.
USB likes to have data
available from a device
at all times. This can
cause a problem for your
application if you have
new data that is the
same as the old. If it is
the same, how will the
application determine if
the data from the device
is old or new? Instead of
adding complexity using
some kind of flag

Photo 6—

The USBwatch interpreter works in conjunction with a

serial port on the microcontroller. Embedded commands allow you
to see what’s happening inside the microcontroller. You determine
the information reported by enabling the hooks within the
HIDmaker-generated code.

Photo 7—

AnyHID is a peephole into USB devices enumerated by your PC. You can interrogate

each device and actually send and receive data to and from the device.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

77

exchange, I don’t provide data to the
USB port unless it is new. So, most of
the time when the host asks for data,
the device will not answer and the host
will timeout after a default (default =
5000, 5 s). This causes some rather
nasty application lags during periods
of no new data (most of the time).
Shortening the USB timeout property to
100 ms in the

CreateHidObjects

routine eliminated it.

Using USB for I/O is no longer as

easy as writing to a port. To become a
user-friendly interface, USB has made
the designer’s job extremely complicat-
ed. Luckily, manufacturers are realiz-
ing they need to help reduce the bur-
den. Trace Systems’s package shortens
the learning curve. HIDmaker, along
with its optional tools AnyHID and
USBwatch, provides the support need-
ed to make USB come alive for the
designer. Trace Systems knows what
you need, and it supplies plenty of sup-
port documentation like the USB, HID

class, and usage table specifications.

I

Photo 8—

With the conversion now complete, the Visual

Basic application originally written using a serial port
interface operates using the new USB interface. Your
customer may never notice the difference.

SOURCES

PIC16C745 Microcontroller with
built-in USB support
Microchip Technology, Inc.
(480) 792-7200
www.microchip.com

PicBasic Pro

microEngineering Labs
(719) 520-5323
www.melabs.com

HIDmaker

Trace Systems Inc.

www.tracesystemsinc.com

TW523 X10 two-way interface
www.X10.com

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

Circuit

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

PROJECT FILES

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

RESOURCES

J. Axelson, USB Complete:
Everything You Need to Develop
Custom USB Peripherals

, 2nd ed.,

Lakeview Research, Madison, WI,
2001.

USB Implementers Forum,
www.usb.org.

background image

78

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

’d like to start out this month by con-

gratulating the folks at NASA and every-
one else involved in the missions to Mars.
As I write this column, both the Spirit
and Opportunity rovers have successfully
landed and are starting to explore the
surface of the red planet.

A mission to Mars calls for embedded

engineering above and beyond the call
of duty. Simply getting to the surface of
the planet in one piece is nontrivial,
as more than a few failed attempts
have demonstrated. Consider all the
stuff that must go perfectly right, and
all that can go so easily wrong, starting
with the launch itself. Presuming the
thing doesn’t just go up like a firecrack-
er and actually makes it off the pad, the
reward is a rover-rattling ride courtesy
of close to 1 million pounds of thrust.

Once safely free of Earthly bonds, the

spacecraft enters a lonely seven-month
cruise phase. Sounds easy enough, until
you consider the distance to travel,
some 300 million miles, and the zero
tolerance for navigation errors that
have doomed past missions. But the
fun really starts with the landing phase.
The NASA folks have a better name
for it, “six minutes of terror.”

Diving toward the surface at 12,000

mph, even the thin atmosphere of Mars
makes for a sweaty brow onboard, and no
doubt in mission control, with fate riding
on a heat shield’s ability to protect the
fragile innards from the blazing tempera-
ture of reentry. After a dicey 4 min. of
playing meteor, the spacecraft—now trav-
eling at “just” 1000 mph—deploys a
supersonic-capable parachute.

Now comes the fun part. Seconds

ture sensing remains an extremely
important task that many embedded
designers must deal with at some
point in their careers. This month I
thought I’d review the mainstream tech-
niques as well as some that are a little
out of the ordinary. But first let’s cover
some basics, starting with the question,
Just what the heck is temperature? To
answer that, a little history lesson is in
order. Along the way, you’ll encounter
some no doubt familiar names.

Of course, the ancient origins of the

temperature sensing subject go back
as far as fire and water. It’s no surprise
that the concepts and nomenclature
we use today still revolve around pri-
mordial facts of life such as the freez-
ing and boiling point of water.

The modern era of temperature

sensing started with the seventeenth-
century thermoscope, which relied on
the change in gas pressure associated
with a change in temperature to draw
liquid up a scaled tube. (Imagine suck-
ing on a straw.) Rumor has it that
Galileo (1564–1642) used wine as the
thermal medium, a fitting precursor
for subsequent spirit thermometers
that used dyed alcohol.

Then in 1724, Gabriel Fahrenheit

(1686–1736) experimented with mercury,
which has a number of advantages
including its visibility, large and uniform
thermal expansion, a wide temperature
range (it remains liquid between –39°
and 357°C), and the simple fact that it
doesn’t stick to the glass. Witness to
simpler times is the way Fahrenheit cali-
brated his temperature scale. A mixture
of sea salt, ice, and water was defined as

The Heat Is On

SILICON UPDATE

by Tom Cantrell

before impact, giant airbags inflate to
cushion the craft for a landing more akin
to a car crash. At the last moment, small
retro rockets fire—a final stab at the
brakes if you will. Hopefully it all works,
because at 40

above the surface the rover

cuts the cord and then it’s look out
below. At this point, luck—or bad luck,
as in big pointy rocks—plays a role as the
lander slams into the surface at 50-plus
mph. Eventually bouncing to a stop, the
craft still has the nontrivial task of right-
ing itself and going through a reverse
origami-like unfolding of solar panels,
cameras, and communications antennas
before taking its inaugural joyride.

RED DAWN

The challenge of thermal manage-

ment takes on new meaning on the
red planet. I recently heard on the
news that residents in the Northeast
have been suffering through a record-
breaking cold snap. Don’t feel bad,
folks, your record lows are about the
same as noon on a hot summer day at
the “subtropical” Mars landing site.
Meanwhile, nighttime on Mars gets
chilly indeed. The solar-powered rover
tucks in for the night when tempera-
tures fall below –100°F!

The Spirit rover is outfitted with a

myriad of temperature sensors, both
external (e.g., in the cameras) and
internal. The latter are installed in the
aptly named warm electronics box
(WEB) that houses the brain (a VME-
bus RISC setup) that handles every-
thing from communication to naviga-
tion and science experiments.

Whether on Earth or Mars, tempera-

Whether you’re building the next Mars rover or a small fire-detecting unit for a robotics con-
test, you can never know too much about temperature-sensing technology. Tom surveys the
various techniques you can use to bring temperature-sensing capability to your designs.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

79

0°, while the “heat of a healthy
man” was set at 96°. However,
the discovery that it is extremely
toxic, as well as the emergence
of better alternatives, has practi-
cally put an end to mercury’s
thermometer aspirations.

Meanwhile, folks like Anders

Celsius (1701–1744) and others
had an even better idea, namely
just to define freezing as 0° and
boiling as 100° (i.e., a centigrade
scale). However, although
“Celsius” and “centigrade” are often
used interchangeably, “degrees C”
means Celsius in modern usage (since
1948). In fact, it’s slightly different
from centigrade (e.g., water boils at
99.975°C).

Later, in the eighteenth and nine-

teenth centuries, interest shifted back
to gas thermometers. This was fueled
by the discovery that different gases
appeared to have the same tempera-
ture expansion coefficient and exhibit-
ed an extremely predictable “ideal
gas” relationship between pressure,
volume, and temperature.

From this thermodynamic perspec-

tive, absolute zero is defined as the tem-
perature at which an ideal gas has zero
pressure. However, every scale needs a
second calibration point to determine
the slope. In 1933 the international sci-
entific community came together and
deemed the freezing point of water
(more correctly the “triple point,”
which is the temperature at which ice,
water, and water vapor are in thermal
equilibrium) as 273.16 kelvins, which
is named after Lord William Thomson
Kelvin (1824–1907).

Absolute zero is an interesting con-

cept. Another way of looking at it
(“kinetics” or “molecular dynamics”)
is that 0K is the temperature at which

atomic motion (the source of heat) ceas-
es. Like the speed of light, 0K is some-
thing that presumably can’t be reached.

But researchers—including 2001

Nobel Prize winners Eric Cornell,
Wolfgang Ketterle, and Carl Wieman—
have gotten darn close with tricks such
as using lasers and magnetic fields to
manhandle matter into submission (i.e.,
slowing atomic motion). At nanokelvin
temperatures, lots of fascinating things
happen. In one experiment performed
at Harvard University, a super cold and
super dense cloud of sodium nearly
froze light in its tracks, reducing it’s
speed to a mere 38 mph!

[1]

HEAVY METAL

So far, you’ve seen liquids and gases

used as thermal medium. But solids
can work too, relying on the fact that
they expand and contract in response
to changes in temperature.

During the last century, so-called

bimetallic temperature sensors played a
large role. Indeed, if you have an older
house, the original equipment thermo-
stat may well contain an example of
the breed. Or, check the kitchen, where
bimetallic temperature sensing is still
at work in toaster ovens and meat
thermometers.

The technique combines two strips

of different metal, notably ones that
have different thermal coefficients of
expansion. The strips are fixed togeth-
er at one end and typically wound in a
coil to reduce the footprint while
retaining enough length to achieve the
desired stroke. As the temperature
changes, the two strips expand and con-
tract at different rates, changing the gap
between the non-fixed ends. Even
today, bimetallic switches live on, espe-
cially in electrically or physically harsh

environments that take advantage
of their robustness and the fact
they don’t require a power supply
(see Figure 1).

Popular with the robotics

crowd, so-called “muscle wires”—
the street name for nitinol, a nick-
el-titanium alloy—are another
interesting example of the thermo-
mechanical breed (see Photo 1).
Nitinol is a unique shape-memory
material that can be deformed, but
then returns to its original shape

when heated. Talk about blue-sky appli-
cations, the Mars Pathfinder rover used
muscle wire as the actuator for a sci-
entific experiment.

[2]

Other phase-change materials—

including all manner of stickers, tapes,
paint, and wax—are used for everyday
temperature-sensing applications (see
Photo 2). Some variations continually
track temperature while others are latch-
ing in nature, thereby keeping a perma-
nent record that a threshold was exceed-
ed. A typical application might find
these sensors accompanying a shipment
of goods that must remain refrigerated.
At the receiving end, a quick glance is all
it takes to confirm whether or not the
shipment remained acceptably chilled
during the entire trip.

Some of the latching-type phase-

change sensors are one-shot in nature
and no longer useful after the tempera-
ture threshold is exceeded (e.g., a label
that changes color permanently). Others,
such as the crayons, are reusable (melted
wax indicating that an over-temper-
ature condition has occurred) simply
by remolding.

FIRE WIRE

I could go on. There are a lot of dif-

ferent ways to measure temperature.

Disc

Actuator ball

Contacts

Terminals

Cap

Figure 1

Don’t dismiss an old-school approach, such as the Airpax

5300 bimetallic switch, when a simple (no power required) and robust
(120 VAC, 5 A, operating temperature to 350°F) solution is required.

Photo 1—

This muscle wire on steroids from Nano-

Muscle is buff. Thanks to a stack of thermo-mechanical
elements, the strongest version can bench press more
than a quarter of a pound (125 g) with a rated life of
more than 1 million cycles.

Photo 2—

Let’s talk turkey. Besides this pop-up dinner-is-

served indicator, other one-shot, or irreversible, tempera-
ture threshold monitors include labels, paints, and wax.

background image

80

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Heck, even the chirp frequency of
crickets will do in a pinch. But I
figure now that you’re halfway
through my column—and the nine-
teenth century—I’d better get on
to electronic temperature sensors.

That story starts with Thomas

Seebeck’s (1770–1831) discovery
in 1826 that heat causes current
to flow between two wires made
of different metal. His invention,
the thermocouple, is a mainstay
in industrial and scientific appli-
cations to this day.

Thermocouples have a lot

going for them beginning with
the fact that they’re really sim-
ple—just two wires joined together at
one end. In turn, that makes them
extremely robust and able to deal
with hell-freezing-over temperature
extremes well beyond the range of
other sensors (see Table 1). Simplicity
also means a raw thermocouple junc-
tion is extremely low-cost, although
add-on options in the form of probes,
packaging, and wiring can add up
quickly. Thanks to their use in mis-
sion-critical industrial and scientific
applications, thermocouples also enjoy
a confidence-inspiring degree of inter-
national standardization and rigorous
specs.

The bad news about thermocouples,

an inevitable payback for the wide tem-
perature range, is low sensitivity—well
under 100 µV per 1°C (see Figure 2). It
takes a huge temperature swing (1000°C)
just to coax 0.1 V from a thermocouple.

From a signal acquisition perspective,

the low sensitivity of thermocouples is
less an issue today than it used to be
thanks to the emergence of low-cost
and high-quality analog chips. Indeed, it
would seem the latest generation of
high-resolution A/D converters makes
the issue go away altogether. For exam-
ple, the 50-µV resolution of a 3.3-V,
16-bit A/D converter is good enough to

quantize, within a degree or two,
close to the basic accuracy of the
thermocouple itself.

A low-level signal may no longer

be such a big problem for the chips,
but it certainly is for the wires.
Besides the obvious challenges
posed by interference and lead
resistance, thermocouple hookups
must overcome the gotcha that the
connection to the measuring instru-
ment itself is a junction that com-
promises the measurement from
the real junction. In a precision sci-

entific laboratory environment, you
might actually find an additional
reference junction sitting in an ice

bath. More typically, you’ll find a low-
cost temperature sensor in the measur-
ing equipment itself that compensates
the thermocouple measurement.

Coming at Ohm’s law from another

angle, in 1871 Sir William Siemens
(1823–1883) proposed using a conductor
whose resistance changed with temper-
ature—the basis for the modern resist-
ance temperature detector, or RTD.
Many conductors can be used, but plat-
inum works best, and RTDs are avail-
able both in real wire (wire wound) and
IC-like (thin film) versions. Platinum
RTDs arguably offer the best overall
temperature sensor performance con-
sidering all of the factors (range, accu-
racy, stability, etc.).

One thing to watch out for is self-

heating, in which heat generated by the
sensor itself contributes error to the
temperature measurement. Platinum
RTDs tend to have low base resistance
(100

), thereby calling for a lot of cur-

rent (and thus potential self-heating)
to deliver a large and easy-to-see volt-
age swing.

As the name implies, a thermistor is

another type of thermal resistor, but
it’s one that relies on a metallic oxide
deposited on a ceramic substrate.
Consider it kind of a blue-collar cousin
to the RTD with slightly less elegant
specs (notably temperature range, stabili-
ty, interchangeability, and linearity) but
some practical advantages (cost, physical
ruggedness, and a higher base resistance).
Although the absolute sensitivity (i.e.,
resistance change per 1°C) of a thermis-
tor is less than an RTD, the relative sen-
sitivity (considering the more limited

Characteristic

Pt RTD, Film

Pt RTD, WW

Thermistor

Thermocouple

Silicon

Active material

Platinum thin film Platinum,

Metal oxide

Two dissimilar

Silicon transistor

wire wound

ceramic

metals

cascade

Relative sensor cost

Moderate to low

Moderate

Low to moderate

Low

Low

Relative system cost Moderate

Moderate

Low to moderate

High

Low

Temperature range

–200° to 750°C

–200° to 850°C

–150° to 500°C

–270° to 1800°C –40° to 125°C

(560°C max. typ.) (600°C max. typ.) (125°C max. typ.)

Changing parameter

Resistance

Resistance

Resistance

Voltage

Voltage

Base value

100 to 2000

100

1 k

to 1 M

<10 µV at 25°C 750 mV at 25°C

Interchangeability

±

0.1%,

±

0.3°C

±

0.06%,

±

0.2°C

±

10%,

±

2°C typ.

±

0.5%,

±

2°C

±

1%,

±

3°C

Stability

Excellent

Excellent

Moderate

Poor

Moderate

Sensitivity

0.39%/°C

0.39%/°C

–4%/°C

40 µV/°C

10 mV/°C

Relative sensitivity

Moderate

Moderate

Highest

Low

Moderate

Linearity

Excellent

Excellent

Logarithmic, poor

Moderate

Moderate

Slope

Positive

Positive

Negative

Positive

Positive

Noise susceptibility

Low

Low

Low

High

Low

Lead resistance errors Low

Low

Low

High

Low

Minimum size (inches) 0.050 × 0.065

0.5 × 0.060

φ

0.016 × 0.120

0.025 × 0.016

φ

SO-53

Minimum probe

0.080

0.080

0.065

0.025

0.080

diameter
Special requirements

Lead

Linearization

Reference

compensation

junction

Table 1—

This table summarizes the key characteristics of the most popular temperature sensors: platinum RTDs

(both wire wound and thin film), thermistors, thermocouples, and semiconductors.

[3]

80

70

60

50

40

30

20

10

0

0

500

1000

1500

2000

2500

E

J

C

R

S

T

K

Temperature (°C)

Milliv

olts

Figure 2—

Although appreciated for their wide operating temperature

range, even the most sensitive type E thermocouple
(Chromel/Constantan) delivers less than 100 µV per 1°C.

background image
background image

82

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

temperature range) is quite good.

The big knock on thermistors is that

the output, although predictable and
repeatable, is extremely nonlinear (see
Figure 3). Keep in mind that for some
applications, such as a simple thermo-
stat, linearity may not be a big deal.
Also, if there’s an MCU in the design, it
can easily handle linearization in soft-
ware at virtually no extra cost. But for
stand-alone (no MCU) applications
that need decent linearity, the extra
circuits required erode the thermis-
tor’s cost advantage.

SEMI SOLUTIONS

Like everything else, temperature

sensing has been riding the wave of
the integrated circuit revolution. The
beauty of the scheme is that any and
all required signal processing and sup-
port circuits can be built on the same
chip. IC temperature sensors are
quickly becoming the easiest to use
and lowest overall cost
solution—advantages
that will only grow with
the inexorable march of
Moore’s law. Their per-
formance specs are also
catching up with the tra-
ditional sensors in prac-
tically every respect. The
only possible showstop-
per is temperature range,
which remains limited as
it is for all ICs.

First-generation analog

IC temperature sensors
remain a popular option
with K, C, and F ver-
sions that typically put
out a healthy 10 mV per
degree (see Photo 3). For

the C and F variants, the issue of
negative temperatures (i.e., nega-
tive voltage output) can be prob-
lematic, requiring an additional
negative or reference voltage
source. A better option is to use
a single supply sensor (e.g., the
National LM50 or Andigilog
aTS21) that adds an internal volt-
age offset and possibly switches
the slope of the output as well.

One small step for chip design-

ers—combining the temperature
sensor with an on-chip A/D con-

verter—became one big step for tem-
perature sensing with the emergence of
digital temperature sensors. The obvi-
ous advantage is that putting the A/D
converter on the temperature chip
itself means you don’t need to come up
with one externally. Better yet, on-chip
integration also eliminates all the
sources of error (interference, voltage
drop, etc.) associated with shuttling an
analog signal between chips.

Putting an A/D converter on chip was

just the start. More functions are being
added all the time, everything from a
simple thermostat capability (compara-
tor and on/off output) to complete ther-
mal management subsystems includ-
ing local and remote temperature sens-
ing, fan control, voltage monitoring, etc.

Ironically, if there’s one glitch in the

digital temperature sensor equation, it’s
with the digital part. Here you have
an example of a good idea—a simple
serial interface—run amok. Who’d

have thought we would need so many
different ways (e.g., SPI, Microwire, I

2

C,

SMBus, and 1-Wire) to ship a few bits of
temperature data from here to there?

Add National’s new SensorPath to

the list (see Figure 4). It reminds me of
the Dallas (now Maxim) 1-Wire inter-
face because both schemes use asyn-
chronous pulse width encoding so a
clock pin isn’t required.

To be fair, most of the serial bus

complexity and compatibility concerns
are limited to fancier systems, notably
PCs. That’s especially true for multi-
master serial bus configurations that
must grapple with messy issues such as
arbitration, collisions, address alloca-
tion, and so on. The situation is much
simpler for typical (i.e., single-master)
embedded applications.

The most interesting trend on the

digital temperature sensor front is as
much about where they are as what
they are. I’ve noticed temperature sen-
sors popping up in MCUs and other
chips—a trend I expect will continue.

THIRD DEGREE

There are a lot of ques-

tions to ask yourself when
choosing a temperature
sensor. The primary deci-
sion factor is temperature
range. If you’re challenged
by the extremes of a blast
furnace or liquid nitrogen,
a thermocouple is the only
way to go—at least when
it comes to contact sen-
sors. (Noncontact sensors,
such as IR or acoustic, are
another option.) On the
other hand, if you can live
within their relatively
temperate limits, it’s
apparent there are few (and
ever fewer) arguments

Thermistor resistance verses temperature

Temperature (°C)

–20

0

20

40

60

80

100

120

140

100K

90K
80K
70K
60K
50K
40K
30K
20K
10K

Resistance (

)

Figure 3—

Thermistors offer good sensitivity and range, but

the output is nonlinear. If that’s a problem, consider using a
platinum RTD.

Photo 3—

As you can see (barely), one advantage of

semiconductor temperature sensors is small size. This
evaluation board from Andigilog comes with a half
dozen members of aTSxx analog sensor family for
easy side-by-side comparison.

Figure 4—

National’s Sensor Path is a new digital temperature sensor interface that uses

pulse-width encoding to eliminate the need for a clock pin.

Master
Write
Start

Master
Write 1

Master
Write 0

Attention

Reset

t

INACT

t

MtrS

Attention

detect

t

INACT

Reset

detect

t

RST

0 µs

50 µs

100 µs

200 µs

300 µs

400 µs

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

83

against semiconductor sensors.

It gets interesting between roughly

–200° and 1000°C. RTDs, thermocou-
ples, and thermistors are all candi-
dates. It’s likely that the decision will
boil—no pun intended—down to a
unique advantage (e.g., sensitivity of a
thermistor, voltage output of a ther-
mocouple, superior stability of an
RTD, etc.) that proves compelling for
a particular application.

Whichever type of sensor you

choose, one thing’s for sure, with ever-
improving performance, lower prices,
and proliferation into other chips, tem-
perature sensors are expanding into
applications both near and very, very
far. The sky, even Mars, isn’t the limit.

As I finish this column, Spirit and

Opportunity are making great strides,
including finding hard evidence that
water once existed and Mars wasn't
always necessarily a dustbowl. Of
course, there was a bit of nail biting
when Spirit had a “computer problem”
(meaning, as usual, a software problem).
What a shining example of right-stuff
engineering when the folks at NASA
delivered an interplanetary bug fix.

Stay warm, rovers. And have a nice

Sol.

I

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.

REFERENCES

[1] C. Lambert, “Light at 38 M.P.H.,”

Harvard Magazine

, www.harvard-

magazine.com/issues/mj99/right.
light.html.

[2] P. Jenkins, G. Landis, and L.

Oberle, “Materials Adherence
Experiment,” IECEC-97339, 32nd
Intersociety Energy Conversion
Engineering Conference, Hono-
lulu, HI, 1997, powerweb.grc.nasa.
gov/pvsee/publications/mars/
techn.html.

[3] Honeywell, “Temperature Tutorial:

Comparing Temperature Sensors,”
content.honeywell.com/building/
components/HycalHtml/temp.
asp, 1998.

RESOURCE

B. Lynds, “About Temperature,”
www.unidata.ucar.edu/staff/
blynds/tmp.htm, 1995.

aTSxx semiconductor temp sensors
Andigilog
www.andigilog.com

Linear and rotary actuators
NanoMuscle, Inc.
(925) 776-4700
www.nanomuscle.com

LMxx semiconductor temp sensors
National Semiconductor
www.national.com

SOURCES

Bimetallic temperature switches
Airpax Corp.
(301) 663-5141
www.airpaxtsp.com

background image

84

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

IDEA BOX

THE

DIRECTORY

OF

PRODUCTS AND

SERVICES

AD FORMAT

: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.

ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2

″″ ××

3

″″

FORMAT

. Call for current rate and deadline information. Send your disk and digital submis-

sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail kc@circuitcellar.com. For more information call Sean Donnelly at (860) 872-3064.

The Suppliers Directory at www.circuitcellar.com/suppliers_dir/

is your guide to a variety of engineering products and services.

experience xBOB

turn serial data into video text

w w w.decadenet.com

D

ECADE

E

NGINEERING

503-743-3194 Turner, OR, USA

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 166 May 2004

85

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 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Got Dial Tone?

R

ING

-I

T

!

T

ELCO

S

IMULATOR

Caller-ID

LED display

Audio Output Jack

Real 20Hz Ring

$325 Sale $299.95

Telecom Hardware/Software Developers

STOP using your phone lines to test and demonstrate
your telecom devices. Our affordable telephone line
simulators offer authentic USA dial tone, busy signals
and ringing. Supports high speed analog modems too!

P

ARTY

-L

INE

T

ELCO

S

IMULATOR

Six Extensions

Caller-ID

Distinctive Ringing

CPC Disconnect

$425 Sale $399

Digital Products

Company

134 Windstar Circle

Folsom, CA 95630 USA

Tel: 916-985-7219

Fax: 916-985-8460

http://www.digitalproductsco.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

87

background image

88

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

89

background image

90

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Email: sales@picofab.net

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

91

background image

92

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 166 May 2004

93

background image

Wireless Monitoring System

Monopole Antenna Design

Turbocharged Upgrade: Crank Trigger Modification Eliminates Engine Knocking

MCU Evolution: New Microcontrollers Meet Increasing Demand

Designing with the Nios (Part 1): Second-Order, Closed-Loop Servo Control

Simple Bluetooth Integration (Part 2): Interfaces and ECI Protocol

ABOVE THE GROUND PLANE

Robot Mechanics

APPLIED PCs

Adaptable Temperature Measurement System

FROM THE BENCH

Smart Sensor Design

SILICON UPDATE

Radio Riot

94

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

88

Abacom Technologies

86

ActiveWire, Inc.

91

All Electronics Corp.

93

Amazon Electronics

20

AP Circuits

71

ARCOM Control Systems

27

Arcturus Networks

90

Ash Ware

7

Atmel

26

Austrol Industries Pty Ltd

15

AVR 2004 Contest

91

Bagotronix, Inc.

84

BayTech Sales

59

Bellin Dynamic Systems, Inc.

58

Belsoft

13

CadSoft Computer, Inc.

89

Carl’s Electronics

93

CCS-Custom Computer Services

92

Conitec

84

Cyberpak Co.

1

Cypress MicroSystems

65

CWAV

20

Dallas Logic Corp.

91

DataRescue

84

Decade Engineering

86

Digital Products Co.

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page

84

DLP Design

8

Earth Computer Technologies

87

EE Tools

(Electronic Engineering Tools)

77

EMAC, Inc.

89

emBoot, Inc.

28

ExpressPCB

84

FDI-Future Designs, Inc.

92

Front Panel Express

85

Hagstrom Electronics

74

HI-TECH Software, LLC

29

Holmate Semiconductor

34

ICOP Technology Inc.

89

IMAGEcraft

66

Imagine Tools

86

Intec Automation, Inc

91

Integrated Knowledge Systems

85

Intrepid Control Systems

91

Intronics, Inc.

57

Jameco

64, 86

JK microsystems, Inc.

85

JPA Consulting

20

JR Kerr Automation & Engineering

59

LabJack Corp.

59

Lakeview Research

31

Lemos International

2

Link Instruments

8, 83

Linx Technologies

56

MaxStream

89

MCC (Micro Computer Control)

9

Microchip

86

MicroControls

88

Micro Digital

92

microEngineering Labs, Inc.

95

Micromint

90

MJS Consulting

86

Mosaic Industries, Inc.

30

Mouser Electronics

42

MVS

86

Mylydia Inc.

C2

NetBurner

85

NPE, Inc.

88

OKW Electronics, Inc.

92

Ontrak Control Systems

18

PCB123

87

PCB Fab Express

C4, 9 Parallax, Inc.

84

Phytec America LLC

87

Phyton, Inc.

90

Picofab Inc.

93

Pulsar, Inc.

88

Quality Kits & Devices

88

R2 Controls

Page

Page

Page

73

R4 Systems Inc.

49

Rabbit Semiconductor

26

Remote Processing

87

RLC Enterprises, Inc.

93

Rogue Robotics Corp.

87

Scidyne

3

Scott Edwards Electronics Inc.

88

Sealevel Systems

5

Sierra Proto Express

89

Signum Systems

85

Softools

92

TAL Technologies

C3

Tech Tools

40, 41

Technologic Systems

90

Technological Arts

89

Tern Inc.

85

Trace Systems, Inc.

91

Triangle Research Int’l, Inc.

77

Trilogy Design

19

Velocity Semiconductor

93

Weeder Technologies

91

Zanthic Technologies Inc.

86

Zexus Technologies Ltd.

90

Z-World

July Issue 168

Deadlines

Space Close: May 10

Material Due Date: May 20

Theme:

Graphics & Video

A

TTENTION

A

DVERTISERS

Call Sean Donnelly now to

reserve your space!

860.872.3064

e-mail: sean@circuitcellar.com

INDEX OF ADVERTISERS

Preview of June Issue 167

Theme: Measurement & Sensors

background image

background image

E

ver think about how dependent you have become on the guy who writes the control program for a product and how vulnerable you are if he

doesn’t know what he’s doing? Last week I had an interesting adventure thanks to a company obviously still working out the bugs in the transition
from electromechanical cams and switches to C++ and microcontrollers. I went to the car wash.

Ordinarily I wash my car at home. I even installed hot and cold water to a hose reel in the garage so I can do it more easily. I don’t know whether

I was weak-willed that day or just feeling adventurous, but I decided to go to the drive-through car wash down the street instead.

I pulled up to the entrance of the car wash. The guy leaning back reading the sports section really didn’t care that I had driven up. He was deter-

mined to finish whatever he was reading. As I was about to lean on the horn, he finally got up and walked around the car. While I was waiting for
my change, I noticed a bunch of posted disclaimers. Apparently SUVs do nasty things if they fall off the tracks or something like that. With all the
signs warning me that the car wash wasn’t responsible for all the damage they intended to perpetrate on my vehicle after the process started, I fig-
ured I shouldn’t care that my SUV would total the car wash as reprisal either.

The operator came to the conclusion that my SUV was tolerable and he took my money. I don’t know why they call it a “drive through,” because

that’s the last thing they want you to do. Just put it in neutral, sit back, and listen to music while everything gets clean.

Well, so much for the music. Satellite radio doesn’t like roofs and I was too far from a terrestrial transponder. Ten feet into the tunnel, my XM

Radio turned to pink noise, and I was subjected to a soapy whiteout. The marvel of mechanical ingenuity rotated nozzles, squirted soap, and
sprayed a mini hurricane of detergent and water as I progressed through the washing stages. Maybe this isn’t so bad after all, I thought.

The car was slowly pushed to the next stage where rotating cloth strips started beating on the car. “Beating” might be a strong description, but

it surely seemed like that. I realized a long time ago that a “touchless” car wash is useless without a little elbow grease. Let’s just say this was robot-
ic elbow grease.

Rotating sprayers went up and down the side doors as the cloth strips went wap, wap, wap against the hood and windshield. I just wished this

thing wasn’t washing my car quite so hard, but I was consoled with the knowledge that it would be only a few more seconds until the rinse cycle
started. Or at least that was how it was supposed to work.

Suddenly, the track stopped moving. For whatever reason, however, the washing continued cycling through the same series of maneuvers.

Instead of the 90 seconds for the whole wash, rinse, and dry, it had now been 2 minutes and I was still seeing soap and spraying water. Something
had happened to the system and it was stuck. OK, operator. Now is the time you get off your chair and go press the reset button, I said to myself.

Through the torrential assault I could see a control panel with a bunch of colored lights mounted on the wall. A red indicator blinked incessantly,

but it didn’t seem to do much else. The cleaning cycle and rotating cloth continued to go wap, wap, wap as a monsoon raged all around the car.

Where the heck was the operator for this thing and how was I supposed to get out of there? What was he doing back there, sleeping? Didn’t

he see that the line wasn’t moving anymore? I honked the horn twice, waited 30 seconds, and honked again. Where was this guy? I thought about
opening the door to find him, but getting 20 gallons of water out of the upholstery quickly stifled that consideration. I thought about using my cell
phone, but whom would I call? If this guy wasn’t in the office to see that his conveyor system wasn’t moving, he wasn’t there to answer the phone
either. Then, the real anger hit me. What idiot designed the control program for this car wash system?! Didn’t he ever hear about closed-loop con-
trol sensing or watchdog timers?

At this point, I was starting to get ripped. At the 5-minute point, I thought about climbing over the seats and going out the hatchback. I’d get

drenched, but perhaps it wouldn’t be quite as soapy on that route. Then, I said screw it. The most off-roading this car had ever seen was the curb
in a parking lot, but I wasn’t going to sit there to the point where I’d have to argue with the car wash owner to pay for a new paint job because they
washed it too well. I jammed the car in gear and drove the 30 feet down the rest of the car wash and out the exit. I did hear a few twangs and a
ripping sound, but whatever brushes, track linkage, etc. was in the way, it was no match for a 3-ton SUV.

I stopped just outside the car wash to clear the soap off the windshield. The operator came running out yelling I had broke his car wash. I said

it had stopped working long before I did anything to it and there weren’t any signs prohibiting emergency exits. His reply was, “I hate SUVs!”

Of course he didn’t understand, but I replied, “Yeah, and I hate dumb embedded-control programmers!”

All Washed Up

steve.ciarcia@circuitcellar.com

96

Issue 166 May 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

by Steve Ciarcia, Founder and Editorial Director

PRIORITY INTERRUPT

background image
background image

Wyszukiwarka

Podobne podstrony:
circuit cellar2001 05
circuit cellar1997 05
circuit cellar2000 05
circuit cellar2002 05
circuit cellar1994 05
circuit cellar1993 05
circuit cellar2003 05
circuit cellar1995 05
circuit cellar1996 05
circuit cellar2001 05
circuit cellar1997 05
circuit cellar1993 05
circuit cellar1996 05
circuit cellar2001 05
circuit cellar1995 05
circuit cellar1994 05
circuit cellar2003 05

więcej podobnych podstron