circuit cellar2004 10

background image

7

9

25274 75349

1 0>

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)

#171 October 2004

DATA ACQUISITION

Low-Cost SCADA Project

MCU-Based Call-Forwarding System

Temperature Sensing and Acquisition

Digital Radio Control

background image
background image
background image

Digital Oscilloscopes

2 Channel Digital Oscilloscope

100 MSa/s

max single shot rate

32K samples per channel

Advanced Triggering

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

Small, Lightweight, and Portable

Parallel Port

interface to PC

Advanced Math options

FFT Spectrum Analyzer options

DSO-2102S

$525

DSO-2102M

$650

Each includes

Oscilloscope

,

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

40 to 160 channels

up to 500 MSa/s

Variable Threshold

8 External Clocks

16 Level Triggering

up to 512K samples/ch

Optional Parallel Interface

Optional 100 MSa/s Pattern Generator

LA4240-32K (200MHz, 40CH)

$1350

LA4280-32K (200MHz, 80CH)

$2000

LA4540-128K (500MHz, 40CH)

$1900

LA4580-128K (500MHz, 80CH)

$2800

LA45160-128K (500MHz, 160CH)

$7000

www.LinkIns4.com

Link Instruments

369 Passaic Ave

Suite 100

Fairfield, NJ 07004

(973) 808-8990

Fax (973) 808-8786

Logic Analyzers

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

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

$800

All prices include Pods and Software

background image
background image

M

any projects are never really done. Sometimes it’s because they

never really worked right to begin with. A lack of money, time, or
brainpower (although rarely admitted) is usually to blame. Other
times, you’re compelled to revisit a project you thought was finished
because new technology makes it possible to improve upon your
design. We have a couple of great projects this month that are the
result of redesigns.

Charlie Krauter went back to the drawing board to correct the

problems that made his undergraduate senior project come up
short (p. 12). He intended to build an efficient liquid piston steam
engine based on a computer model that would pump water using few
moving parts. When it failed, what bothered him the most was that he
couldn’t figure out why it didn’t work. Charlie decided to build a low-
cost supervisory control and data acquisition system. His CAN bus
system turned his project into a success.

In “Intelligent Sensor Head,” Andrew Smallridge discusses how

he redesigned a Bowen ratio data acquisition system to offer better
stability and accuracy (p. 60). He was inspired to revisit the temper-
ature sensor conditioning and acquisition subsystem by the introduc-
tion of inexpensive, high-performance analog building blocks.
Moreover, he kept the overall cost in check because he didn’t need
a hardware development platform and he used free software devel-
opment tools. The project is built around a Maxim MAX1463 signal
processor and a Microchip PIC18F252 microcontroller. The result is
impressive.

Larry Cicchinelli had similar results when he went back to work on

a previous logic analyzer project (p. 54). This month, he walks us
through the design of his new eight-channel, single-board logic ana-
lyzer (SBLA). He set a tall order to fill; the most significant goal was
to fit all of the circuitry on a single PCB that would be easy to build.
Larry met his goal, and the result is a hard-working piece of test and
measurement equipment that’s a must-have for anyone who deals
with complex digital circuits.

Even when you say you’re finished with a project, chances are

you’ve already made a mental list of potential upgrades. These
designers have shown that a redesign can yield big results. To bor-
row an oft-repeated sentiment from Tom Cantrell, as long as the
march of silicon keeps up the pace, just about any project can be
improved upon.

4

Issue 171 October 2004

www.circuitcellar.com

CIRCUIT CELLAR

®

EDITORIAL DIRECTOR/FOUNDER

Steve Ciarcia

MANAGING EDITOR

Jennifer Huber

TECHNICAL EDITOR

C.J. Abate

WEST COAST EDITOR

Tom Cantrell

CONTRIBUTING EDITORS

Ingo Cyliax

Fred Eady

George Martin

George Novacek

Jeff Bachiochi

NEW PRODUCTS EDITOR

John Gorsky

PROJECT EDITORS

Steve Bedford

Ken Davidson

David Tweed

ADVERTISING

PUBLISHER

Dan Rodrigues

E-mail: dan@circuitcellar.com

ASSOCIATE PUBLISHER/DIRECTOR OF SALES

Sean Donnelly

Fax: (860) 871-0411

(860) 872-3064

E-mail: sean@circuitcellar.com

Cell phone: (860) 930-4326

ADVERTISING COORDINATOR

Valerie Luster

Fax: (860) 871-0411

(860) 875-2199

E-mail: val.luster@circuitcellar.com

ADVERTISING ASSISTANT

Deborah Lavoie

Fax: (860) 871-0411

(860) 875-2199

E-mail: debbie.lavoie@circuitcellar.com

CONTACTING CIRCUIT CELLAR

SUBSCRIPTIONS:

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

GENERAL INFORMATION:

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

AUTHOR CONTACT:

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

CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub-
lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at
Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico
$31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico $55,
all other countries $85.
All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money order,
or check drawn on U.S. bank.
Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH
03755-5650 or call (800) 269-6301.
Postmaster:
Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

For information on authorized reprints of articles,

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

Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the
consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-
er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or
from plans, descriptions, or information published by Circuit Cellar®.
The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to
build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to
construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.
The reader assumes any risk of infringement liability for constructing or operating such devices.
Entire contents copyright © 2004 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks
of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

CHIEF FINANCIAL OFFICER

Jeannette Ciarcia

CUSTOMER SERVICE

Elaine Johnston

CONTROLLER

Jeff Yanco

ART DIRECTOR

KC Prescott

GRAPHIC DESIGNER

Mary Turek

STAFF ENGINEER

John Gorsky

QUIZ COORDINATOR

David Tweed

Cover photograph Chris Rakoczy—Rakoczy Photography

PRINTED IN THE UNITED STATES

Redesigned to Impress

jennifer.huber@circuitcellar.com

TASK MANAGER

background image
background image

6

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

October 2004: Data Acquisition

4

TASK MANAGER
Redesigned to Impress
Jennifer Huber

8

NEW PRODUCT NEWS
edited by John Gorsky

11 TEST YOUR EQ

edited by David Tweed

FEATURES

COLUMNS

DEPARTMENTS

94 INDEX OF ADVERTISERS

November Preview

96 PRIORITY INTERRUPT

The Collegiate Challenge
Steve Ciarcia

54 Single-Board Logic Analyzer

Larry Cicchinelli

60 Intelligent Sensor Head

Andrew Smallridge

76 Telephone Message Watchdog

An Intelligent Call-Forwarding System
Jingxi Zhang, Yang Zhang, and Huifang Ni
Renesas Design 2003 First Prize Winner

12 Supervisory Control and Data Acquisition

Charlie Krauter

26 E-Field Serial Touchpad

Erwin Saavedra

32 Pseudo-Random Noise Theory and Applications

Shlomo Engelberg and Haim Benjamin

36

ABOVE THE GROUND PLANE

Stepper Drive (Part 2)
Digital
Ed Nisley

40

APPLIED PCs

Big PICs
Fred Eady

48

FROM THE BENCH

Digital Radio Control
Jeff Bachiochi

70

SILICON UPDATE

Try Hard with a Vengeance
Tom Cantrell

Data Acquisition Solution (p.12)

Message-Forwarding System (p. 76)

Digital R/C Circuitry (p. 48)

background image
background image

8

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

Edited by John Gorsky

MODULAR I/O SYSTEM

The SeaI/O family is a modular I/O system that offers

selectable connectivity and a wide variety of I/O types for
distributed control and data acquisition requirements. An
array of configurations is available, each designed for maxi-
mum flexibility and easy field wiring. Ordering options
allow for connection to the host device via Ethernet
(Modbus/TCP), RS-485 (Modbus/RTU), USB, or RS-232.

Multiple units of any I/O

type can be easily daisy-
chained together using con-
venient pass-through con-
nectors. This expansion
capability enables a distrib-
uted network to be con-
trolled with even a tradition-
al point-to-point USB or RS-
232 host connection. For
easy software integration,
application programs or third
party software can use the
SeaMAX library or industry-
standard Modbus protocol.

SeaI/O modules are per-

fect for a wide variety of
applications and environ-

ments such as process control, data acquisition, broad-
cast automation, security, and facility management. Five
different I/O models are currently available that offer a
choice of optically isolated inputs, Reed relay outputs,
and Form C relay outputs. Field-removable terminal
blocks are standard, facilitating fast, flexible field wiring.
SeaI/O modules operate from 9 to 30 VDC. Power is input

via a terminal block or DC
jack. Both table mount and
DIN rail mounting options
are available.
Configuration is easy
using Sealevel’s software
configuration tool.

The standard operating

temperature range of
SeaI/O modules is 0°C to
70°C. An extended temper-
ature range (–40° to 85°C) is
optional.

SeaI/O prices start at

$369.

Sealevel Systems, Inc.

www.sealevel.com

background image
background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

11

What’s your EQ?

The answers are posted at

www.circuitcellar.com/eq.htm

You may contact the quizmasters at eq@circuitcellar.com

CIRCUIT CELLAR

Test Y

Your E

EQ

Problem 3

What are some of the advantages of the

second circuit over the first? Hint: think about some of the

characteristics of nonideal components.

Problem 4

Frugalson has a simple voltage measure-

ment and serialization application. The budget only affords a

12-bit ADC and a $2 MCU for conversion and control. The

12-bit binary ADC has a full range of 0 to 10 V, and the serial

packet formatting must be in decimal in units of 0.01 V. One

day before the deadline of the project, Frugalson realizes

that the MCU has no C language support, let alone floating-

point libraries. Should Frugalson start to update his resume?

Contributed by David Tweed

Edited by David Tweed

Problem 1

What is the load current I

LOAD

in the follow-

ing circuit if R3/R2 = R4/R1?

Problem 2

What is the load current I

LOAD

in this other

circuit if R3/R2 = R4/R1?

+

V

IN

R

1

V–
V+

R

4

V

A

R

3

I

LOAD

R

2

+

V

IN

R

1

V–
V+

R

4

V

A

V

B

I

LOAD

R

2

R

4

R

5

background image

12

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

computer model that demonstrated how
the device would work. Armed with this
model, I convinced my professor to let
me built a full-scale prototype.

When it came time to try it out, I

turned on the heat and watched this
grand device of my own creation gur-
gle, spit, and ultimately do nothing.
Many more hours of tinkering pro-
duced no other effect. It was my final
lesson in how mechanical engineering
differs from the style of development I
was used to. I presented my results as

S

everal months ago, I began con-

structing my senior project for my
undergraduate program in mechanical
engineering. It was a liquid piston
steam engine that could pump water
with a minimum amount of moving
parts. Before starting the mechanical
engineering program, I had some expe-
rience in the electronics and software
world, but no practical experience
with mechanical systems. Therefore,
it shouldn’t surprise you how I took on
this unproven idea. First, I developed a

best I could and still got my degree,
but I felt as though I hadn’t finished
the project. Not because it didn’t
work, but because I couldn’t tell how
and why it didn’t work. All I knew is
that it didn’t fit the computer model.

I realized that if I were to continue

to pursue this on my own, or try to
invent another mechanical contrap-
tion based on a computer model, I
would need a data acquisition system
to measure the differences. I had sev-
eral requirements for my homebrew

Supervisory Control and Data Acquisition

Charlie recently built a data acquisition system that he now uses when experimenting with
liquid piston steam engines. The system includes a CAN bus-to-Ethernet bridging device
and a CAN-based thermocouple interface node.

FEATURE ARTICLE

by Charlie Krauter

Figure 1—The RCM3700 core module plugs into the CANPipe board, which contains the CAN bus controller and transceiver hardware. The NOR gate is needed for the

Rabbit to interface to the multiplexed bus on the SJA1000 controller.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

13

supervisory control and data acquisi-
tion (SCADA) system. First, I wanted
it to be expandable. Who knows what
I’ll want to add later? Second, I
thought it should be small because I
couldn’t imagine more than a few
hundred sensor points stuffed in my
garage. Third, I decided it should be
heavy on data and light on control. I
thought it would be good to have some
distributed control capabilities in the

system, but it’s primarily for
data collection. Finally, I
was shooting for an inexpen-
sive system because I was
paying for it myself.

Based on these criteria

and a desire to stick with
standards for the communi-
cations protocol, I chose to
create a CAN bus system
that connects sensor nodes
to a PC-based data collection system
through an Ethernet bridge. CAN bus
has enough speed for this application,
and the robust signaling and long bus
lengths are good for outdoors experi-
ments involving water pumps.

I chose Ethernet for communication

between the bus and a PC. Its advan-
tages include standardization and long
signaling lengths. The other logical
choice would have been USB, which
has the relative advantages of simplic-
ity and affordability; however, the lim-
itations on bus lengths with USB
would have created problems for
experiments in which the data collec-

tion station needs to be remote. This
requirement—to have a PC-based data
collection system communicate with
CAN bus—brought about the
CANPipe CAN-to-Ethernet bridge. I’ll
discuss that first, and then I’ll cover the
first sensor node I built, which is an
eight-channel thermocouple interface.

CANPipe

The CANPipe connects to a CAN

bus and allows hosts to send and
receive messages on the bus using
TCP/IP over an Ethernet link. In some
ways this is more complex than using a
dedicated CAN controller card or periph-
eral, but it allows host software to be
written without the need for special driv-
ers and makes it possible for more than
one host to access the device remotely.

The CANPipe hardware, which is

built around a Rabbit Semiconductor
RCM3700 embedded core module,
uses a Philips SJA1000 controller chip
to communicate with the CAN bus
side. The software on the RCM3700
acts as an application server that
allows multiple host systems to con-
nect as clients.

RCM3700

The RCM3700 incorporates an

R3000 microcontroller, program flash
memory, RAM, and Ethernet hard-
ware all on a module that can be
plugged into a custom board. This
canned solution simplified the design.

As you can see in Figure 1, there

isn’t much extra circuitry beyond the
CAN bus hardware and some glue
logic. The RCM3700 connects to the
board with a 40-pin, dual-row header.
The pins have a standard 100-mil
pitch, which is helpful when trying to
locate a socket to plug them into.
Using the RCM3700 was also nice
because the development system

Listing 1—The

ale_read() and ale_write() routines are used by the RCM3700 to emulate a

multiplexed bus cycle. They are written in assembly language for the sake of efficiency.

//Low byte of address is latched with ALE.

nodebug root void ale_write(int address, int value)

{

#asm

ipset 1

//Pair of external writes must be atomic

ld a, L //Low byte of address is latched in on ALE

pulse

ioe ld (ALE_DUMMY_ADDRESS), a

ld a, 0x01

ld L, a //Mask out low address byte (make odd)

ex de, hl //de holds masked address

ld hl, (sp+value) //Get value

ld a, L

ioe ld (de), a

ipres

#endasm

}

nodebug int ale_read(int address)

{

#asm

ipset 1 //Pair of external writes must be atomic

ld a, L //Low byte of address is latched in on ALE

pulse

ioe ld (ALE_DUMMY_ADDRESS), a

ld a, 0x01

ld L, a //Mask out low address byte (make odd)

ioe ld a, (hl)

bool hl

ld L, a

ipres

#endasm

}

Photo 1—The bare CANPipe board has everything

connected and the RCM3700 core module plugged
into it. The ribbon cables are for the pair of CAN bus
connectors. The zip tie on the core module is a simple
substitute for mounting screws.

Rabbit: ID0-7(PA0-7)

SJA1000: AD0-7

Rabbit: ICS4(PE4)

SJA1000: /CS

Rabbit: /IOWR

SJA1000: /WR

Rabbit: IA0(PB2)

SJA1000: ALE

Figure 2—The multiplexed bus on the SJA1000 requires the RCM3700 to

write out a register address followed by a read or write of the actual data.

background image

14

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

comes with libraries for a full
TCP/IP stack. This left me only
having to write code for the
CAN interface and the applica-
tion server itself.

I wanted the device to be

rugged. With the Ethernet con-
nector on board, I was concerned
that the module might work
loose from its socket with repeat-

ed use. I fixed this with a com-
mon zip tie running through
holes in the carrier board (see

Photo 1). It looks strange, but it’s defi-
nitely secure and much simpler than
screws and spacers.

The RCM3700 also comes with a

1-MB serial flash memory chip. I haven’t
made use of it in the current version of
the device, but it may come in handy
for logging some of the received CAN
messages in a future version.

SJA1000

The SJA1000 controller chip seems

to be a standard among the fairly
small group of stand-alone CAN con-
trollers. Everybody wants to sell their
microcontroller offering bundled with
an embedded CAN controller. I under-
stand the logic behind this, particularly
for those who work in large volumes.
In my case, adding a separate controller
chip to a microcontroller system that I
am comfortable with and that has all
the capabilities I need makes sense.

Neither the Rabbit nor the AVR,

which I’ll describe later, have built-in
CAN controller hardware. This leaves
me with larger, more expensive cir-
cuits, but it’s well worth it for my
one-off designs. The SJA1000 inter-
faces to a processor through an Intel-
style parallel I/O bus, which gave me
a few headaches. In its extended
mode, the chip is capable of handling
both basic CAN 1.0 messages and the
extended frame format messages
defined in CAN 2.0. The main differ-
ence between the two message types
is the size of the message identifier,
11 versus 29 bits.

For my SCADA project, I stuck to

the 11-bit identifiers for simplicity.
However, the CANPipe can function
as a generic bus-interfacing tool, so it’s
nice to support both. The SJA1000 has
a single transmit buffer and a 64-byte
FIFO for received messages. This is a
good fit for the SCADA application,
in which the CANPipe spends a lot
more time receiving messages than it
does transmitting them. Message
records stored in the on-chip FIFO are
of variable lengths, allowing it to effi-
ciently store smaller incoming mes-
sages. Because a CAN frame consists
of a 2- or 4-byte identifier followed by
0 to 8 data bytes, the length of a
record with an additional information
byte ranges from three to 13. Thus,

Photo 2—Take a look at the back of the CANPipe device. With

some fine-tuning, I managed to get the cutout for the Ethernet
connector on the RCM3700 to line up properly.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

15

fixed-length message records in the
FIFO could potentially waste a lot of
buffer space. Refer to the “CAN
Message” sidebar for information
about arbitrating access to the bus
between the nodes.

ANOTHER BUS

In addition to having to learn a lot

about the CAN bus, I had some prob-
lems with the peripheral I/O bus. The
only real hardware complication in
my simple design was the fact that
the SJA1000 controller chip interfaces
to a multiplexed address/data bus. But
the RCM3700 uses separate address
and data lines. I dealt with this by
using a combination of glue logic and
software.

When everything works, the con-

troller chip thinks it is getting an
address cycle followed by a data cycle,
while the RCM3700 believes it is
talking to two separate devices. No
one knows what is really going on,
and everyone is happy. Now let’s
focus on how it works (see Figure 2).

Every read or write operation to the

controller chip is done with the
ale_write() and ale_read() rou-
tines (see Listing 1). These routines
first write the register address to any
even I/O address (A0 = 0). This causes
the A0 signal at PB2 and the *IOWR
signal on the RCM3700 to go low. The
SJA1000’s ALE pin is driven high by
the NOR gate output, which loads the
data into the address latch.

The routines then perform either a

second write or a read to the fourth
I/O bank with an odd I/O address. The
CHIP SELECT pin for the RCM3700’s
fourth I/O bank is connected to the
CHIP SELECT pin on the controller
chip, causing the desired register to be
read or written to. This technique is
obviously slower than a single I/O
cycle would be, but it’s still much
faster than bit-banging the port.

ADDITIONAL HARDWARE

I used a Microchip MCP2551 CAN

transceiver to translate from logic to
CAN bus levels. The system has two
CAN connectors wired in parallel. A
CAN bus is a daisy-chained network
that must be terminated at both ends
with 120-

resistors. Rather than ter-

minating the bus internally and
requiring the CANPipe to be at one of
the ends, I opted for two connectors. I
rely on external terminators. A 40-W
switching power supply provides
power for the CANPipe board and also
supplies 12 V to other devices on the
CAN bus through the optional power
supply lines.

CONSTRUCTION

I normally consider a project fin-

ished as soon as the circuit is built

and it spends its life as an unprotected
board. However, I need this system to
be able to survive some abuse, so I
enclosed it in an aluminum chassis
box. I used a three-dimensional solid
modeling program to work out a good
arrangement of the components inside
the box and to calculate the necessary
holes and cutouts. (The 3-D model is
posted on the Circuit Cellar ftp site.)
It certainly was not a necessary step.

In the past, I’ve relied on the cut-and-

try assembly method. It usually works

background image

16

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

and results in only a few extra holes in
the finished product. This method was
an experiment to see if modeling the
assembly first would save time in the
long run. Although it wasn’t perfect, I
got better results than I usually do
with the classic method (see Photo 2).

CANPipe SERVER

To handle the TCP/IP side of things,

the CANPipe listens on port 1921 for
incoming connections. A host, usually
a PC, wishing to communicate on the
CAN bus opens a connection to this
port. The CANPipe could theoretical-
ly handle numerous clients; however,
its ability to monitor all the traffic on
the CAN side at the same time would
start to suffer.

The software currently allows up to

three hosts to connect at once. After a
client connection is established, the
client and server can begin to send
commands to each other for transmit-
ting and receiving CAN messages and
setting filters. Table 1 is a list of the
commands and their formats. When
clients first connect, they are immedi-
ately able to begin transmitting mes-
sages to the bus; however, they will
not receive any of the CAN bus traffic
until at least one filter is enabled.
Each filter consists of a mask value
and a match value that is used to check
against each that appears on the bus to
see if a client wishes to receive it.

The CANPipe sends heartbeat mes-

sages to each connected client every
few seconds and expects an echo
message back from each one. If a set
number of echoes are missed, the
socket is closed so that the server
can clean up the sockets it didn’t ter-
minate properly. Applications on the
client side can also use heartbeat
messages from the server to tell the
difference between a quiet CAN bus
and a stalled TCP/IP connection. The
exact time between heartbeats and the

allowable number of missed echoes
can be configured.

CONTROL PANEL

The first working version of the host

PC software was written in Python
using the wxPython windowing tool
kit. Python is my language of choice for
writing applications on nonembedded
systems because of its clean syntax,
good libraries, and cross-platform sup-
port. The result is a simple graphical
application that I wrote in a weekend.

Figure 1—The collision avoidance protocol used by nodes on a CAN bus

ensures that the highest priority message will be transmitted without interruption.
This gives messages guaranteed latency that depends on their assigned priority.

CAN ID

0×4B5

0×4B6

0×500

Stops sending

Stops sending

SY
NC

10 9 8 7 6 5 4 3 2 1 0

Message format

The format for messages to and from the server (different from CANBus messages) is <1 byte command><1
byte length><0 or more message bytes>. The length byte is the length of the entire message, including itself
and the command byte.

Valid commands to the server

0x01

Transmit CAN message with standard (11 bit) ID <2 byte ID><0-8 bytes data>

0x02

Transmit CAN message with standard ID and RTR flag * same format as 0x01

0x03

Transmit CAN message with extended (31 bit) ID * <4 byte ID><0-8 bytes data>

0x04

Transmit CAN message with extended ID and RTR flag * same format as 0x03

0x05

Set message filters, sets up one to four filters on incoming messages. Replaces previous filters.
Setting filter count to 0 eliminates filters (no messages forwarded) <1 byte filter count><4 byte 1st
mask><4 byte 1st filter><4 byte 2nd mask><4 byte 2nd filter> …

0x10

Heartbeat echo. This should be sent after each received heartbeat from the
server. Missing a set number will cause the connection to be dropped

0x11

Drop connection. Ends the connection gracefully.

0x20

Set time, sets the RTC on the CAN bridge
<1 byte sec><1 byte min><1 byte hr><1 byte day><1 byte mon><2 byte year>

Commands sent by the server

0x01–0x04 Forwarding CAN message, same format and message type as commands detailed above.
0x10

Heartbeat from server, sent at configured interval (5 s).

0x25

Message filter error, filters reset. This error message can be triggered by adding more filters than
the server is configured to handle.

Table 1—The CANPipe acts as a TCP/IP server that hosts can connect to for sending and receiving CAN mes-

sages. This requires a protocol for both the CAN messages and other commands from the hosts to the device.

CAN Message

For arbitrating access to the bus between the nodes,

CAN uses a unique collision avoidance scheme that
ensures the highest priority message will get through. It
relies on the fact that the CAN bus uses dominant (bit 0)
and recessive (bit 1) states to transmit information. In
this respect, it is like an open-collector line, where one
or more drivers can simultaneously pull down the line.

The CAN bus data lines are only in the recessive state
when all nodes are transmitting recessive bits.

The message arbitration scheme works by having all

nodes that currently want to transmit begin at the same
bit time. Starting with the second bit, each node begins to
transmit the message ID. After sending each bit of the ID,
the nodes check to see if what they sent is what’s actually
on the bus. If a dominant state (0) exists when the node is
sending a recessive bit (1), then it knows a higher priority
message is being transmitted and it waits until the next
frame to try sending its own message again.

Figure 1 illustrates how this works. This arbitration

scheme helps synchronized data collection work
smoothly. First, a high-priority time sync message is
sent out at precise intervals. Sensor nodes can then store
their readings at that point and attempt to transmit
them. All of the messages are then sent out in an orderly
fashion without jamming the bus.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

17

Photo 3 is a screen shot of the main

window with the Transmit CAN dia-
log box. The control panel application
displays a list of all received messages
and lets you transmit CAN messages
and set up filters. In its current state,
it’s a nice tool for analyzing CAN traf-
fic and inserting messages onto the
bus. I may expand it later to support
logging certain messages to a file, but I
won’t add much more than that.

The code that actually handles the

connection between the PC and the
CANPipe device is encapsulated in a
separate library (see Listing 2). The
intention is to use it in Python scripts
that can be easily tailored to the data
collection needs of a particular exper-
iment. The basic control panel appli-
cation still will be useful as a debug-
ging tool, but I am actively avoiding
the temptation to try and create a
huge, bloated, GUI application that
can do everything. After all, the whole
point of this is to get back to design-
ing machinery.

THERMOCOUPLE NODE

The CANPipe device allows a PC to

send and receive messages on a CAN
bus through a TCP/IP connection, but
CAN is not interesting with only one
device talking to itself. Actually, CAN
doesn’t work at all with only a node
because the protocol depends on other
nodes acknowledging a transmitted
message. To give the CANPipe some-
thing to do, and to stick with the origi-
nal intent of this project, I also con-
structed a thermocouple interface node
for it to talk to.

Thermocouples are a cheap, simple

way to take surprisingly accurate tem-
perature measurements. They are espe-
cially suited for measuring surface tem-
perature at several points in a system.

Up to eight type K thermocouples

can be plugged into the node device.
The signals are routed through an ana-
log multiplexer and fed into a special-
purpose amplifier and cold-junction
compensator IC. Then they are digi-
tized and can be transmitted across
the CAN bus on command.

THERMOCOUPLES

A thermocouple is a commonly

used temperature sensor. Its populari-

ty is partly due to it being a cheap,
rugged, and simple device. It is, after
all, nothing more than a pair of wires
composed of different alloys that are
connected at the temperature-sensing
end (see Figure 3).

A thermocouple generates a small

voltage across the other end of the two
wires, which is proportional to the
temperature difference between the
two ends. This is the result of the
thermoelectric effect, which I don’t
pretend to fully understand. The volt-
age is tiny (40 µV per 1°C), and so it
must always be amplified.

A trickier problem with thermocou-

ples is the fact that they only sense
relative differences in temperature. In
order to get an absolute measurement
at one end of a thermocouple, the
actual temperature at the other end
must be known. To simplify the final
measurement, a common technique is
to use a different type of temperature

sensor, such as a thermistor, to con-
trol an offset voltage that creates an
absolute temperature signal when
added to the thermocouple. This is
known as cold-junction compensation.
The AD595 chip used in this project
has an internal thermistor that per-
forms this task along with amplifying
the combined signal to a usable level
(10 mV per 1°C).

BOARD CIRCUITRY

For the CANPipe, I interfaced an

SJA1000 CAN controller chip to the
Rabbit 3000 microcontroller.
Although there are a number of sys-
tems offered with a CAN controller
built into the chip, I chose this route
because I’m familiar with the Rabbit,
which was a good fit for this applica-
tion. For this device, I picked my other
favorite microcontroller system, the
Atmel AVR, and had to add a separate
CAN controller chip again. Although
this created more hardware expenses
and space, it was still worth it for me
to use the familiar AVR instead of
starting over with something new.

The circuitry for this project is sepa-

rated into two boards. The first one is
the controller board, which contains
an ATmega8 microcontroller, an
MCP2510 CAN controller, and an
MCP2551 CAN transceiver (see

Chromel wire

Alumel wire

T

COLD

T

HOT

V

Photo 3—This application communicates with the CANPipe device and displays all of the traffic on the bus.

Figure 3—Two wires composed of different alloys are

connected at one end to make a thermocouple. The
voltage present at the unconnected ends of the wires is
proportional to the difference in temperature between
each end of the device.

background image

18

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Figure 4). It has headers for two CAN
bus connectors, an in-circuit program-
ming interface, and an SPI interface to
the sensor board.

The ATmega8 has 8 KB of flash pro-

gram memory and 1 KB of RAM. It
runs in the circuit with an 8-MHz
clock. This is plenty of horsepower for
the application. I was able to write the
code in C using the GCC AVR port
and the extremely nice WinAVR
development package. AVR-GCC and
the WinAVR package are both free and
open source. The quality of these tools
is a major reason why I have stuck
with the AVR.

Atmel doesn’t offer integrated CAN

controllers on any of its AVR chips.
Therefore, I interfaced the ATmega8
to Microchip’s MCP2510 CAN con-
troller, which has an SPI host inter-
face. The other option would have
been to use the SJA1000, with its
faster parallel bus interface. However,
I am running the CAN bus at only
125 kbps, and I do not plan to have
the thermocouple node transmitting
data more than a few times a second,
so the speed isn’t necessary. Moreover,
the SJA1000 in a DIP package is larger
than the MCP2510. The higher pin
count for the interface would have
required a larger AVR chip too. I
haven’t made the leap to surface-mount
construction for my home projects just
yet, so the difference is substantial.

The sensor board uses an ADS7818

ADC to digitize the signals and transmit
them back to the controller board (see
Figure 5). It also has an AD595 thermo-
couple amplifier, and an ADG507 ther-
mocouple multiplexer to sequence the
different channels into the amplifier and
ADC. There is also an RC filter on the
amplifier output. A healthy sprinkling
of bypass capacitors is used in an effort
to keep as much noise as possible away
from the tiny thermocouple signals.

The ADS7818 as a single-channel,

12-bit ADC with an internal voltage
reference that comes in an eight-pin
package. It interfaces to a host con-
troller with an SPI-like bus. A digi-
tized result is clocked out serially
after signaling a conversion using the
*CONV pin. However, this is not the
same as an SPI CHIP SELECT signal,
as I learned the hard way. Only a short

active-low pulse is needed to get the
ADC to start clocking out data.
Treating the *CONV signal like a
CHIP SELECT by keeping it low caus-
es the chip to repeat the data in
reversed-bit order, even after the
*CONV signal goes high again.
Because the ADC shares the SPI bus
with the MCP2510 CAN controller,
this created a lot of confusion. It was
the wrong assumption to make, and a
closer read of the datasheet would
have saved me a lot of time.

The AD595 thermocouple condi-

tioner chip outputs 10 mV per 1°C. It
is designed to run on an extended
range, split power supply for tempera-
tures above 500°C (5,000 mV output)
and temperatures below 0°C, which
create a negative voltage output.

To get signals from the ADS595 in

the 0- to 5-V range, I had to use the

chip’s adjustment pins. A voltage refer-
ence (U5) and resistor (R4) input a fixed
current of approximately 10 µA into
the T+ pin, shifting the 0° reading up
by approximately 250 mV. Another
resistor (R1) is hooked up to run in par-
allel with the internal feedback resist-
ance in the final amplifier stage of the
chip. This reduces the output to
approximately 5 mV per 1°C. The
result is that temperature ranges from
–50° to 950°C will produce outputs
within the 0- to 5-V range of the ADC.

Note that none of these adjustments

are calibrated. I used standard 5% tol-
erance resistors. The intent is to rely
on software calibration to produce
conversion constants that can be
stored in nonvolatile memory by the
controller. In this current stage of the
project, the node transmits its read-
ings as raw ADC values. The calibra-

Listing 2—Python is a good language for both quick, dirty scripting and application development. It has

a clean syntax and encourages an object-oriented programming style.

class CPClient:

def __init__(self):

self.sock_lock = threading.Lock()

self.list_lock = threading.Lock()

self.connect_flag = False

self.loopback = False

self.rx_msg_list = []

self.filter_list = []

def __del__(self):

self.close()

def _send_command(self, command, data):

if self.is_connected():

message = chr(command) + chr(len(data)+2) + data

self.sock_lock.acquire()

try:

self.sock.sendall(message)

except socket.error:

self.sock.close()

self.sock = None

print “Socket error, closing”

self.sock_lock.release()

def _get_messages(self):

buffer = “”

while self.is_connected():

#keep listening for incoming messages

try:

buffer += self.sock.recv(100)

except socket.timeout, socket.error:

continue

#just try again

while len(buffer) >= 2:

if len(buffer) >= ord(buffer[1]):

#at least one full message is in the buffer

code = ord(buffer[0])

length = ord(buffer[1])

self._handle_message(code,buffer[2:length])

buffer = buffer[length:]

else:

break #listen for rest of message

background image
background image

20

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

tion and conversion is done on a PC,
but the idea is the same.

Another thing to notice on the

schematic is diode D1. There is a
small bias current to ground from the
DB input on the AD595. If a thermo-
couple end is not grounded, this input
must be connected to ground to pre-
vent the pin from saturating.
However, if DB is directly grounded
on the board and connected to a long
thermocouple wire that is also ground-
ed, a large ground loop is set up that
introduces a lot of noise into the sig-
nal. The forward drop of the diode will
block a ground loop current and hold
the DB pin at 0.6 V when there is no
other ground connection.

Unlike the controller board, the sen-

sor board was not printed. Instead I
used a small protoboard and point-to-
point wired the components. Although
this was a pain and it contributed to
some system reliability problems, I
thought it was necessary because I
was least confident about this part of
my design. If I had it to do over again,
I would prefer to make a printed
board; but then again, the numerous
changes I ended up making along the
way would have been much more
expensive and time-consuming.

By separating the device into two

boards, I was able to design a more
generic controller board that potentially
can be used in future CAN bus sensor
node designs. It was also good because
the sensor board went through a num-
ber of revisions. The trade-off was a
larger and more expensive system. But
design flexibility is ultimately more
important for this project.

AVR FIRMWARE

This first version of the node software

has two basic tasks: reading in values
from the sensor board and transmitting
those values on command over the CAN
bus. Using AVR-GCC, almost all of the
code for this was written in C with the
exception of a low-level SPI block
transfer routine that was written in
inline assembly for speed (see Listing 3).

Getting a temperature reading from

one of the thermocouple channels is
done in several steps. First, a small
delay is needed to overcome the rise
time of the RC filter on the AD595

output and to give the alarm output
time to trigger if there is an open ther-
mocouple circuit. After this delay, the
system checks to see if the open ther-
mocouple alarm is active. If not, the
signal is sampled 10 times by the
ADC, and the multiplexer is switched
to the next channel to be sampled.
The 10 samples are averaged to reduce
noise. This is then stored as the cur-
rent reading. The node device reads a
channel approximately 30 times per
second, so all channels are scanned
every 0.25 s. A final sampling rate of
4 Hz is fine for most temperature meas-

urements. It would be possible to speed
up the sampling rate, but it isn’t neces-
sary for this application. The possible
increase in signal noise is not worth it.

When the node receives a data sync

message (ID 0x010) on the CAN bus,
it stores all of the current readings in
a transmit buffer and begins to trans-
mit each of the eight readings in sepa-
rate messages. While this occurs, it
still reads in new values.

HARDWARE CONTRUCTION

Like the CANPipe, this device will

be used outdoors, so I enclosed the

Listing 3—This routine was written in in-line assembly to speed up SPI transfers from the AVR to the ADC

chip. The SPI transfer is done in two phases to efficiently handle a command followed by a data transfer.

#define ASM_SPDR 0x0F

#define ASM_SPSR 0x0E

/*

routine to read/write data to a slave. Enable/disable of chip

select must be done before/after a call to this function. Data is

tranferred in two stages. First, some data can be written without

reading anything back. Next, a second buffer can both write out

data and simultaneously read bytes in.

iwbuffer - first stage buffer, bytes will only be written

iwlen - number of bytes in first stage

rwbuffer - second stage buffer, bytes will be transmitted and

then overwritten with the corresponding received byte.

rwlen - number of bytes in the second stage

*/

void spi_transfer(char *iwbuffer, char iwlen, char *rwbuffer,

char rxlen)

{

asm volatile(

"tst %1"

"\n\t"

"breq asm_spi_transfer_rw"

"\n"

"asm_spi_transfer_loop1:"

"\n\t"

"ld r0, Z+"

"\n\t"

"out %4, r0"

"\n"

"asm_spi_transfer_wait1:"

"\n\t"

"sbis %5, 7"

"\n\t"

"rjmp asm_spi_transfer_wait1"

"\n\t"

"dec %1"

"\n\t"

"brne asm_spi_transfer_loop1"

"\n"

"asm_spi_transfer_rw:"

"\n\t"

"tst %3"

"\n\t"

"breq asm_spi_transfer_end"

"\n"

"asm_spi_transfer_loop2:"

"\n\t"

"ld r0, Y"

"\n\t"

"out %4, r0"

"\n"

"asm_spi_transfer_wait2:"

"\n\t"

"sbis %5, 7"

"\n\t"

"rjmp asm_spi_transfer_wait2"

"\n\t"

"in r0, %4"

"\n\t"

"st Y+, r0"

"\n\t"

"dec %3"

"\n\t"

"brne asm_spi_transfer_loop2:"

"\n"

"asm_spi_transfer_end:"

"\n"

:

: "z" (iwbuffer), "r" (iwlen), "y" (rwbuffer), "r", (rxlen),

"I" (ASM_SPDR), "I"(ASM_SPSR)

: "r0"

);

}

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

21

hardware in an aluminum box (see
Photos 4a and b). Thermocouples con-
nect through eight mini jacks on the
top of the box. The only other cutouts
in the box are the two DE-9
connectors for the CAN bus,
which also brings 12 V of
power to the device.

Eight pairs of thermocouple

wires are soldered directly to
the pins of the muliplexer chip
on the sensor board, while the
other ends connect to screw
terminals on the backsides of
the thermocouple jacks. A type
K thermocouple is made up of
chromel and alumel wires. I
had some difficulty making
good solder joints with these
metals, so I ended up with
some weak joints that came
loose later on. A high soldering
temperature seemed to help
with this, but it isn’t very
healthy for the multiplexer IC.

HOST INTERFACE

I have already discussed the

CANPipe and the control panel inter-
face that runs on a PC. The control
panel is a generic tool for sending and
viewing messages on the CAN bus. For

the thermocouple interface node, I used
the existing CANPipe interface library
to create a simple temperature monitor
application (see Photo 5). It isn’t much,
but it doesn’t have to be. One of the
ideas behind the SCADA system I am
building is that the data collection soft-
ware on the host does not have to be a
full-fledged, do-everything application.
I could easily spend several months
trying to write such a thing. Instead,
small programs specific to an experi-
ment can be written as needed. By con-
tinuing to build up the Python libraries
I have already written, I can make the
process of writing new application-spe-
cific programs simple and fast.

KEEP IT SIMPLE

Temperature is a fundamental prop-

erty of a system that must be measured
for almost any controlled experiment;
therefore, the thermocouple node was
chosen as the starting point for my
homebrew SCADA system. Naively, I
had hoped that this would be a simple
one to build. Getting the bugs out of
the node controller system while also
trying to separate noise from micro-
volt signals ended up requiring a fair

amount of time and effort.

Although having eight thermocouple

channels in one box is nice, I would pre-
fer to make smaller individual nodes

Figure 5—The sensor board connects to the controller board through an SPI bus. It contains circuitry to demultiplex, amplify,

and cold-junction compensate the thermocouple inputs, along with a 12-bit ADC.

Figure 4—The controller board contains the AVR controller and the CAN bus circuitry. It was designed as a generic

controller board that can be used in several different nodes.

background image

22

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

with only one or two points in the
future. Getting all eight channels work-
ing and tested along with the input sig-
nal problems associated with scanning
through channels reminded me of why I
pursued a distributed model of the
SCADA system. Even though keeping
the nodes small will require me to build

more of them, the price in redundancy
is worth the gain in simplicity.

CANPipe SOLUTION

When data acquisition is a priority,

your desktop PC is a great tool for the
final collection and storage step. TCP/IP
over Ethernet is a standard way to trans-

fer bulk data between higher-end com-
puter systems. Neither is good for real-
time data collection in a harsh environ-
ment. This is where the CANPipe
comes in handy. Relatively cheap sensor
nodes can be networked together on a
real-time industrial bus, and all of the
data they produce can make its way to
a PC sitting safely indoors.

I

Author’s Note: Atmel recenly released
a new AVR device, the AT90CAN128,
which has an on-chip CAN controller.
This makes the CAN controller cir-
cuit described here with the separate
CAN controller IC unnecessary for an
AVR-based CAN node. I would like to
thank Alex Wolfing for his help with
the design and Bill Sprouse for assist-

ing with the SJA1000 driver code.

Photo 4a—As you study the guts of the thermocouple node, note that the controller board with the AVR is on the

left. The prototyped sensor board is on the right. b—The thermocouple node is finished. The DE-9 connector on

the lower side of the box carries power and CAN bus signal lines.

a)

b)

Charlie Krauter lives in Sacaramento
with his wife Sarah and their strange
friend Paul. He has been working as a
software engineer at Z-World for the
past four years. Charlie has a B.S. in
Physics from the University of

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

23

SOURCES

AD595 Thermocouple amplifier,
ADG507 thermocouple multiplexer
Analog Devices, Inc.
www.analog.com

AT90S4433 Microcontroller
Atmel Corp.
www.atmel.com

MCP2551 CAN Transceiver
Microchip Technology, Inc.
www.microchip.com

SJA1000 CAN Controller
Philips Semiconductors
www.semiconductors.philips.com

RCM3700 RabbitCore
Rabbit Semiconductor
www.rabbitsemiconductor.com

ADS7818 ADC
Texas Instruments, Inc.
www.ti.com

Photo 5—This application on the host PC is for displaying the thermocouple input results. WxWindows and Python

make it relatively easy to create display and logging applications for different needs.

PROJECT FILES

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

California, Davis and a B.S. in
Mechanical Engineering from California
State University, Sacramento. His inter-

ests include thermodynamics and gen-
eral tinkering. You may contact him at
charlie@fleacat.net.

background image
background image
background image

26

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

E

ach day more and more people

spend time sitting in front of comput-
ers. Engineers who design computer-
human interfaces are constantly look-
ing for new ways to enhance the man-
ner in which this communication is
made. This means you’ll probably see
new designs for mice, trackballs, key-
boards, and related tools.

With this in mind, I designed the E-

Field Serial Touchpad for the 2003
Motorola E-Field Sensor Contest. In
this article, I’ll show you how to build
a touchpad to replace your everyday
mouse. Although most laptops have
touchpads, you’ll see that you can
now customize your own with a sim-
ple microcontroller and a Motorola
MC33794 e-field sensor.

PAD BASICS

In addition to the MC33794, my E-

Field Serial Touchpad includes an
MC68HC908JK3 8-bit microcontroller
and a MAX232 for RS-232 protocol
communication with the PC’s serial
port, Unlike common mice, the touch-

The plastic tape serves as an adhesive

for the materials as well as an insula-
tion layer between the electrodes and
your finger. This isolation must be
kept in order to ensure a correct
response. Direct contact will eventual-
ly sink the skin’s ionic charge and
you’ll lose the signal. The insulation
barrier prevents this from happening;
it provides a better response because
the e-field sensor detects electric field
modification.

The pads are isolated (see Figure 1).

This is also useful for permitting a par-
tial field interference, which at the same
time allows a variable signal to be
detected. Just imagine the tip of your
finger resting between the lines. The
equivalent finger seen by each pad will
be half a finger, which will give you
half-field detection. This represents dif-
ferent motion magnitudes by the cursor.
Figure 2 shows the sensor’s layers.

HARDWARE

The prototype chipset is made of a

microcontroller, the e-field sensor, and
the RS-232 driver. This can be
observed in Figure 3, where the basic
layout suggested in the datasheets was
implemented. The RS-232 driver con-
nection is made through the TX pin
and digital ground. The analog ground
is tied to the digital ground, but only
at one point. In a printed circuit lay-

E-Field Serial Touchpad

FEATURE ARTICLE

by Erwin Saavedra

pad uses an external power supply
rather than energy from the serial port.

The other important piece of hard-

ware is the pad itself. This is the fun
part because you can design various
layouts for different kinds of responses.
Well, you also need software power to
do this. Figure 1a shows a sketch of my
touchpad design. (Figure 1b shows a
different possible layout for achieving
more complex responses.) The outer
area represents up, down, left, and right
movements. The center area is for rest-
ing and clicking. Gently slide the tip
of your finger across each section to
move the cursor. Tap the center to
make a selection.

Strong cursor movements are achieved

by placing your fingertip completely over
a particular section of the touchpad.
Leaving part of your finger between two
areas directs partial and slower move-
ments. This is because the equivalent
capacitance is proportional to the area of
exposure. In the completed project, the
velocity of the cursor is dictated by the
refresh rate, which is software con-
trolled. Refer to the application notes
listed in the Resources and References
sections of this article for more informa-
tion about the MC33794 and its use in
other touch panel applications.

The pad has a hard acrylic body.

The design also includes a cardboard
sheet, aluminum foil, and plastic tape.
I didn’t use glue when I built the pro-
totype. I wanted to avoid the buildup
of isolation material between the
wires. Nevertheless, an insulation bar-
rier with a higher dielectric constant
provides better sensitivity.

[1]

So, who

knows, maybe the glue would help.
I’ll leave that to you.

Want to get rid of that mouse? Erwin’s MC33794-based E-Field Serial Touchpad is the solu-
tion you’re looking for. The pad connects to your PC’s serial port. Simply drag your fingertip
across the aluminum pad and tap gently to initiate a command.

Figure 1a—My touchpad design is a simple one. You
can make up, down, left, and right movements and
everything in between. Tap the center to make a selec-
tion.
b—As an alternative, you can design a pad with
more possible directions. Avoid exceeding the total
number of channels (nine), or you’ll have to use anoth-
er MC33794 or multiplex.

Cable

Figure 2—The layers of the pads look like this. Remember
to add the isolating material for getting a good response.

a)

b)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

27

the 10-MHz oscillator and readjust fre-
quency-dependent routines, such as the
SCI protocol routine. If the implemen-
tation is to be added to a device other
than a PC, it is probable that the RS-
232 driver is unnecessary because the
pad will be connected directly to the
main board. This further improves the
cost-benefit relation of the touchpad.

SOFTWARE

The prototype is noisy because the

electronic chipset was built in a noise-
rich environment and the touchpad was
built with everyday materials. Let’s go
over some ways to reduce the noise.

The MC33794 provides a SHIELD

signal to reduce noise in the electrodes
cable. This is especially beneficial
because it allows for the use of more
than 1 m of cable without adding con-
siderable noise.

Additional noise comes from the

board’s contacts, power supply, and
other physical sources. Two software
techniques involving the initialization
block and value rounding can help
combat these sources of noise.

The initialization block is in charge

of initializing the SCI, the mouse, and
the MC33794 (see Figure 4). For the
SCI, the initialization routine loads
appropriate values in the timer for
1,200-bps generation. Besides this, it
also establishes 7 bits, 1 stop bit, and
no parity protocol.

[2]

For the mouse,

the initialization block preloads the

out, this should be done as close as
possible to the power supply to avoid
noise. Because the prototype was
implemented in a noisy environment,
no effort was made to monitor the
supply’s pins. In a more formal imple-
mentation of the project, this should
be taken into account to reduce noise
in the readings.

I didn’t use the MC33794’s watchdog

timer, lamp, and ISO communication
modules. I didn’t use the SIGNAL pin
either, but you might want to incorpo-
rate it for your application.

In order to avoid high costs, and

because my project doesn’t require
extended precision, I didn’t use op-amps.
As a result, the LEVEL signal directly
enters the microcontroller’s ADC pin.
Tests indicate that the offset value in
the LEVEL signal goes from 2.9 to 3.2 V.
The active signal range is approximately
–1.8 to 1 V. Although the reference pins
were added, the implementation does
not use them because the maximum
absolute mouse step is 127 pixels and

the value itself is divided by four to
avoid jumps. The best-case scenario will
lead to a 23-pixel move. In other words,
amplification isn’t needed because the
values already fit in the desired margin.
Precision isn’t critical in this design.

Finally, I left the DIS_SHIELD at

zero in the prototype because I didn’t
use coax cable (or any shielding). A
more formal implementation would
involve shielding the pad’s cable in
order to prevent noise. You could also
make the microcontroller control
them in order to test for malfunctions.

I used an external power source

because of the sensor’s need for high
voltage. A charge pump or DC-DC con-
verter may be used to obtain energy
from the serial connector, but be careful
not to pass the 10-mA limit. One way
to do this is using a MC68HC908QY4
instead of a MC68HC908JK3 because it
has a smaller pin count and an oscilla-
tor that can be trimmed internally. (I
happened to have the ’QY4, so that’s
what I used.) Another way is to reduce

Figure 3—A simple sensor interface and the SCI module (not shown) comprise the schematic. Avoid the connector
if you build a single two-sided board, implementing the metallic contacts in it (imagine a very slim mouse).

Start

Initialize

Stable?

Sample

Process

Event?

Send

N

Y

N

Y

Figure 4—The main program’s flow chart is simple. The
initialization block also can contain a plug-and-play routine.

background image

28

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

three default values for the mouse
protocol (see Table 1). These 3 bytes
are sent every time an event happens.
The values for the x and y positions are
given as two’s complement. The code
takes this into account and performs a
nega instruction in the value for left
and down movements. Listing 1 shows
the two cases: positive and negative
movements. The shifting instructions
perform the rounding. Dividing by a
factor of eight makes the cursor move
more smoothly and slowly. It also fur-
ther reduces noise. In practice, the sig-
nals end up having magnitudes from
one to 16. Also note that in the nega-
tive case, zero is forced in the sixth bit
because the x and y bytes must begin
with a zero (see Table 1).

Finally, for the MC33794, the initial-

ization routine loads the initial value
into the variables. It also performs a sta-
bilization loop to prevent misreadings
because of power-up (see Figure 5).
During this process, the channels are
continuously sampled until the sum
of the errors—the absolute difference
between present and past samples—is
less than the established threshold
(ACERROR). The routine also records
the mean value for each channel inde-
pendently. Thus, you must not touch the
pad until the indicator LED indicates
that the initialization process is finished.

After initialization is completed, the

acquisition block acquires samples. Only
the first five channels were analyzed in
the project. Every time a sample is
taken, a stabilization delay is executed,
permitting the sensor’s circuitry to work
correctly. Each sample is subtracted from
the mean measure of its respective chan-
nel, and then saved in the array. There
are two arrays: EFMDATA stores the
mean values of the channels and offsets;
EFDATA stores the current absolute
channel difference, which is called the
error in the initialization process.

Button detection, which is performed

by a rustic high-pass filter, is achieved
with the instructions shown in

Listing 2. The constant

BUTTONTHR

performs this event. It decides if the
signal is to be filtered or passed.
Basically, the routine detects a high dif-
ference (high slope) between samples of
the button channel. If the high differ-
ence is repeated continuously, indicat-

ing the presence of a high-frequency
signal, a button event is generated.

Finally, the transfer block performs

the data process for deciding what to
send back. It also implements the seri-
al transmission process. Simply com-
paring the magnitude of each signal
decides a command. However, priority
is given in this implementation to
each signal. In other words, if the up
arrow is used, it doesn’t matter if the
down arrow is also used. It won’t be
read. I did this to ensure proper testing
functionality. You can modify the
design to handle more pads. Note also
that the signal magnitude is divided.
This can be changed in order to pres-
ent more gain or improved movement.
You may download the complete code
from the Circuit Cellar ftp site.

The last issue to consider is the

refresh rate, which is important
because it avoids jumps in the cursor’s
position, thus making it difficult to
follow and locate. For example, a mag-
nitude of 20 pixels and a refresh rate
of 1 s make the cursor jump 20 pixels

every second. This is an annoying
process. To solve this problem, select
a higher refresh rate.

The refresh rate is implemented in

software by delays, as specified in the
code comments. Eliminating these
delays increases the refresh rate,
which is useful. But make sure the
cursor doesn’t move too fast. The
minimum refresh rate time depends
mainly on the setting time needed for
reading the sensor’s channels. The
computation doesn’t take long.

PROTOTYPE

My results were acceptable (see

ACERROR = 0

Sample

Sum of the absolute
difference for every
channel between the
actual and last value

< ACERROR?

N

Y

Figure 5—The stabilization algorithm is a variance cal-
culation routine. It can be overrun if the sensor is
mounted on a noise-free board.

Byte 1

Control

1 B1 0 B2 Y7 Y6 X7 X6

Byte 2

X position

0 X5 X4 X3 X2 X1 X0

Byte 3

Y position

0 Y5 Y4 Y3 Y2 Y1 Y0

Table 1—This is as simple as it gets. These bytes are
sent to the PC to show button action or movement.
They’re sent only after there’s been some movement.

Listing 1—The shifts in this routine, which analyzes finger activity, reduce noise. You can modify them to suit
the amount of noise in your application.

.

.

lda

EFDATA+1

clc

rora

asra

asra

tsta

beq

next1

sta

MOUSEY

jmp

mup

next1

lda

EFDATA+2

clc

rora

asra

asra

tsta

beq

next2

nega

and

#%00111111

sta

MOUSEY

jmp

mdown

.

.

background image
background image

30

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Photo 1). Be careful when you connect
the hardware. I recommend that you
install a serial mouse beforehand because
the software doesn’t include plug-and-
play capability. This is an important
issue that requires further analysis.

The pad is easy to use. It’s similar to

the touchpads on laptops. Its only
shortcoming is that corner-to-corner
movement is difficult. I blame this on
the software. You can modify the code
to suit your needs.

There’s plenty of room for improve-

ment. To start, you can further mini-
mize the noise by building a better
pad and using quality PCBs. You can
minimize the current consumption by
using a smaller microcontroller. I used
less than half of the GPIOs on the
MC68HC908JK3. Reducing the crys-
tal’s frequency can help this too.

REFINEMENTS

I’ll leave the fun part to you. Consider

the project a success if you can con-
vince your neighbor to replace his pad.
Convincing him to switch to your
design depends on what you do to
make your pad different.

As I see it, there are only two areas to

work on, the pad and the software. As
for the pad, consider creating a colorful
design that includes figures or cartoons.
Another consideration is the sensor lay-
out. A helix design would work well for
a child. As the child moves his or her
finger from right to left, the pointer
would draw an arc rather than a straight
line. For a more serious user, think
about creating a pad with several
degrees of velocity. Or maybe build a
pad with special locations where you
can double-click without tapping.

Finally, don’t underestimate the

software. The software
is what allows you to
differentiate your pad
from others. I tried to
keep the software as
simple as possible. As
you know, I can’t move
the cursor from corner
to corner. But you can
do it. Another idea is to
interpret complex finger
movements. For
instance, if you draw a
circle, a shortcut to Alt-

F4 occurs and the current window closes.

You can try anything. The impor-

tant point is that you can now cus-
tomize your own pads. You don’t have
to rely on big companies do it for you.
Use your imagination. The possibili-
ties are limitless.

I

Listing 2—The button detection routine surely needs your imagination! Here, there’s a hard implementation
for a high-pass filter. I used this routine because it’s fast, but there are better ways to handle it. If you want to,
you can implement a turbo function similar to the old video game consoles.

.

.

lda

EFDATA

clc

rora

asra

asra

psha

sub

PBUTTON

bhi

next4a

nega

next4a

cmp

BUTTONTHR

blo

next5

pula

sta

PBUTTON

inc

BUTTONCON

lda

BUTTONCON

cmp

#$02

blo

next6

clr

BUTTONCON

jsr

mbutton

jsr

mrelease

jmp

standby

next5

pula

sta

PBUTTON

clr

BUTTONCON

.

.

Erwin Saavedra earned a degree in
electronic engineering from the
Universidad Industrial de Santander in
Bucaramanga, Colombia, where he is
currently studying toward a master’s
degree in electronics. Erwin has worked
as an application engineer, an embed-
ded software designer, and a teacher.

REFERENCES

[1] Motorola, Inc., “E-Field Sensing:

An Alternative Solution to Control
Panel Applications,” rev. 0,
AN1985/D, 2003.

[2] Microchip Technology, “AN519:

Implementing a Simple Serial
Mouse Controller,” DS00519C,
1997.

RESOURCE

Motorola, Inc. “Electric Field Imaging
Device,” MC33794/D, rev. 6, 2003.

SOURCE

MC33794 E-field sensor,
MC68HC908JK3 microcontroller
Motorola, Inc. (now Freescale Semicon-
ductor, Inc.)
www.freescale.com

PROJECT FILES

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

Photo 1—I admit it’s messy, but it certainly works. With some surface-mount
devices, I turned my mouse into a credit card-sized portable peripheral.

His interests include embedded con-
trol, nonlinear control software, and
DSP software techniques. You may
contact Erwin at

esaavedra@ieee.org.

background image
background image

the system. A delta function—basically
an extremely tall, narrow pulse—is made
up of all the different frequencies in
equal amounts. When it passes through a
linear system, each frequency is affected
by the system separately. (This is known
as the superposition principle.) By look-
ing at the output’s fast Fourier transform
(FFT), you can see how each frequency
has been affected. It’s easy to use this
information to find the magnitude of the
system’s frequency response.

This method has a serious drawback.

Using a delta function (or a good approx-
imation of one) as the input can hurt
the system. We’re talking about using
a large voltage spike as the input.

Another way to test all frequencies at

once is to enter white noise. It too is
composed of all the frequencies in equal
amounts. In white noise, however, the
phases of the components at different
frequencies vary randomly. The problem
with using white noise is that you can-
not use an FFT to measure the spectrum.
Because you are measuring random
noise, you must be a bit smarter when
making your measurements. (Use some-
thing like the method of averaged peri-
odograms to make the measurement.)

[1]

Why doesn’t white noise have the

same problems as the delta function?
After all, they are both made up of
all the frequencies in equal amounts.
The answer has to do with the phase
of the component parts of the two
signals. In the delta function, the
phases of the different frequencies
are organized in such a way that at
one point the different frequencies
interfere constructively. That’s what
causes the large spike. In white
noise, the phases are random, which

causes the different frequencies to
add without hitting a high peak.

32

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

P

seudo-random noise is fake random

noise. It is not random; it is determinis-
tic. Deterministic random noise seems
to be an oxymoron. If you have deter-
ministic noise, you do not have random
noise. Nonetheless, the pseudo-random
noise we produce is deterministic in the
strictest sense. We give exact directions
for producing the signals. In what sense
can such signals be random? They can
be random if they have some of the
same properties as random signals.

Suppose you have a random sequence

of ones and zeros. What sort of behavior
do you expect to see from the elements
in the sequence? The first thing you
expect is that in a long subsequence
you will have roughly the same number
of zeros as ones. If the placement of the
ones and zeros at any given location is
done independently of the placement of
the ones and zeros at any other point,
then you would also expect there to be
no correlation between the value of the
subsequence at any given point and the
value at any other point.

Our recipe for constructing sequences

shows you how to produce sequences
that have properties similar to those
of random sequences. In any long
sequence, the number of ones and
zeros will be almost equal, and the
sequence will be almost uncorrelat-
ed with itself. In fact, you can prove
that the signal produced by our
recipe shares many other properties
with truly random sequences.

Previously, you learned how deter-

ministic random noise is used in
direct sequence in spread-spectrum
systems (S. Engelberg and E.
Shekalim, “Spread Spectrum: Theory
and Practice,” Circuit Cellar, Issue
156, 2003). In this article, we’ll show
you how pseudo-random sequences

Pseudo-Random Noise Theory and Applications

Shlomo and Haim’s ADuC812-based noise generation system produces noise on demand.
Read on to learn how you can use pseudo-random sequences for measurement purposes.

can be used as a measurement tool.

SAMPLE APPLICATION

If we can deliver on our promise to

produce deterministic random noise,
what can we do with the noise? First,
let’s consider how you can use truly
uncorrelated noise, which is also
known as white noise.

Suppose you have a linear filter and

want to know how it affects different
frequencies. The obvious way to test
this is to connect a signal generator to
the filter, apply sine waves of various
frequencies, and look at the output on
an oscilloscope. By comparing the
amplitude of the input and output sine
waves, you’ll find the magnitude of
the frequency response. Because of the
number of necessary measurements,
this method can be time-consuming.

There are many other ways to deter-

mine the magnitude of a system’s fre-
quency response. We’ll consider three.
All of the others involve entering all the
frequencies at once and looking at the
spectral content of the system’s output.

The first method used to determine

the magnitude of the frequency response
is to use a delta function as the input to

FEATURE ARTICLE

by Shlomo Engelberg & Haim Benjamin

Figure 1a—A three-cell shift register with feedback in this configu-
ration will produce a seven-element sequence.
b—This eight-cell
shift register with feedback will produce a 255-element sequence.

Ck

0

1

2

Three-cell shift register with feedback

Ck

0

1

2

3

4

5

6

7

Eight-cell shift register with feedback

a)

b)

background image

that are of interest to us.

We will not prove the

many results about such
sequences. For proofs,
refer to S.W. Golomb’s
Shift Register Sequences

.

We’ll explain why a
maximal length
sequence has almost as
many zeros as ones.

First, note that if you

list all the possible states
of a shift register, you’ll
see that ones and zeros
appear the same number
of times in each cell.
In a maximal length
sequence, you go through
all of the possible states
except the all-zeros state.
Thus, one must appear
one more time than zero

in any given cell in one
cycle of the shift-register.

As you know, a cycle has 2

n

– 1 elements,

so it has an odd number of elements.
Therefore, there must be either more
zeros than ones or one more one than
zero. The ones and the zeros are as
evenly divided as possible.

Other than this nice property, it’s

important to know that the autocorre-
lation of a maximal length sequence is
nearly a delta function. This property of
the autocorrelation is used to show that
the energy in the sequence is almost
evenly distributed among the frequen-
cies of which the sequence is com-
posed. (The amount of energy at DC is
different from the amount at the other
frequencies.) In white noise, the energy
is uniformly distributed among all fre-
quencies. Because our sequence is like
white noise in this way, our sequence is
approximately white too. This white-
ness is the property that we make use
of when measuring the magnitude of
the frequency response of a system.

SEQUENCE PRODUCTION

We’ve described one example of the

production of a maximal length
sequence. In general, you take a shift reg-
ister and feed back the XOR of several of
the cells to the shift register’s input. Let’s
consider some conditions that the feed-
back connections must satisfy.

First of all, if you have a shift regis-

last two cells is fed back into the first
cell. Suppose that cell 0 starts with a
one, and the other two cells start with
zeros. The progression of the values of
the cells is given in Table 1. Note that
the states start repeating themselves
after seven time steps.

Let’s consider the values in cell 0 in

one period over seven time steps. The val-
ues are {1, 0, 1, 1, 1, 0, 0}. Note that there
are four ones and three zeros. That is as
nearly balanced as you can get when your
sequence has an odd number of elements.

MAXIMAL LENGTH SEQUENCES

In general, if you have an n-cell shift

register whose next value is determined
by the current state of the cells, then the
states of the shift register must start
repeating after 2

n

time steps at most.

After all, there are only 2

n

possible states

of the cells and the next state is deter-
mined by the current state. Actually, the
number 2

n

is a bit too high if your feed-

back is the XOR of some of the cells in
the shift register. If all the cells are zero,
a zero is fed back and you’ll find that the
all-zero state cannot be part of a long
sequence of register value. The longest
possible cycle is 2

n

– 1 time steps.

Sequences of this type are called maxi-
mal length sequences. This is what we
got in the previous example (as 7 = 2

3

– 1),

and it’s precisely sequences like that

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

33

There’s a fourth way of

testing a system. Consider
a signal made up of all the
different frequencies but
in which their phases are
picked in such a way that
the resulting deterministic
signal has no high peaks. If
you use this signal as your
input, you can look at its
output and easily deter-
mine the magnitude of
the system’s frequency
response. This method
checks the entire frequen-
cy response at one time. It
does not involve high volt-
ages, and it doesn’t require
a truly random signal.
From the point of view of
a person coming to meas-
ure a system, this type of
signal is optimal. Its only
disadvantage is that it
seems like producing such a signal might
be difficult. But, as you’ll see, producing
such a signal (i.e., producing determinis-
tic random noise) is fairly easy.

IMPLEMENTATION

A method for producing pseudo-ran-

dom noise was developed in the 1950s.
It produces periodic pseudo-random
noise by using a shift register with linear
feedback.

[2]

This method is easily imple-

mented with a shift register. However, if
you want a flexible implementation, a
microprocessor is a better choice because
it allows you to make a variety of sys-
tem adjustments with minimal effort.

Let’s start with a description of the

method. Consider the three-cell shift
register in Figure 1. There are three
cells, and the exclusive OR (XOR) of the

Figure 2—Take a closer look at the schematic of the noise generation system. The LCD is a
DataVision DV-16400-S2FBLY. When a connector leads out the pins on a standard 8052 port,
the port number is given in addition to the connector information.

Time step

Cell 0

Cell 1

Cell 2

1

1

0

0

2

0

1

0

3

1

0

1

4

1

1

0

5

1

1

1

6

0

1

1

7

0

0

1

8

1

0

0

9

0

1

0

Table 1—This is the progression of the shift register’s
states. The states begin repeating after seven time steps.

background image

34

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

host of additional peripherals. It
has two digital-to-analog convert-
ers (DACs), an eight-channel ana-
log-to-digital converter (ADC, a
watchdog timer, 640 bytes of flash
memory programmable by the
microprocessor, and 8 KB of flash
program memory. The evaluation
kit has many other on-board
goodies. For this project, we used
many of the standard features of
the 8052 and one of the DACs.

We connected a keyboard to

the ADuC812 (via port 2) and a
standard 4 × 16 LCD screen (via port 0
and several pins of port 3). Refer to
Figure 2 for the precise connections
that you must make to the evaluation
kit to implement the noise generator.

After our noise generation program

has been downloaded to the ADuC812
using the Windows Serial Downloader
(provided by Analog Devices) and the
system is turned on, it welcomes you
and tells you to press any key to move
from screen to screen. The system then
proceeds to a screen that allows you to
choose the amplitude of the output
waveform. After a choice is made, you
can change your mind at any time. The
system outputs the noise through the
processor’s zeroth DAC. The system
also outputs a 5-V version of the
sequence through pin 4 of port 3. Refer
to Figure 2 for the precise location of
these signals in the evaluation kit.
Photo 1 is the system we used.

SPECTRAL PROPERTIES

Before describing how we used

deterministic random noise, you need
to understand more about its spectral

ter with n cells and you want a maxi-
mal length sequence, the element in the
last cell (the most delayed cell) must be
one of the elements that is XORed.
Otherwise, you might as well use a shift
register with fewer than n cells. The
sequence will not go more than 2

n – 1

– 1

steps without repeating itself.

Also, you must make sure that there

is an even number of cells that con-
nect to the XOR. In the case of an odd
number of connections, whenever all
the cells have ones in them, the feed-
back will allow that state to persist.
Thus, the longest possible sequence
will have a period of 2

n

– 2 steps, and

this isn’t a maximal sequence.

In practice, there is no need to search

for the proper connections to the XOR.
There are numerous lists of such connec-
tions.

[3]

From this recipe book, you’ll find

that if you’d like to use an eight-cell shift
register, there are several sets of connec-
tions to choose from. For example, you
could connect the eighth, seventh, sixth,
and first cells to the XOR (see Figure 1).
This configuration generates a sequence
that only repeats itself every 255 steps
(2

8

– 1 = 255 steps).

ADuC812-BASED SYSTEM

We could have implemented a

random noise generator using a
shift register and a bit of addi-
tional logic, but we decided to
use a microprocessor. This
allows us to make changes to
the system and control it easily.

We used Analog Devices’s Eval-

ADuC812QS, which is an evalua-
tion kit for the ADuC812, a
microcontroller with an on-board
digital-to-analog converter (DAC).
The ADuC812 is an 8052 with a

properties and the frequencies at
which the energy in the deterministic
random noise is located. The sequence
we used is a periodic sequence.
Because it’s periodic, the energy in the
signal is located at the harmonics of
the fundamental frequency, which is
the reciprocal of the period.

We used an eight-cell shift register, so

the there were 255 (2

8

– 1) elements in

each cycle. We produced a new element
every 0.5 ms. Thus, the period was
127.5 ms and the fundamental frequen-
cy was 7.8 Hz. Photo 2 shows the meas-
ured spectrum of the microprocessor’s
output (where each division represents
50 Hz). A careful look at Photo 2 shows
that there is roughly the right number
of peaks per division.

Because the noise we produce is

always one of two values and can only
change values at fixed intervals, the
noise is not white at high frequencies
(see Photo 3 for a picture of the output
of the system). The stepping makes
the spectral content lower at high fre-
quencies. It isn’t hard to show that
“high” means frequencies reasonably

close to the reciprocal of the
width of each step. (In the exam-
ple, the step length is 0.5 ms and
the relevant frequency is 2 kHz.)

MEASUREMENT

After you set up the system,

you are ready to start measuring
filter parameters. In our example,
we consider a simple RC low-pass
filter for which

τ

= RC = 0.5 ms.

We use our system to measure
the filter’s time constant by look-
ing at the magnitude of the fil-
ter’s frequency response. To

make these measurements, you

Photo 3—Here you see the periodic random noise (top) and the output
of the RC filter (

τ

= 0.5 ms) through which the noise was passed (bottom).

Photo 2—Note the uniformity of the peak heights in the spec-
trum of the periodic random noise.

Photo 1—As you study our system, keep in mind that
most of the cables used to connect the components
have been removed for the sake of clarity.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

35

need an oscilloscope that can perform
an FFT. We used the Agilent 54622D
mixed-signal oscilloscope.

We connected our system’s output to

one side of the resistor. The other side
of the resistor is connected to one side
of a capacitor, and we ground the other
side of the capacitor. We attached one
oscilloscope lead to the output of the
system and one lead to the point
between the resistor and the capacitor
(to the output of the low-pass filter).

After starting the system, the oscil-

loscope’s screen will look like Photo 3.
The top portion is the system’s out-
put; the bottom part is the filter’s out-
put. What is more interesting is the
output of the oscilloscope when it is
set to calculate the FFT of the input
and when it is set to calculate the
FFT of the output.

The FFT of the input is given in

Photo 2. The FFT (out to 500 Hz) is
almost flat-topped. This shows a prop-
erly white signal. More interesting is
the plot given in Photo 4. There you
can see the influence of the filter. It is
well known that the 3-dB down point
of an RC low-pass filter occurs at f =
1/2

πτ

. Because we chose a time con-

stant of 0.5 ms, we found that the 3-dB
down point ought to be at f = 318 Hz.
As you can see in Photo 4, the 3-dB
down point is indeed approximately at
this frequency.

NOISE PRODUCTION

Pseudo-random noise is easy to pro-

duce. Using a microprocessor, we
built a system that produces such
noise on demand. For our purposes,
pseudo-random noise has the advan-

tages of random noise and
delta functions all wrapped
up in one package. Using
an oscilloscope that can
calculate an FFT, we use
our noise-generating sys-
tem to examine the magni-
tude of the frequency
response of a system. You
can do so too.

I

PROJECT FILES

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

REFERENCES

[1] A.V. Oppenheim, et al, Discrete-

Time Signal Processing

, Prentice-

Hall, International, Upper Saddle
River, NJ, 1999.

[2] S. W. Golomb, Shift Register

Sequences

, Holden Day, San

Francisco, CA, 1967.

[3] New Wave Instruments, “Linear

Feedback Shift Registers:
Implementation, M-Sequence
Properties, Feedback Tables,”
www.newwaveinstruments.com/
resources/articles/m_sequence_
linear_feedback_shift_register_lfsr/.

Shlomo Engelberg received
his B.E.E. degree in 1988

and his M.E.E. in 1990. He
also holds an M.S. and
Ph.D. in Mathematics.

Shlomo is a senior lecturer in the elec-
tronics department at the Jerusalem
College of Technology—Machon Lev.
You may contact him at
shlomoe@jct.ac.il.

Haim Benjamin is an academic reservist
in the Israeli Defense Force. He is cur-
rently pursuing a B.T.A.S. degree at the
Jerusalem College of Technology—
Machon Lev. You may contact him at
haimbenyamin @walla.co.il.

SOURCES

54622D Mixed-signal oscilloscope
Agilent Technologies
www.agilent.com

ADuC812 MicroConverter
Analog Devices, Inc.
www.analog.com

Photo 4—Take a look at the spectrum of the output of the low-pass filter.
Each vertical division represents 1 dB and each horizontal division repre-
sents 50 Hz. Note that the 3-dB down point is approximately 300 Hz.

background image

36

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

supply voltage into 5 V for the digital
logic. The small trace along the right
edge of the board supplies the switch-
ing regulator, but there is no correspon-
ding common return trace.

Instead, three green ovals across the

middle of the board mark separate
connections between the 24-V com-
mon trace and the 5-V common. The
only common connection between the
leftmost PIC and the rest of the board
runs down past the corresponding
SLA7044 controller, across the bottom
of the board, up past the rightmost
’7044, and then to the switching regu-
lator’s common.

The PWM currents create voltages

along the copper traces that carry them.
The magnitude of those voltages depends
on the DC resistance and AC induc-
tance of the traces, as well as the rise
time of the PWM currents. Photo 5 in
my August column showed spikes of
several hundred millivolts across what
should be a 0-V trace (“Stepper Drive
(Part 1): Analog,” issue 169). That
meandering digital logic common car-
ries four such currents that may add
or subtract unpredictably, so the
potential (yeah, a pun) for interference
is quite high.

I isolated the digital and motor com-

mons by cutting those three connec-
tions, and then wiring the digital sides
directly to the switching regulator’s
common terminal. A single wire from
that terminal to the 24-V supply’s com-
mon pad at the bottom-right corner of
the board reconnected the two com-
mons. This means the digital logic cur-
rent flows in relatively small loops that

ABOVE THE GROUND PLANE

by Ed Nisley

N

ow that you’ve seen how the

stepper circuitry in my Sherline CNC
mill controller works, I can describe the
modifications to improve it. Although
many of the modifications don’t affect
the schematic diagram, they do change
how the currents flow across the board.
After you realize how small details
affect large currents, your designs
should begin working better, too.

COMMON CURRENT PATHS

Photo 1 superimposes the solder-side

traces on a component-side view of the
Sherline motor driver board and high-
lights the places where I modified the
circuitry. The two wide traces below
the four motor connectors near the bot-
tom of the image carry the PWM-limit-
ed current for all four motors from the
24-V power supply pads in the lower
right corner. A switching regulator in
the upper-right corner converts the 24-V

are unaffected by the motor currents.

The SLA7044 controllers refer their

logic-level control inputs to two digi-
tal common pins, which are highlight-
ed by the eight horizontal green ovals
across the lower middle of the board.
The original board layout connected
those pins to the high-current traces,
with all the bad effects described
above. I also cut those connections
and wired the controller logic com-
mons directly to the 5-V regulator
common.

All of those changes helped to

reduce the noise on the logic supply.
The next step was to reduce the trace
length carrying those PWM currents.

Photo 2 shows the X-axis controller

circuitry in detail. I soldered the 0.33-

current-sensing resistors directly to the
24-V common bus. Fortunately, they fit
perfectly between the motor cable con-
nectors and used existing vias!

In addition to reducing the trace

resistance, their new location reduces
the area of the current loop from the
motor connector to the controller,

Stepper Drive (Part 2)

In Ed’s last column, he described how he reworked the stepper circuitry in his Sherline
CNC mill controller to run a bit quieter. This month, he goes into more detail about PWM
current regulation. He also describes how his modifications have affected the waveforms.

Photo 2—Connecting the 0.33-

current-sensing

resistors directly to the high-current common trace
eliminates some stray resistance and reduces the area
of the current path. The flying-blob solder joint is not
recommended practice, but it was convenient for oscil-
loscope probing!

Digital

Photo 1—The green ovals mark connections between

the logic and high-current commons. Yellow and cyan
mark high-current paths from the current-sensing resistors.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

37

through the resistors, and back to com-
mon. That reduces the current induced
in other conductors, which means less
noise in the rest of the circuitry.

The purple oval near the DB-25 paral-

lel-port connector at the top of the pic-
ture marks the connection between the
port’s common pins and the digital logic
common. I cut that trace and inserted a
10-

resistor to isolate the driver box

common from the PC’s common, which

eliminated a possible ground loop path.

Low-level analog circuits often have

noise caused by small differences in the
common voltage between two chassis.
The hum in audio systems is the most
obvious example. The problem typically
arises when an external magnetic field
induces a voltage around a conductive
loop that includes the common connec-
tion between two boxes. That voltage
can appear across an analog input, where
it contaminates the desired signal.

If the total resistance is low, which

is true for good interconnections, the
loop current can exceed several
amperes. A few ohms of resistance can
reduce the current by orders of magni-
tude: 0.1 V across 0.1

is 1 A, but a

10-

resistor cuts it to 10 mA. The

induced voltage remains the same, but
it now appears in essentially one spot.

The voltage here appears in series

with the digital logic signals on the par-
allel port and lowers the link’s noise
margin. Fortunately, these are relatively
clean and low-speed signals, so a slight
amount of additional noise doesn’t have
any effect. You may need differential
signals for truly sensitive circuits.

With all of the common signals

rewired and the isolating resistor in
place, my oscilloscope and signal gen-
erator connections no longer modulat-
ed the motor’s acoustic noise. That
indicated I was on the right track.

REFERENCE VOLTAGES

The thin red trace running across

the board, just below the three vertical
green ovals between the ’7044 drivers,
carries the REF/*ENABLE signal from
the X-axis PIC. The ovals mark three
capacitors that were evidently added
to bypass noise from that line to com-
mon. Unfortunately, because they con-
nected to the high-current common,
they also conducted high-amplitude
PWM noise back into the signal.

The Ref/*Enable signal has both ana-

log and digital functions. When the
voltage is above VDD-1 (approximately
4 V), the driver’s logic and outputs are
disabled. When it’s between 0.4 and
2.5 V, the PWM current is linearly pro-
portional to the voltage. Below 0.4 V,
the input’s effect isn’t defined.

The resistive divider in Figure 1 sets

a nominal 2-V level when the PIC’s pin
acts as an input, so the circuit doesn’t
take advantage of the linear current con-
trol mode. When the PIC’s pin becomes
an output, it can pull the Ref/*Enable
line high to disable the SLA7044 driv-
ers. All four drivers see the same volt-
age, which is affected by noise from
all four motors.

I removed that circuitry, added the

components in Figure 2 to each PIC
and SLA7044, and wrote new firmware
to take advantage of it. As a result, the
firmware from this column will not
(repeat

not

) work in an unmodified

Figure 1—The original Ref/*Enable circuit attempts to

reduce impulse noise with capacitors, but they also
conduct noise from the motor current back to the signal.
The “batteries” represent voltages induced by PWM
motor currents in the circuit-board traces. The X-axis
PIC sets the voltage for all four SLA7044 controllers.

Figure 2—The modified Ref/*Enable circuit has one low-

pass filter for each SLA7044. RA allows the PIC to reduce
the motor current without resetting the registers. Although
the noise is lower, it still isn’t good, probably due to high
source impedance and lengthy common wires.

Listing 1—These five microsteps define the rotor positions from the full-on A winding to the full-on B
winding. The

AMP_xxx constants define the bits that set the PWM-controlled output current in the motor

windings, while the

W_xxxx constants set the phase.

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

// +A=100 +B=0

// Mark this phase with an external bit flag!

Ph0

bsf

NC3

// Flag up

SendCfg

W_PLUS,AMP_900,W_PLUS,AMP_000

bcf

NC3

// Flag down

return

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

// +A=91 +B=40

Ph1

SendCfg

W_PLUS,AMP_675,W_PLUS,AMP_225

return

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

// +A=71.4

+B=71.4

Ph2

SendCfg

W_PLUS,AMP_450,W_PLUS,AMP_450

return

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

// +A=40 +B=91

Ph3

SendCfg

W_PLUS,AMP_225,W_PLUS,AMP_675

return

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

// +A=0

+B=100

Ph4

SendCfg

W_PLUS,AMP_000,W_PLUS,AMP_900

return

background image

38

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

When the PIC’s input

floats in Input mode, the
resistive divider sets the
voltage to 2 V. In Output
mode, a digital high
pulls the voltage
extremely close to 5 V,
and a digital low pulls it
to 0.5 V. As a result, the
PIC can disable the driv-
er completely by raising
the pin, allow normal
operation by floating it,
or reduce the motor cur-
rent to a minimum by
pulling the pin low.

Completely disabling

the driver obviously eliminates all
noise, but it also eliminates the
torque holding the motor in position.
The motors drive leadscrews that
reduce the effect of forces on the
milling machine table, but I do not
have enough experience with the
modified controller to be confident
that the motors won’t creep away
from their positions with the current
turned off. Hence, I included the idle
mode with reduced current.

The low-pass filter formed by the

resistive divider and bypass capacitor
attenuates some high-frequency noise
without appreciably slowing down
the digital logic signals applied to
the Ref/*Enable lines, but it doesn’t
completely eliminate the problem. I
believe that a more robust common-
voltage plane would help considerably,
as would a lower impedance voltage
source, but those are not changes I can
easily retrofit to the existing board.

FLING THE NOISE

Photo 3 shows the result of the wiring

modifications on the A and B windings
of the X-axis motor. The REF/*ENABLE
signal in the bottom trace still has
enough hash to confuse the PWM mod-
ulator when the MOSFET power transis-
tors turn on and off, which should not
be the case. However, the windings
no longer interfere with each other,
unlike the situation in Photo 2 in my
August column.

In any event, while the motors still

whine, the tone is completely stable.
Attaching test equipment or the PC
doesn’t modulate the tone any more,

so the ground loops are under control.
My custom firmware cuts off the
holding current after 5 s of inactivity,
making the motors completely silent
when the mill isn’t cutting. All in all,

it’s a great improvement
and the mill works
essentially the same as it
did before.

SENDING BITS

Sherline’s PIC micro-

controller source code
isn’t available, so I wrote
a clean-room version
that I could tweak as I
modified the board’s
wiring. Several options
may come in handy for
your applications, even if
you don’t have Allegro
SLA7044M drivers in

your circuit. Any changes are a simple
matter of firmware, right?

The original Microchip PIC16F627

chips have 1-KB flash program memo-
ry and 128 bytes of EEPROM storage.

Photo 3—The modified circuitry eliminates the unwanted interaction between the A and B

windings shown in the top traces. There’s still too much noise on the reference voltage, which
causes trouble when the MOSFETs turn on and off.

Listing 2—These two macros format and send the serial datastream to the SLA7044M for each motor step.

Using macros, rather than subroutines, performs all the bit shuffling at assembly time, producing fast and

bulky machine code.

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

// Send one pair of bits to both halves of the controller

SendBit MACROBit_A,

Bit_B

IF

Bit_A

bsf

SDA

ELSE

bcf

SDA

END

IF

IF

Bit_B

bsf

SDB

ELSE

bcf

SDB

END

IF

call

BlipSClk

ENDM

`

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

// Send two configuration sequences to both halves of the conoller

SendCfg MACRO

WA,CA,WB,CB

SendBit WA,WB

// Winding phase

SendBit (b’001’ & CA),(b’001’ & CB)

// Current LSB

SendBit (b’010’ & CA),(b’010’ & CB)

SendBit (b’100’ & CA),(b’100’ & CB)

// Current MSB

call

BlipStrobe

bcf

SDA

// Tidy up the data lines

bcf

SDB

ENDM

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

39

My code adds up to about 400 instruc-
tions and uses none of the EEPROM,
so the ’627 has lots of room left over. I
decided that being pin-compatible was
important, so I used the same chip.

The stepper motors can start turn-

ing at 1,000 steps per second with no
load and have a maximum no-load rat-
ing of about 2,500 steps per second.
Because the Sherline controller uses
quarter-step mode, the PIC must be
able to generate 10,000 steps per sec-
ond. Assuming that the motor can
actually drive the leadscrew at those
rates, the carriage will move at 9.4

per second. In actual practice, that’s
an aggressive speed.

PICs have fairly limited bit-shuf-

fling capability, so I implemented the
motor control code as a set of macros
that sorts out all the bits at assembly
time. At run time, the code simply
sets or clears precalculated bits and
doesn’t execute any complex and
time-consuming logic.

Listing 1 shows the code that quarter-

steps the rotor from the +A position
through the +B position, equivalent to
one full step. Each step requires setting
the proper phase and current in both
halves of the SLA7044M driver chip, so
the

SendCfg macro has four arguments.

Listing 2 shows how the

SendCfg

macro sends the winding phase bits,
followed by the three current ratio
bits. The bitwise AND operations pass
their zero or nonzero results to the
SendBit macro, which clears or sets
the corresponding data outputs and
clocks the bits into the driver.

The code can handle about 8,000 steps

per second, which is close enough to the
maximum speed for my purposes. You
can get slightly higher speeds by con-
verting the

BlipSClk subroutine to a

macro and making a few other tweaks,
but the motor really doesn’t have much
torque at those speeds anyway.

The rest of the code, which I don’t

have space to present here, is equally
straightforward. One interrupt routine
ticks off 100-ms intervals, while
another watches for pulses on the Step
input and records the Direction input.
The main loop polls flags set by those
routines and does what’s needed: turns
off the motors after 5 s or calls for the
next microstep. That’s all it takes!

PROJECT FILES

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

SOURCES

SLA7044M Motor driver
Allegro MicroSystems, Inc.
www.allegromicro.com

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

EMP-21 Programmer
Needham’s Electronics
www.needhams.com/e21.html

Milling machine
Sherline Products, Inc.
www.sherline.com

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

CONTACT RELEASE

Did you figure out the missing com-

ponent in my August column’s simu-
lation model? The two half-windings
act as coupled inductors, so that
changing the current in one directly
affects the other. You can see this
most clearly in the voltage at the cur-
rent-sensing resistor, which actually
goes negative when the MOSFET
turns off.

Microchip’s MPLAB IDE runs fine

with Win4Lin under Mandrake Linux,
but mixing DOS and Unix line end-
ings confuses the assembler. My
Needham’s Electronics EMP-21 device
programmer requires a pure Windows
system for its USB communications.

Remember that the firmware is not

compatible with the unmodified
Sherline board, so you cannot simply
program four PIC16F627 chips and
pop them in your controller. Also, the
code-protect bits are set in the
Sherline chips, so you cannot extract
their code and save it for later. If you
reprogram their chips, you cannot
restore the original program.

I

background image

40

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

O

n May 10, 1954, exactly four days

after my birthday, Texas Instruments
announced the commercial availability
of the first grown-junction silicon tran-
sistor. Today, a few months after turning
50 years old, I’m writing about micro-
controllers and microprocessors that
contain the equivalent of hundreds (and
sometimes thousands) of transistors.

Although the transistor was making

itself known in the late ’60s to the mass-
es via the transistor radio, I was still
building electronic devices that depend-
ed on good old vacuum tubes. Little did I
know that things in my electronic life
were about to make a radical change. As
a teenager, I would cut my dad’s best
friend Leslie Armos lawn each week. It
just so happened that Mr. Armos’s was
an electronics engineer who worked on
missile electronic systems at Redstone
Arsenal in Huntsville, Alabama, which
is a scant 30 miles from my hometown
of Fayetteville, Tennessee. My payments
for the lawn work were lessons on tran-
sistor theory and bushel baskets full of
dropout transistors in all types of pack-
ages that Mr. Armos brought home from
work. Mr. Armos was as brilliant with
tubes as he was with transistors. My
first stereo was a hand-me-down home-
brew tube-type Leslie Armos special.

I’m the son of an Army lifer. My

parents spent that “new stereo” sum-
mer in Germany. I stayed in Tennessee
and ran the house sitter crazy with that
thing. I was really into James Brown at
the time, and, if you can imagine James
screaming at full throttle all day and

every corner and you end up with a pin-
compatible, 64-pin part that offers eight
I/O channels. The pin-per-pin compati-
bility between the 80- and 64-pin micro-
controllers makes for easy upgrades and
downgrades, depending on your applica-
tion needs. In fact, microEngineering
Labs sells a development board called
the PICProto80, which has a unique
pad pattern that supports both 80- and
64-pin microcontrollers.

I’m not going to quote or paraphrase

the datasheet here. The bottom line is
that if you’ve worked with PICs before,
you’ll find nothing new when you begin
working with the PIC18F8x2x parts.
The same things you are used to finding
on smaller PIC parts are here, but in
larger numbers with enhanced capabil-
ities. One welcome new feature is the
inclusion of a set of enhanced USARTs
(EUSARTs) with autobaud and wake-
up capability.

Microchip offers a demonstration

board that comes ready to roll with a
factory-mounted PIC18F8720, which
is currently the biggest mama in the
PIC18F8x2x family. The PIC18Fxx20
64/80-pin TQFP demo board, like the
new big PICs, doesn’t contain any sur-
prises. Basically, the PIC18Fxx20
64/80-pin board contains everything
you would expect in a microcontroller
demo board: a standard serial port, an
MPLAB ICD2 programming/debugging
port, LEDs, push button switches, and,
of course, a temperature sensor. Like
the PICProto80, the PIC18Fxx20 64/80-
pin TQFP demo board is equipped with

Big PICs

APPLIED PCs

by Fred Eady

night, you can imagine the pain the
house sitter endured.

It became apparent that my nightly

forays from Mr. Armos’s house into the
land of the transistor were starting to
take effect. I was listening to the music
of the day using valves (a British term
for tubes) and playing along with my
homebrew transistorized bass guitar
amplifier. My assembly techniques
changed radically as I moved from the
rolling pastureland where tube projects
lived to the smaller apartment con-
fines of transistor circuits. I went tran-
sistor crazy. If it could be transistorized,
I tried to build it. During my teen
years, I built everything from musical
instrument stomp boxes to high-pow-
ered car stereo amplifiers.

The apartment gets smaller each year.

Through-hole electronics have given
way to surface-mount technology. Most
of you have traveled the same electronic
path that I’ve taken. To be able to con-
tinue to walk with me, you’ll have to be
able to apply today’s smaller and denser
circuitry in your designs. With that said,
let’s get down and dirty and put some of
Microchip’s new high-density microcon-
troller hardware to work.

BIGGER PICs

The new additions to the PIC18Fxxxx

family of microcontrollers are high-pin-
count devices that contain up to 128 KB
of program flash memory and more than
3 KB of data memory along with 1 KB of
EEPROM. The 80-pin packages support
nine I/O ports. Clip two port pins from

The newest members the PIC18Fxxxx family are high-pin-count devices that boast up to
128 KB of program flash memory, more than 3 KB of data memory, and 1 KB of EEPROM. Fred
explains how he built an embedded Bluetooth radio as he experimented with a few PIC micro-
controllers and the Promi-ESD-02 Bluetooth module.

background image
background image

42

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Listing 1—Lucio Di Jasio’s

putrs code is the cousin of printf. I’ve shown just enough code to give

you a taste of Lucio’s

putrs utility code. The C18 compiler automatically puts any string constants it

encounters into program memory and operates on them from there. I added the EUSART2 shadows so I
can get at the PIC18LF8621’s second EUSART.

#define B38K16MHZ

25

// Equals 38 kbps at 16 MHz

#define B115K20MHZ

10

// Equals 115.2 kbps at 20 MHz

#define B56K20MHZ

21

// Equals 56 kbps at 20 MHz

#define B96001966MHZ 31

// Equals 9,600 bps at 19.66 MHz

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

// UART init

void UARTinit( char b)

// b data rate generator period. Use B38K16MHZ,B115K20MHZ,

// B56K20MHZ, etc.

{

SPBRG1 = b;

// Set the data rate

TXSTA1 = 0x24;

// TX enable BRGH = 1

RCSTA1 = 0x90;

// Continuos RX, SPI enabled

PIR1bits.RCIF = 0;

// Clear receive flag

TRISJbits.TRISJ4 = 0;

// CTS output enable

CTS_USART1 = 1;

// Not ready to receive

} // UARTinit

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

// UART2 init

void UARTinit2( char b)

// b data rate generator period. Use B38K16MHZ, B115K20MHZ,

// B56K20MHZ, etc.

{

SPBRG2 = b;

// Set the data rate

TXSTA2 = 0x20;

// TX enable BRGH = 1

RCSTA2 = 0x90;

// Continuos RX, SPI enabled

PIR3bits.RC2IF = 0;

// Clear EUSART2 receive flag

TRISHbits.TRISH2 = 0;

// CTS output enable

CTS_USART2 = 1;

// Not ready to receive

} // UARTinit2

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

// putc sends a character to the console

// data is an ASCII character to send to console

char putc( char data)

{

#ifdef RTS_USART1

while( RTS_USART1); // Check hardware handshake if enabled

#endif

while ( !TXSTA1bits.TRMT);

// Wait for the transmit register

// to be empty

return TXREG1 = data; // Write the data byte to the USART1

}

// putc

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

// putc2 sends a character to the console

// data is an ASCII character to send to console

char putc2( char data)

{

#ifdef RTS_USART2

while( RTS_USART2); // Check hardware handshake if enabled

#endif

while ( !TXSTA2bits.TRMT); // Wait for the transmit register to

// be empty

return TXREG2 = data;

// Write the data byte to the USART1

} //

putc2

void putrs( const rom char *s)

{

while(*s != ‘\0’ )

putc(*s++ );

} //

putrs

void putrs2( const rom char *s)

{

while(*s != ‘\0’ )

putc2(*s++ );

} //

putrs2

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

43

the tricky 80/64-pin pad layout.

The Microchip C18 C compiler sup-

ports the PIC18F8x2x parts. Using the
Microchip C18 compiler is a bit different
from coding with the CCS C compiler.
For instance, there is no

printf function

in the Microchip compiler implementa-
tion. There are also fewer built-in, PIC-
specific utility functions. I was initially
alarmed by this and placed a call to
Microchip to ask why. I was introduced
to Lucio Di Jasio. As it turns out, Lucio
wrote a rather nifty piece of code (conio.h)
to overcome what I had considered
shortcomings in the C18 compiler.

Lucio also sent me a big PIC MP3

player application that he had designed,
coded, and built. I studied Lucio’s code
and have incorporated his conio.h func-
tionality into the big PIC projects I’ve
been working on. I thought that you
might also need a jumpstart with C18,
so I obtained Lucio’s permission to give
you the C18 source code and the MP3
project files. You may download the
files from the Circuit Cellar ftp site. By
the way, a

printf function will even-

tually be included in the C18 compiler;
however, Lucio has taken care of that
for now in his conio.h utilities. Some of
Lucio’s work can be seen in Listing 1.

I have a gaggle of big PIC projects in

the works. One project is far enough
along to discuss here. Let’s take a look
at what I’ve been up to.

EMBEDDING BLUETOOTH

The tiny eight-pin module you see in

Photo 1 is an embedded Bluetooth radio
complete with an integrated UART. The
Promi-ESD-02 is a class 2 device with
2.5 mW of output power. This 18 mm ×
20 mm module is designed to be incor-
porated in OEM designs that require
wireless RS-232 capability.

Six I/O pins provide an interface to

the module’s UART. However, if you
choose not to incorporate handshaking,
you can get away with using only two of
the six I/O lines: RXD (UART data in)
and TXD (UART data out). The other
four I/O lines are STATUS, RST (reset),
CTS (clear to send), and RTS (request to
send). The STATUS I/O pin is an output
that’s used to drive an LED to indicate
the status of the radio connection. RST
is the reset I/O pin and is active low.
Handshaking is accomplished using the

module’s CTS and RTS I/O pins. If
handshaking isn’t desired, the CTS I/O
pin must be tied to ground or held low
by the host microcontroller.

My first choice for a host microcon-

troller was the PIC18F8720 because it is
the star of the PIC18Fxx20 64/80-pin
TQFP demo board. I figured that all I
would have to do is lash the Promi-
ESD-02 to the breadboard area of the
demo board and write some code to talk
to the Promi-ESD-02’s UART. Well, in
theory, that’s all I needed. However, in
reality I had some work to do before I
could relax and write UART code.

The first hurdle I had to clear was

altering the PIC18Fxx20 64/80-pin
TQFP demo board power supply to suit
the Bluetooth radio module. The
Promi-ESD-02 is a 3.3-V device and the
big PIC demo board is wired for 5 V.

The PIC18F8720 that comes with the

PIC18Fxx20 64/80-pin TQFP demo board
is not designed to operate at 3.3 V. I would
have to install a PIC18LF8720 to reach
down to 3.3-V operation. However, during
my discussion with Lucio, I learned that
the 19.66-MHz clock on the demo board
would not function properly at the reduced
voltage if I used the stock PIC18F8720 or
its LF counterpart. Take a look at what
the PIC18LF8720 datasheet revealed:

where F

MAX

is the max clock frequency

and V

DDAPPMIN

is the minimum V

DD

.

Plugging 3.3 V into the F

MAX

equation

and pounding some keys on my TI-89

F

MAX

DDAPPMIN

=

MHz/V

2 V + 4 MHz

9 55

.

(

)

(

)

V

Photo 1—Everything is here. A Bluetooth radio, a
UART, and an antenna (the white bar) are positioned
inside the area of a postage stamp. Even though the
Promi-ESD-02 doc doesn’t note it, pin 1 is identified by
the hole in the shield.

background image

44

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

resulted in a maximum clock frequen-
cy of just over 16 MHz at 3.3 V using a
PIC18LF8720. I could get by with this
clock in the Bluetooth project, but I have
other 3.3-V PIC projects in the fire that
will need a speedier clock. Lucio suggest-
ed using the PIC18LF8621. Using a
PIC18LF8621 puts 16.36 MHz per volt
into the F

MAX

equation and yields a 25-

MHz maximum clock rate at 3.3 V. One
of my other 3.3-V big PIC projects is run-
ning a 20-MHz clock with no problems.

The next step in the demo board

conversion involved replacing the
stock 5-V MAX232 RS-232 interface
IC with a pin-compatible 3.3-V Sipex
3232 RS-232 interface IC. After I had
removed the original PIC18F8720
microcontroller and RS-232 interface
IC and replaced them with their 3.3-V
cousins, I had only the voltage regula-
tor itself to convert to finish the job.

The PIC18Fxx20 64/80-pin TQFP

demo board uses a 78L05. Instead of
removing the 78L05, I decided to simply

version of the Promi Bluetooth modules.
The Promi-ESD-02 documentation sug-
gests using a test jig to get familiar with
the radio. Because the commercial
Promi-ESD-02 test jig is not yet avail-
able, I decided to build one from scratch.

I enlisted another one of my big PIC

project boards to help with getting a
Promi-ESD-02 test jig built. My big PIC
project board is a simpler version of the
PIC18Fxx20 64/80-pin TQFP demo
board. The project board I use to sup-
port the Promi-ESD-02 test jig is also a
3.3-V test stand designed around the
PIC18LF8621. An on-board Sipex 3232
supplies all of the RS-232 conversion
for the Promi-ESD-02’s TXD, RXD,
CTS, and RTS lines. A Reset button and
3.3-V power supply are also included on
my big PIC test stand. A microcontroller
isn’t needed because the Promi-ESD-
02’s UART is in direct communication
with the PromiWIN configuration pro-
gram and a Tera Term Pro session run-
ning one of the Florida room’s PCs.
The wiring details of my Promi-ESD-
02 test jig are displayed in Figure 1.

The Sipex 3232 is tied into the test

jig’s PIC18LF8621 microcontroller I/O
structure. Like the PIC18Fxx20 64/80-pin
TQFP demo board, all of my big PIC test
stand’s microcontroller I/O pins are ter-
minated at a header pin. To make it easy
to connect the Promi-ESD-02 I/O pins to
the Sipex 3232, I fabricated a daughter-
board to support the Promi-ESD-02
radio module and its status LED.

I was concerned when I wired the

Promi-ESD-02 and big PIC test stand. The
Promi-ESD-02 documentation provides a
module layout that identifies the pins of
the Promi-ESD-02 module. The problem
is that the drawing does not tell you
whether you are looking at the pins
from the top or bottom of the module.

Pin 1 of the Promi-ESD-02 module is

the ground pin. I put on my pointy wiz-
ard’s hat and thought about this from
an RF engineer’s perspective. If I were an
RF guy or gal, I would shield the innards
of my little radio. So, I pulled out my
VOM and looked for continuity between
pin 1 and the radio shield. As the emper-
or of Austria in the movie Amadeus
(1984) would say, “There it is…” I went
on the assumption that the only pin that
was electrically connected to the shield
was indeed pin 1 and wired in the Promi-

route its 5-V output into the
input of a ZR330 3.3-V regula-
tor and steer the ZR330’s 3.3-V
output into the V

DD

main of

the ’Fxx20 64/80-pin TQFP
demo board. That gives me
the freedom to use a 5-V device
on the converted PIC18Fxx20
64/80-pin TQFP demo board

without having to add a 5-V reg-
ulator and associated circuitry.

The only other active com-

ponent on the PIC18Fxx20

64/80-pin TQFP demo board is the
temperature sensor. I checked the
TC74 datasheet and found that the lit-
tle temperature sensor is good with
anything from 2.7 V up. My custom
3.3-V PIC18Fxx20 64/80-pin TQFP
demo board (now a PIC18LF8621 demo
board) complete with a Promi-ESD-02
is shown in Photo 2.

After the host hardware was com-

plete, I verified the RS-232 connectivity
with a bit of Lucio’s conio.h code that
sent a message from the newly convert-
ed PIC18Fxx20 64/80-pin TQFP demo
board to a Tera Term Pro emulator ses-
sion running on my laptop in the Florida
room. Before you can write UART code,
you’ll have to learn the ways of the
little Promi-ESD-02.

EXPLORING PROMI-ESD-02

The Promi-ESD-02 modules are brand

spanking new. Although I’ve worked
with Initium modules before, I’m a babe
in the woods with the new embedded

Figure 1—After I figured out what pin was what, the rest was easy. You can get a full schematic of the PIC18Fxx20
64/80-pin TQFP demo board from the Microchip web site. I tied the Promi-ESD-02 TXD and RXD pins to the sec-
ond PIC18LF8621 EUSART in a no-handshake, null modem configuration with CTS grounded.

Photo 2—Changing out the PIC18F8720 for a PIC18LF8621 wasn’t
difficult. I cheated and used an SMT rework machine for the task.
Switching in the Sipex 3232 was done by hand. I could have done
the big PIC by hand as well, but I wanted the picture to be pretty.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

45

ESD-02 module with that reference. I put
away my pointy RF wizard hat and
applied power to the big PIC/daughter-
board test stand assembly. The status
LED indicated that the Promi-ESD-02
was offline. And I didn’t see smoke or
smell the Promi-ESD-02 module cooking
itself. Things were good.

The Promi-ESD-02 can be configured

using the canned PromiWIN application
or by way of a terminal session using a
subset of the AT modem command set.
I was pleased to see the little radio iden-
tify itself to the PromiWIN program. At
this point, I figured I would need to con-
figure a companion Initium radio mod-
ule to learn about making connections
between a pair of radios. So, I pulled out
one of my Promi SD202 Bluetooth serial
adapters and attached it to one of my
laptops. To my surprise, the newer of the
laptops doesn’t have a standard serial
port. I guess I’ll be investing in one of
those USB-to-RS-232 dongles. Using
PromiWIN, I set up the laptop radio for
9,600 bps with the standard 8 data bits,
1 stop bit, and no parity settings.

After the PromiWIN application sees

the PC serial port and receives identifi-
cation information from the radio
attached to the serial port, the next
step in the radio set-up process is to
assign a link speed and set the radio
mode. I selected 9,600 bps.

The Promi radios work with a link

speed from 1,200 bps up to 115 kbps.
There are four modes: MODE0 (standby
status for Bluetooth connection), MODE1
(connect to the last connected device
only), MODE2 (connect from the last
connected device only), and
MODE3 (allow any Bluetooth
device to discover/connect).

I selected MODE1 for the

laptop device because I figured
I would put the test jig device
in MODE2. Using MODE1 and
MODE2 establishes a perma-
nent and automatic link
between two devices following
their initial connection.
Previously, I used these modes
successfully with a pair of
Promi SD202 adapters. So, I
figured it would work well in
this application too.

Now that the laptop Promi

SD202 was configured and

ready to go, I turned to set up the Promi-
ESD-02 on the test jig. After repeated
tries, I could not get the Promi-ESD-02 to
enter any modes other than MODE0. I
was receiving identification informa-
tion from the test jig and concluded that
maybe the CTS or RTS I/O lines were at
the incorrect levels or just plain hooked
up incorrectly. I tried disconnecting the
CTS and RTS lines and got absolutely
nothing in the way of identification infor-
mation from the Promi-ESD-02 UART. I
then tied CTS to ground and let RTS fly. I
got identification information, but I still
could not put the Promi-ESD-02 into a
different mode. Because I had a pair of the
little embedded radios, I swapped in the
other radio on the test jig. Same results.

Finally, I decided to just operate every-

body in MODE0. I reset the laptop
Promi SD202 adapter for MODE0 and
instructed it to scan for other Bluetooth
devices. I then used PromiWIN to put
the test jig radio in Discoverable/
Connectable mode. I was happy to see
the results you see in Photo 3. The lap-
top radio saw and identified the test jig
radio. I highlighted the discovery and
used the PromiWIN Connect To button
to establish a communications session
between the laptop and test jig radios. I
opened Tera Term Pro terminal emula-
tor sessions on the laptop and the desk-
top PC supporting the test jig and sent
data to and from the laptop and test jig
using the Bluetooth radio link.

At this point I didn’t know whether

or not the Promi-ESD-02 modules
were broken, but because I had dis-
covered I can pass data through both

of them, I assumed they were working
as designed. The next step was to learn
about the AT commands as the
PromiWIN Windows application will
not run on the ’LF8621.

After some fooling around with the

commands using Tera Term Pro sessions,
I found that I could control the test jig
Promi-ESD-02 and establish or break
communication sessions using the Promi
AT command set. This is a good thing
because all I had to do in my UART code
was transmit ASCII commands and
data to the Promi-ESD-02 UART and
receive and act on ASCII responses
from the Promi-ESD-02 UART via the
PIC18LF8621’s second EUSART. The first
EUSART is dedicated to the PIC18Fxx20
64/80-pin TQFP demo board’s serial port.

My desire was to place the ’18Fxx20

64/80-pin TQFP demo board’s Promi-
ESD-02 into permanent Discoverable/
Connectable mode and access it at will
from a laptop or another Promi-ESD-02
embedded device. This was easily
accomplished by issuing the

AT+BTSCAN

command to the Promi-ESD-02. This
command instructs the Promi-ESD-02
to scan until it establishes a Bluetooth
connection with another device.

To establish a communication session

with the Promi-ESD-02/’LF8621 combina-
tion, the

ATD112233445566 command is

issued to a remote Bluetooth device with
112233445566 being the actual Promi-
ESD-02/’LF8621 Bluetooth device address.
For instance, to connect to the Promi-
ESD-02 configuration shown in Photo 2,
simply enter

ATD000B531318AF in the

Tera Term Pro session and hit the Enter

key. A few moments later, the
CONNECT 000B531318AF mes-
sage appears in the laptop’s
Tera Term Pro window.
Likewise, a similar connect
message appears in the Promi-
ESD-02 desktop’s emulator ses-
sion showing the address of the
laptop’s Promi SD202
Bluetooth device.

At this point, using Tera

Term Pro, I have established
a communications session
between the laptop’s Promi
SD202 and the desktop’s
Promi-ESD-02. I can just as eas-
ily generate the

AT+BTSCAN or

ATD000B531318AF commands

Photo 3—PromiWIN is a Windows application that simply issues the AT commands
and displays the results in a Windows-like manner. The Connection(out) screen is
shown here. The search results you see in this shot can be obtained with a terminal
emulator session or the PIC18LF8621 by issuing the

AT+BTINQ?AT command.

Connection(in) is just another way of executing the

AT+BTSCAN AT command,

which puts the Promi module in Discoverable/Connectable mode.

background image

46

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

PROJECT FILES

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

SOURCES

Promi-ESD-02 and Promi-SD202
Lemos International (distributor)
www.lemosint.com

PIC18LF8621, ’F8720, ’Fxx20 64/80-pin
TQFP demo board, C18 C compiler
Microchip Technology, Inc.
www.microchip.com

PICProto80 Prototyping board
microEngineering Labs
www.melabs.com

SP3232 RS-232 Interface IC
Sipex Corp.
www.sipex.com

using the ’18LF8621 EUSART and, thanks
to Lucio, some simple C code. Take a
look at Listing 2 to see how I did it.

BIG PICTURE

I haven’t even scratched the surface

of the PIC18F8x2x’s capabilities.
Now that I’ve Bluetooth-enabled a
PIC18LF8621, there’s still lots of analog-
to-digital, PWM, and general-purpose
microcontroller I/O stuff that can be done
with the rest of the PIC18LF8621’s sub-
systems and I/O ports. With the advent of
the monster PICs, you’d be hard pressed
to produce an application that will run
the big PICs out of program space or I/O.

You may not have had the pleasure of

learning about transistor theory and eat-
ing homemade Polish sausage with
Leslie, but if he were here, he too would
tell you that it really doesn’t have to be
complicated to be embedded.

I

Listing 2—In this code snippet, I enabled both of the PIC18LF8621 EUSARTS. After I got the Promi-ESD-
02’s attention, I issued the

AT+BTSCAN command. After AT+BTSCAN is executed, it remains in effect

until the Promi-ESD-02 is reset. I used another one of Lucio’s utilities,

getsn, modified it for EUSART2,

and used it to buffer data coming from the Promi-ESD-02’s UART. I then redirected the buffered data out to
EUSART1, which is connected to a Tera Term Pro terminal emulator session.

void delay_ms(unsigned int delay)

{

do{

Delay1KTCYx(5);

}while(delay—);

}

#define rset LATG,0

// Define Promi RST pin

char buffer[128];

void main(void)

{

unsigned int x;

char rc;

TRISGbits.TRISG0 = 0;

// RESET PIN

bit_clr(rset);

// Reset Promi-ESD-02 module

delay_ms(1000);

bit_set(rset);

UARTinit(B56K20MHZ);

// Close enough to work with 19.66 MHz

UARTinit2(B96001966MHZ);

putrs2(“AT\r\n”);

// Get Promi’s attention

delay_ms(1000);

putrs2(“AT+BTSCAN\r\n”); // Make Promi discoverable/connectable

while(1){

rc=getsn2(buffer,127);

// Get incoming data using EUSART2 at

// 9,600 bps

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

putc(buffer[x]); // Echo incoming data to EUSART1 at

// 56 kbps

}

}

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.

background image
background image

48

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

“R

alphie boy.” That’s what they

used to call me. You wouldn’t have want-
ed to be caught sitting next to me on an
amusement park ride. I was green way
before Mr. Spock found it fashionable.

I still don’t fly well. I think this entire

motion sickness thing started back in
the 1960s with a birthday gift. I’ll bet
plenty of you remember the COX con-
trol-line flying aircraft, which consisted
of a .049 gas engine fastened to a plastic
airplane tethered to your hand via 50

of string. The tether was actually two
strings that alternately pulled the plane’s
tail flaps up or down. This gave the pilot
(the poor sucker in the middle) the abili-
ty to make the airplane climb and dive
as it buzzed around in a circle. Needless
to say, you had to keep up with the rota-
tion to keep from getting wrapped up in
the tether. If you didn’t, the plane would
continue flying around you in smaller
and smaller circles until, well, you get
the picture. But I never worried about
this happening because I always ended
up keeled over from dizziness.

I knew guys who were successful at

control-line flying. I was literally green
with envy. Glue can fix broken plastic
only so many times. This hobby quietly
segued into Estes model rocketry. I
found I could easily step back and watch
a launch without any significant loss of
balance. This started my love affair with
space, but I never got over my urge to
fly aircraft. Sometime between then
and now, radio control has made it
possible for guys like me to accom-
plish what COX couldn’t. Sure, like
many others, I’ve flown simulator mis-
sions using my PC. Not the same.

ered to have an idle position. From this
position, you can make adjustments to
either side of the servo’s idle position. If
this timing pulse is used to modulate a
carrier at the transmitter, a matching
receiver can demodulate the timing pulse
without much hassle to directly run the
servo. So, I’m back to the question of how
the servo responds to this pulse train.

The servo recognizes its present posi-

tion (PP) by monitoring the output shaft
with a potentiometer. With the shaft at
–90°, the potentiometer has minimum
resistance. With the shaft at 90°, the
potentiometer has maximum resistance.
A one-shot is set up using a capacitor and
the potentiometer. After it’s triggered, the
on time is 1.25 ms when the potentiome-
ter is at minimum resistance and 1.75 ms
when the potentiometer is at maximum
resistance. Notice that these are the
same timings as the requested position
(RP) pulse train coming from you. The
one-shot is triggered with the beginning
edge of each pulse of RP and the two (RP
and PP) are compared. An error signal
can be created if there is a difference
between the two. This error can be posi-
tive or negative. The error’s sign is used
to control the direction of the motor in
an attempt to eliminate the error. When
the error has been eliminated, the
motor has successfully moved the shaft
to a position where the requested posi-
tion matches the present position.

Most R/C servos use a Mitsubishi

M51660L IC designed for this purpose.
Figure 1 shows a typical servo circuit
employing the M51660L. This device
contains just about everything needed
for the servo, including the bottom

Digital Radio Control

FROM THE BENCH by Jeff

Bachiochi

There seems to be an R/C hobby for
everyone. You can drive cars, trucks,
tanks, and any other kind of wheeled
vehicle. You can fly planes, gliders,
blimps, and any other kind of aircraft.
You can also sail warships, sailboats,
submarines, and any other kind of aquat-
ic craft. Today you can put yourself into
just about any driver’s seat.

R/C SERVO

The R/C servo is a design marvel. It

consists of a motor and gear train
designed to give maximum torque and
speed of an output shaft over an approxi-
mately 180° rotation. The output shaft’s
rotation of its servo arm is normally used
to push and pull a control arm to perform
a function like steering wheels or moving
an aileron or rudder. So how can this
motor be used to position the servo arm?

It all starts with the control signal. An

R/C servo is most happy with a 1.25- to
1.75-ms pulse train at a 20-ms rate. To
the servo, the pulse width requests a
position of the output shaft. Position can
be thought of in two ways: minimum 0°
(1.25 ms) and maximum 180° (1.75 ms),
or minimum –90° (1.25 ms) and maxi-
mum 90° (1.75 ms). For the sake of
this discussion, I will use the latter.
Halfway between the maximums, I can
describe a position of 0° (1.5 ms). This
midpoint can be thought of as rest, or
idle, for many controls, steering straight,
or flying level.

This control signal is developed by the

position of joysticks, switches, and knobs
on the user interface, normally the R/C
transmitter. Self-centering joysticks are
the main reason servo signals are consid-

When it comes to building R/C systems, digital control is the way to go. In this article, you’ll
learn how to retrofit your R/C vehicle with a simple digital system. With Jeff’s help, you can
animate an R/C airplane with retractable landing gear and controllable lights.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

49

provides improved servo signal stability.

Although all the mimicking of the

original R/C system makes for a plays-
well-with-others approach, it certainly
doesn’t take advantage of the microcon-
troller’s full power. Without new data
transmission standards, you would not
be able to mix and match transmitters
and receivers. If this doesn’t bother you,

you might want to experiment with
your own communication standards. In
fact, with transceivers becoming small-
er and lighter, it may be time to make
this entire R/C thing bidirectional.

DIGITAL R/C

You don’t see many R/C users using

more than four channels. There just

half of an H-Bridge to control the
motor in either direction at currents
to approximately 0.5 A!

MULTIPLE CHANNELS

As I mentioned earlier, an R/C servo

likes to have its pulse repeated every
20 ms. If you want to send pulses from
more than one channel, you have only
20 ms to do it because the first chan-
nel must be updated again at that point.
Using the aforementioned conventional
modulation techniques, only so many
channel pulses at 2 ms will fit into
20 ms. This is where microcontrollers
join the fray.

On the transmitting end, a microcon-

troller can scan all of the inputs (poten-
tiometers and switches) and rapidly col-
lect pertinent data. The microcontroller
can form the pulse train based on the col-
lected data sent over the radio link. A
microcontroller on the receiving end can
interpret the pulse train and make adjust-
ments to a table of values used by a back-
ground routine. This creates R/C servo
signals at a sustained rate independent
of potential radio interference, and it

Figure 1—This typical schematic of a servo unit uses the Mitsubishi M51660L servo motor controller. The poten-
tiometer connected to the pin1 input gives position information to the controller because it is physically linked to the
output shaft. Two internal transistors (along with the two external ones) form a full-bridge motor controller.

background image

50

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

aren’t that many degrees of necessary
control. However, R/C is also used for
applications like animatronics, which
may be the most well known. I con-
sider animatronics to be more than
just animating movie makeup. Some
robots can be placed in this category. I
put robots that use some other mode
of transportation other than wheels
and treads in this category.

I think a robotic arm can be consid-

ered as animatronic. When creating a
complex movement from scratch, like
a hand reaching for a glass, it is often
impossible to visualize the proper com-
bined joint paths that will successfully
accomplish the task without incident.
Playing with joint control using an R/C
connection allows you to experiment in
real time and halt any command that
may wreak havoc because of the visual
feedback you bring to the equation.

Whether you are using two or 20 chan-

nels of control, communicating digitally
has definite advantages over analog com-
munications. Besides a transmission
speed gain, digital communication has the
advantage of determining whether or not
a received command is correct. Dropouts
in an analog transmission mean data
error, which cause a servo to position
itself improperly. If digital data gets
received with an error, the bad data can

be tossed and not applied to the servo. In
fact, if communication fails altogether, a
receiver could be programmed to make
fail-safe adjustments, like reducing
speed to zero or flying in a circle.

Of course none of this can work if a

digital standard cannot be established.
For now R/C users must be content
with receivers analyzing analog trans-
mission signals with signal processors
to get a digitally cleaned up signal with
some smarts. If you want to be on the
edge, you will need to develop both a
digital transmitter and receiver using
your own communication format.
Depending on the complexity of the
radio link you choose, you will need
to alter the communication format.

The dumbest links have no ability to

help it get to its destination. You need a
data format that includes complete data
packets to ensure proper reception. This
may consist of a preamble (to wake up
the receiver and lock on the following
data), a destination address (to allow the
receiver to use or reject the data), a
length of data value (the number of data
bytes to receive), the data, and some
kind of error-checking code (to deter-
mine that the data was received correct-
ly). Generally, these transmitters and
receivers have no data buffers, and data
direction is limited to one way.

The smartest links can

accept data directly by packe-
tizing the data and transmit-
ting it. The receiver not only
removes the data from the
packet, but can also acknowl-
edge the reception of it. This is
a two-way communication and
allows the data to be retrans-
mitted if the packet was not
acknowledged (because it was
received with corrupt data).
These devices have data buffers
that temporarily hold the data.

You may choose to use a

link that falls somewhere
between the two. Whatever
you choose, refer to the man-
ufacturer for details on what
kind of format might be best
suited for this device.

EXPERIMENTAL PROJECT

The basic project consists

of a user PCB with two joy-

sticks that provide four proportional
controls and four push buttons. The
servo PCB has four servo outputs, which
reflect the position of the joysticks, and
four digital outputs, which reflect the
condition of the push buttons (or toggle
switches). To simplify the hardware, a
single PCB design handles both ends of
the project. (Separate PCBs would allow
a considerable size reduction in the
servo PCB, which is desirable for reduc-
ing the weight when used in an aircraft.)
Figures 2 and 3 show the basic opera-
tions needed for each end of the project.

USER INPUT MODULE

Both applications fit in the same

microprocessor. Jumpers are on the
jumper block JP2 (see Figure 4). JP2-1
determines the application’s mode.
Installing a jumper on JP2-1 grounds the
RB4 input. The application then jumps
to the transmitter application initializ-
ing the microcontroller to use the PCB
as a user input module. A user input
module is populated with two joysticks
and four push buttons (or toggle switch-
es). The joysticks are constructed as
two potentiometers at right angles to
one another. One is affected by moving
the joystick in a vertical direction,
while the other is affected by moving

Initialization

Data

arriving?

Reset buffer pointer

Data

finished?

Move channel 1 through 4

from buffer to servo registers

Expansion

data

available?

Use SPI to send data

to expansion modules

Y

N

Y

N

Y

N

RX Interrupt

Move character to buffer,

increment pointer,

and clear finished flag

Exit

TMR2 Interrupt

Set finished flag

Exit

TMR1 Interrupt

Clear last servo

output, set next servo

output, set/clear SW

output, and load

Timer1 from servo

Exit

Figure 3—The servo PCB must refresh the servos at a 20-ms rate.
Timer1 handles this. One servo on time is loaded from the associated
servo registers each time through the interrupt. The fifth time through a
dummy off time is loaded to complete a 20-ms cycle. A Timer2 overflow
flags the end of the received data (lack of data for two character times).

Initialization

A/D conversions

of potentiometers 1

through 4 stored into

the transmission buffer

Sample state of

switches 1 through 4

stored into the

transmission buffer

Expansion

modules?

Send data in the

transmission buffer

Use the SPI interface

to collect the data

and store it to the

transmission buffer

Y

N

Figure 2—The user input application must collect data
and transmit it to the servo output PCB using an RF
transmitter. If collecting the data takes too long, a timer
interrupt could transmit the present buffer data at spe-
cific intervals.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

51

the joystick in a horizontal direction.

Each potentiometer is used as a voltage

divider input to the microcontroller’s
internal A/D converter. Although the
A/D converter is a 10-bit conversion, all
values are converted to a percentage (a
number from zero to 100). This value fits
into 7 bits, leaving the most significant
bit of the byte for switch status. One
value holds both analog (potentiometer)
and digital (switch) data. This allows four
channels of each to fit neatly into 4 bytes.

Transmitting data is the priority (if

any) for this module. By storing values
directly in the transmission buffer, the
most recent data is always available to be
transmitted. The data (or packet if neces-
sary) doesn’t have to be gathered, except
for maybe calculating a checksum value
just before transmitting the buffer.

In the case of one-way RF communi-

cation, the format must include all

channels because there is no feedback
as to what the receiver may have lost.
When two-way RF communication is
available, the format might contain
only changes. Because an acknowl-
edgement of some kind can be used to
verify receipt, the receiver will always
have the latest data.

During the design phase of the expan-

sion module, I attempted a cost reduc-
tion by designing with a cheaper, less
sophisticated microcontroller. However,
if I used the same microcontroller, I
could actually use the same PCB for all
four modules: the user input PCB, the
user expansion PCB, the servo output
PCB, and the servo expansion PCB. This
would mean adding an extra expansion
connector to the PCB. I would also like
to change the connector from an RJ-11
to a square pin header. I found it was
too easy to grab a modular phone cable

with the ends terminated wrongly
(reversed), potentially causing damage.

Each of the expansion modules needs

a module address. This number can be
programmed into the internal EEPROM
using the on-board push buttons to
enter data. With this method the num-
ber of expansion boards is not limited
to the number of available jumpers
(JP2). The main module can, as part of
its initialization, go out on the SPI bus
and see what’s there. This automatic
operation would be more user-friendly
than having to set jumpers to correctly
identify expansion modules.

SERVO OUTPUT MODULE

When the PCB is used for servo output

control, three-pin headers are installed
instead of the joysticks and switches.
The pinout matches standard servo con-
nections, signal, power, and ground.

Figure 4—This schematic can be used as a universal experiment board. Joysticks, switches, and expansion input circuits can be added for use as the transmitter. Or, when used as a
receiver or output expansion board, JP3–6 can supply RC servo pulse trains and JP7–10 will have digital outputs. JP1 may need modification depending on the radio link you choose.

background image

52

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

(Note that servos that don’t conform to
this pinout must have their pins removed
and reinserted into the header to reflect
this configuration.) Digital outputs use a
similar three-pin header and have power
and ground available, therefore allowing
LEDs to be operated either in Source or
Sink mode or to power external circuits.
The remaining jumpers (JP2-2, JP2-3, and
JP2-4) are used to indicate the number
of expansion modules attached. In this
form, up to seven expansion modules
can be daisy chained to the master.

Priority for this module is given to the

receive data interrupt, which quickly
moves a data byte to the receive buffer.
The next highest priority is the Timer1
overflow. This routine is responsible for
maintaining the servo (and digital) output
for each channel, using the latest data in
the channel registers. All four channels
are updated about every 20 ms. The
Timer2 overflow has the lowest priority.
If it overflows, it indicates that no charac-
ter has been received for two character
time periods, and the main program loop
must update the channel registers based
on the latest data in the receive buffer.

The number of expansion channels

comes from the receive buffer’s point-
er. Because there are 4 bytes of data
for each module, the pointer can be
used to determine how many modules
are being used. Expansion module
data is transferred to each expansion
module using the SPI interface.

TIMING AND POWER

The data rate is presently 19.2 kbps.

Referring to Photo1a, the oscilloscope

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

Circuit

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

PROJECT FILES

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

is triggered on the rising edge of the
lower trace, which is the busy (CTS)
output of the RF receiver. The upper
trace shows the serial data leaving the
receiver approximately 14 ms after the
receiver obtains a lock on an RF trans-
mission. Notice the receiver becomes
ready again approximately 2 bytes
prior to the data’s end, just as the last
of the receiver’s buffered data empties
into its UART.

In Photo 1b, the oscilloscope is trig-

gered on the first start bit of an 8-byte
serial transmission (4 bytes from the
user input module and 4 bytes from one
expansion board) to the RF link (top
trace). The lower trace shows the SPI
clock during a 5-byte communication
(1 byte board address sent and 4 bytes
of data retrieved) with the expansion
board. Each expansion module adds
approximately 1 ms of SPI communica-

tion time to the loop; however, this
takes place while the RF transmitter
is busy sending data. In addition to the
SPI communication, 4 bytes of data
per expansion module are sent over
the RF link. This adds 2 ms (per
expansion module) to the overall
transmission time.

The user input module with the RF

link requires approximately 75 mA at
5 V to operate. Input expansion boards
only add about 10 mA each. On the
receiving end, the servo board with
the RF link draws approximately 50 mA.
My CS-50 servos idle at approximately
25 mA with movement currents of
greater than 100 mA each. That’s
approximately 0.5 A per servo board
under worst-case conditions, so you’ll
want to use those NiCd batteries for
vehicles or a DC power supply when
animating puppetry.

I have a couple of projects in mind

now that I have some circuitry I can
experiment with (see Photo 2). You
may not be ready to retrofit your R/C
vehicle with this digital system; but,
just think about how you could ani-
mate an aircraft by adding lights, an
ejecting pilot, bomb bay doors, and
retractable landing gear. If robotics is
your thing, you could add manual con-
trol to your robot’s autonomous
nature or create animatronics. One
thing is clear: With this project I’ve
just about eliminated any potential
bouts of motion sickness.

I

Photo 2—The user input PCB on the right and the
servo output PCB on the left (as well as the expansion
PCBs for input and output that aren’t shown) all use
the same prototype PCB. Although not the smallest
footprint for stuffing into an R/C model, using the same
PCB everywhere makes the most sense for experi-
mentation on a shoestring budget.

SOURCES

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

M51660L Servo motor controller
Mitsubishi Electric
www.mitsubishielectric.com

Photo 1a—By far the most time-consuming portion of this application is the RF communication. Because of this,
the original idea of sending individually addressed data packets was scrapped for packets containing all data. The
lower trace shows the RF busy time while the upper trace shows the actual data sent.
b—SPI communication
between user input and expansion input modules (and servo output and expansion out modules) requires approxi-
mately one-quarter of the time as the actual data transmissions to the RF link. Because the expansion modules
handle their own data collection and servo timing, there is no waiting on expansion processes.

a)

b)

background image
background image

address changes is 20 ns. The RAM has
a minimum 10-ns write enable pulse-
width requirement, which is just met
with a 50-MHz square wave with a 50%
duty cycle. The RAM also has a zero
hold time requirement between the *WE
(clock) and address bits. This allows the
address to change at the same time the
rising edge of the clock is clocking new
data into the RAM.

ADDRESS GENERATOR &

TIMEBASE

Both of the circuits use N-bit up coun-

ters. The address generator is 17 bits. The
timebase is 6 bits. One of the advantages
of designing with PLDs is that the design
software has built-in LSI functions. In
order to use a counter, all I had to do was
select it from a list of built-in functions,
select which inputs and outputs I wanted
to use, and then define the appropriate
parameter values. The parameters and
signals I needed for the address generator
are as follows: direction = up, width = 17,
clock input, asynchronous clear input,
and Q outputs. Some of the other inputs
and outputs include: asynchronous load,
carry in, carry out, and clock enable.

54

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

G

ood test and measurement equip-

ment is a prerequisite for working with
digital circuits of any complexity. In this
article I’ll describe an eight-channel, sin-
gle-board logic analyzer (SBLA) that you
can build for approximately $60 (see
Photo 1). The SBLA connects to any
available parallel port (EPP 1.7) on a PC.

You may download the code for this

project from the Circuit Cellar ftp site. In
addition to the documentation, the Visual
Basic program that controls the analyzer
and displays the results is also posted on
my web site (www.qsl.net\k3pto).

SBLA DESIGN

This design is based on a device I built

that uses up to six measurement cards
and is configurable with any card combi-
nation of eight-channel logic analyzer
or single-channel DSO. (Refer to the
January/February 2003 edition of QEX
for more information on this topic. The
data for this device is also posted on
my web site.)

After building the DSO/LA, I wanted

to see what it would take to design a
smaller logic analyzer in which the entire
circuit fits on a single circuit board,
hence its name. Because the bulk of the
logic for the original device was achieved
using a PLD, it turned out to be fairly
easy to modify it for this simpler device.

Before I started designing the system,

I set a few goals for myself: build a sin-
gle PC board that can be fabricated by
a hobbyist; use as much of the previous
PLD design as possible; use eight chan-
nels and possibly expand to 16; imple-
ment the same program as the DSO/LA;
use a 50-MHz sample rate and 128,000
samples per channel; and implement
the same INI file for system configura-

Single-Board Logic Analyzer

Larry’s eight-channel, single-board logic analyzer can connect to any parallel port on your
PC. It’s a great tool to have on hand if you work with complex digital circuits. Read on to learn
more about this small, inexpensive design.

tion. I accomplished every goal.

The logic of the SBLA consists of a

PLD, RAM, oscillator, and three sup-
porting bidirectional buffers (see
Figure 1). The primary function of two
of the buffers is to isolate the PLD
from the PC. I felt that the additional
required circuitry was worth the effort
to protect the PLD, which is the most
expensive part of the circuit.

The SBLA design can be partitioned

into three parts: the PLD, the rest of the
hardware, and the Visual Basic program.
I’ll focus on the hardware. I’ll describe
the GUI and INI file, but won’t cover the
Visual Basic program’s internals. Photo 2
shows the main GUI screen and some of
the software’s analysis capabilities.

Because the bulk of the system logic

is in the PLD, I’ll begin by describing its
partitioning. There are several blocks
within the PLD: the address generator
and timebase, the trigger control, the
trigger detect, and the trigger latch.

The PLD must be a 10-ns device in

order to handle the 10-ns pulses from the
50-MHz oscillator. However, the RAM’s
12-ns write cycle time is adequate
because the minimum time between

FEATURE ARTICLE

by Larry Cicchinelli

Photo 1a—The top layer of the PCB contains the PLD, input buffer, and output buffer ICs. The 25-pin D connector,
which you can barely see at the upper left, connects to the parallel port of the PC. The nine-pin D is for the input sig-
nals. The RAM is under the PLD. A 5-V regulator is mounted to the box as well as the barrel connector for input
power.
b—Take a look at the assembled unit and the nine-pin D cable for the input signals. The cable is made from
two pieces of four-conductor flexible telephone cable with a separate wire for ground.
c—Here you see the main cir-
cuit (the PLD and the input buffer ICs). The 25-pin D connector on the right connects to the parallel port of the PC.

a)

b)

c)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

55

nal changes state every 4,096 samples;
therefore, it has a falling edge every
8,192 samples. Because it starts out
low, the first rising edge (occurring after
4,096 samples) is the earliest that a trig-
ger event can be detected.

The circuit basically operates as fol-

lows: first, the system sets the pre- and
post-trigger counters; second, the system
allows the pre-trigger counter to count;
third, it waits for the pre-trigger counter
to count down to zero; fourth, it waits
for a trigger event (latched by the sample
clock); fifth, it stores the address counter
value at the trigger event; sixth, it enables
the post-trigger counter; seventh, it waits
for the post-trigger counter to count down
to zero; and, finally, it signals to the
Visual Basic program that the system has
completed its sampling. Data sampling
starts with the second step and termi-
nates after the sixth. The address counter
is allowed to wrap around to a count

The timebase uses the same signals

but is only 6 bits. It drives an eight-
input multiplexer, which is used to
select the sample frequency/period.
Selection zero of the mux is used when
reading the stored data back to the PC.
Selection one comes directly from the
crystal oscillator. The six remaining
inputs come from the timebase divider.
This is currently set as a simple binary
divider. With a 50-MHz oscillator, the
available sample periods are 20, 40, 80,
160, 320, 640, and 1,280 ns.

These values may seem strange, but

the Visual Basic program can perform
calculations using the sample period so
it does not matter too much. I may
decide to enhance the divider to give
more conventional sample periods, but
these have served me quite well so far.
A 40-MHz oscillator gives more conven-
tional sample periods: 25, 50, 100 ns,
etc. The program allows you to define

the sample periods via the INI file. The
timebase multiplexer’s output is used to
drive both the address generator and the
write signal (*WE) of the RAM.

TRIGGER CONTROL

The trigger control subsystem starts

with the pre- and post-trigger count cir-
cuits, which are made with 4-bit, preset-
table down counters. These allow you
to select from any one of 16 pretrigger
counts. The pretrigger value can be set to
a multiple (0 to 14) of 8,192 samples,
starting with an offset of 4,096. If you’re
familiar with commercial logic analyzers,
you’ll recognize that this is considerably
less flexible than they are. However, I
have found that this capability is ade-
quate enough to meet most requirements.

The counters are driven by the A12

signal from the address generator. When
inverted, this signal provides the circuit
its 8,192-count resolution. The A12 sig-

Figure 1—Take a closer look at the PCB. Because most of the logic analyzer is contained in the PLD, this schematic is mainly the interface to and from the PLD.

background image

56

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

zero meets the trigger conditions. If it
doesn’t, the address bit 0 must be a one.

REMAINING CIRCUITS

Other circuits in the PLD include the

command function decode, the timebase
selection latch, the trigger condition val-
ues latch, and gating selected signals
back to the PC. The circuits external to
the PLD perform mostly buffering and
isolation. U2 and U3 are 74HCT245s.
Their main function is to isolate the
PLD from the cable to the PC.

U4 is a 74AHCT245. I used an AHC

device because I need the higher speed.
The standard HCT devices are not fast
enough for 50-MHz operation. Also, I
selected HCT devices instead of HC
because the output voltage levels of
the PLD only go up to approximately
3.5 V. All three could be AHCT, but I

of zero and begin counting up again.
Because the pre-trigger value and the
trigger event address are known, the soft-
ware aligns the data properly for viewing.

There are a number of control sig-

nals that are generated by this circuit.
Three are sent back to the PC as sta-
tus information. After the system has
been enabled, it displays each of these
values as the capture cycle progresses.

TRIGGER DETECT

The trigger detect circuit is simple

and, as a consequence, limited in its
capabilities. Because I wanted to keep
the system as small and as inexpensive
as possible, only the first four channels
are used for triggering. The following
possibilities are available: a channel is
disabled (trigger on any state); a channel
is enabled to trigger when the channel
is a logic 1; and a channel is
enabled to trigger when the
channel is a logic 0.

The circuit is essentially

an AND gate, so the selected
trigger condition for all four
of the channels must be met
in order to trigger the system.
Again, this is considerably
less flexible than commercial
units, although I’ve found it
adequate to meet my require-
ments. As I work on the
system, I may be able to
enhance its triggering capa-
bilities. This will be largely a
function of how much more
logic is available in the PLD.

TRIGGER LATCH

The trigger latch is perhaps

the simplest subsystem in the
logic analyzer; it’s simply a
16-bit latch. The trigger con-
trol circuit creates the latch
signal when the trigger event
is detected. The latch’s out-
put is gated to the PC 8 bits
at a time. Note that even
though there are 17 address
bits, the latch is only 16 bits.
Again, this is done as a cost-
saving measure. The software
can easily insert the seven-
teenth bit by looking at the
data and determining if the
address with bit 0 equal to

do not like to use high-speed devices
except where required. The 50-MHz
oscillator is a standard TTL/CMOS
part with no special requirements
other than a 50% duty cycle.

CONSTRUCTION NOTES

The devices mounted on the top of

the board include the connectors and
headers (except H1 for programming
the PLD), the two resistor networks, U5
(RAM), U6 (oscillator), and the bypass
capacitors. The devices on the other
side include U1 (PLD), U2, U3, U4, and
H1 (the PLD programming header). The
power socket is mounted on the box.

The construction process requires a

few deviations from normal construction
methods. I mounted the PLD in a socket,
which is an SMD type with J leads. I
chose this type in order to avoid having

to drill 84 holes in the board
and route signals between
pins. However, soldering the
leads presents a challenge.
The method I adopted
involves carefully bending
the socket leads one at a time
so that they protrude out
from the side of the socket.
This makes it look like an
SOIC socket. The operation,
which takes approximately
10 min., isn’t too difficult.

The RAM is also a J lead

package. Again, I bent the
leads out to make it essential-
ly an SOIC. I have not been
able to find a pin-compatible
RAM in an SOIC package.
There are fast RAMs available
as SOICs, but their pinouts
make them more difficult for
laying out the board.

There are three extra head-

ers on the board: J1, J2, and
J3. These are mainly used for
expanding the system to
16 channels. I hope to have
this feature fully implement-
ed in the future. However,
the headers are also used as
signal feed-through points.
So, if you are not planning
on implementing the second
set of eight channels, you’ll
need to solder jumper wires
in their place because the

Photo 2a—This display (Screen 0) shows all of the data collected (126,976 samples).
Study the results of two of the measurement capabilities of the system. The time
between Marker 1 and the cursor is –4.649 ms. (It is negative because the marker is
earlier in time than the cursor.) Also, note the decoded hex values of the serial data
between the marker and the cursor. The background color of the SO signal indicates
that the data has been inverted by the program. Logic 1 is displayed in red, and logic 0
is in black.
b—A shorter period of time (2,000 samples) is displayed in Screen 1. The
marker and cursor have been moved to include only the two initial transactions, both
of which are identical. The transactions identify the flash memory device for the con-
trolling program as well as verify that it is ready.
c—Note the shorter period of time
(1,000 samples) in Screen 2.

c)

a)

b)

background image
background image

58

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

there are not a lot of controls on the
screen. Arm initiates a capture and
display cycle. Draw, which redraws
the data, is used when you change
some of the operating parameters and
still want to use the captured data.
Other controls include Start and End
Sample, Cursor Position, Zoom In
and Out, Slide (move the view of the
data forward or backward), and
Screen, which allows you to choose
up to six different views (screens) of
the same captured data.

Photo 2 shows the serial communica-

tions between a microprocessor and a
serial flash memory device. The chip
select (CS) and clock and serial in (SI)
are generated by the microprocessor.
The serial out (SO) is data transmitted
by the serial flash memory. Note that
each is a different screen view. You can
switch among the different screens by
scrolling through them with the plus (+)
and minus (–) controls.

I

board does not have plated through holes.
If you choose to mount the connectors,
you’ll need to be careful because many of
the pins must be soldered on both sides
of the board. Inserting the connector
upside down and then pushing the plastic
insulation piece closer to the board after
soldering can easily accomplish this. I
suggest breaking loose the plastic spacer
from each pin before soldering.

There are several places where

hand-inserted feed-through wires must
be inserted. They are plainly indicated
in the documentation posted on my
web site (www.qsl.net\k3pto). The
10-pin header, which is only for pro-
gramming the PLD, isn’t required for
operation. The 2.1-mm jack and sock-
et are for power input.

The parts list posted on the Circuit

Cellar

ftp site doesn’t contain the bypass

capacitors I used because I had them in
stock. I don’t remember where I pur-
chased them. Any good high-frequency
bypasses will do.

I also haven’t shown the PCB. Because

I made my own, it would be difficult to
determine the total price of the materi-
als needed to etch it. However, I hope
to have Far Circuits make a board. If
there is enough interest, I will make a
kit available that will include a pro-
grammed PLD and a PCB.

INI FILE

The program uses an INI file for config-

uration information. It is similar in con-
struction to the Windows 3 INI file types.
I attempted to put every menu parameter
in this file. I still prefer this technique as
compared to putting everything in the
registry. There are some items in the INI
file that are not currently available via
the menus: the parallel port address, a list
of available sample periods, and a name
to appear in the title bar.

The first time the program runs it

looks in the same folder as the program
for DSO.INI. If it is not there, a window
pops up that allows you to find one.
After the program is run, it saves the
path of the last used INI file in the reg-
istry and will use the file when the pro-
gram restarts. This is the only item
stored in the Registry.

The sample file, as well as the

Windows Help file, fully describes the
INI file’s syntax. You must edit it at least

once to register your name, which will
appear on the title bar, and to insert the
address of your parallel port. After
doing so, the values will be copied to all
of the subsequently saved INI files.

I recommend having an INI file

associated with each of your projects.
This is faster than going through each
of the menus.

SOFTWARE

I wrote the program in Visual Basic 6. I

obtained a printer port driver DLL from
www.LVR.com. Because the program
is based on my DSO/LA, you’ll see a
number of references to it. These can be
ignored because the same program is used
for both devices. I have not attempted to
change every occurrence of DSO/LA
because it doesn’t affect the operation of
the program. The Help system points out
the differences where appropriate.

I have tried to make the program as

easy and as intuitive as possible. There
are few menus, and I believe they are
reasonably easy to navigate. The main
menu has several selections.

The File selection allows you to oper-

ate on the INI file as well as data. You
can store and retrieve the acquired data
in either the binary or CSV format. All
configuration information is stored in
an INI file of the same name as the data
file but with the appropriate file type.
You can also save and retrieve any INI
file you wish.

The Boards selection allows you to

name each channel as well as enable and
disable and optionally invert selected
channels. The Trigger selection allows
you to select the trigger state for each
channel and the pretrigger count. The
Display selection is primarily the zoom
and slide factors as well as the timebase.
Markers enables and disables up to four
time markers. The Function Keys selec-
tion shows and executes function key
commands. Measurements enables asyn-
chronous and synchronous (SPI) decod-
ing. Help is an extensive help feature
that uses the old style of Windows help.
The Debug selection debugs the hard-
ware and loads dummy data so you can
play with the display capabilities.

SYSTEM OPERATION

Operating the system is simple. As

you can see from the screen shots,

Larry Cicchinelli holds a bachelor’s
degree in Electrical Engineering from
Drexel Institute of Technology and a
master’s degree in Engineering Science
from Pennsylvania State University. He
has been an amateur radio operator
(K3PTO) since 1961 and holds an
advanced class license. Larry currently
works as a Technical Support Manager at
Z-World. Previously, he spent more than
30 years designing automatic test equip-
ment for automotive electronics and
integrated circuits for Visteon Corp. You
may contact him at k3pto@arrl.net and
visit his web site www.qsl.net\k3pto.

SOURCES

ATF1508AS CPLD
Atmel Corp.
www.atmel.com

74HCT245 Transceiver
Philips Semiconductors
www.semiconductors.philips.com

CY7C109B
Cypress Semiconductor Corp.
www.cypress.com

PROJECT FILES

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

background image
background image

60

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

T

he advent of low-cost, versatile,

high-performance analog building blocks
allows you to revisit earlier designs and
deliver solutions featuring better stabili-
ty and higher accuracy than could have
been economically achieved with legacy
designs. This article examines one such
scenario in which the temperature sensor
conditioning and acquisition subsystem
of a Bowen ratio data acquisition system
were redesigned. It provides insight into
the versatility available through the use
of such devices, in this case, the Maxim
MAX1463 dual-channel signal processor
integrated circuit. The cost of entry for
experimenting with these devices is rela-
tively low because no hardware develop-
ment platform is necessary and free soft-
ware development tools are available
from the relevant manufacturers.

BOWEN RATIO

The Bowen ratio data acquisition sys-

tem is used to determine temperature
and water vapor gradients
using energy balance Bowen
ratio techniques. The Bowen
Ratio, which is named after
an American astrophysicist
Ira S. Bowen (1898–1978), is
the ratio of sensible heat loss
per evaporative heat loss. The
original system that was the
basis for this article measures
wet and dry bulb air tempera-
tures at two heights, net radi-
ation, and soil heat flux.

For temperature measure-

ment, one pair of wet and
dry bulb sensors is located
1.0 m above the vegetation
canopy. The second pair of
sensors is located approxi-

errors. The bridge uses two-wire RTD
sensors. The resistance of the RTD sen-
sor cables affects the measurements.
The sensor cable resistance depends
nominally on the cable material, diame-
ter, and cable length. Because of the low
values of resistance involved for sensing
temperature changes, it is necessary to
balance the bridge using the actual cable
that will be used in the deployment.

Contact resistance from screw termi-

nals, for example, will also be a source
of errors. To minimize this particular
issue, the cables are usually soldered at
the sensor end and at the signal-condi-
tioning end. The system starts to get a
bit unwieldy because the sensors, with
their associated cables, are tied to the
system from the time it is calibrated
until the experiment is completed.

The cables themselves affect the sen-

sor readings in other ways. As the cables
are exposed to temperature variations,
they expand and contract with resulting

resistance changes that affect
the sensor readings. This
effect may be different
between the various cables as
a result of other environmen-
tal conditions. The cables
will oxidize when exposed to
typical field environments.
This results in a change in
resistance of the cable over
time. In order to minimize
some of these effects, a typi-
cal Bowen ratio system peri-
odically rotates the upper and
lower sensors via a rotating
arm assembly. This intro-
duces another potential
source of errors because the
cables are mechanically

Intelligent Sensor Head

FEATURE ARTICLE

by Andrew Smallridge

mately 1 m above them. The tempera-
ture-sensing subsystem determines the
wet and dry bulb temperature gradients
between each of the sensor pairs. The
temperature sensors are two-wire plat-
inum RTD elements with a nominal
resistance of 100

at 0°C and a rela-

tively linear transfer function of nomi-
nally 0.385

per 1°C.

As you can see in Figure 1, the RTD

sensors are located in two arms of a
bridge. The R

NULL

resistor is used to

null the bridge when the temperature at
RTD1 and RTD2 are the same. A subse-
quent temperature differential between
sensors RTD1 and RTD2 will produce a
voltage across the bridge proportional to
the temperature differential.

There are a number of issues with

this classic design. In order to resolve
temperature gradients of 0.01°C, the
system must be able to resolve differen-
tial resistance values of 3.85 m

. Let’s

examine some of the main sources of

Andrew redesigned the temperature sensor conditioning and acquisition subsystem of a
Bowen ratio data acquisition system. He used intelligent sensor heads connected via a digital
communication bus to a centralized logging unit.

Figure 1—On the left is a simplified representation of the dry bulb temperature signal-
conditioning circuit used in the original system. On the right is the same configuration
taking cable resistance into account. Resistors Rx-1 and Rx-2 represent the lead
resistance of the cable between the relevant RTD sensor and the conditioning circuit-
ry. For the reference dry temperature (TD), you want to measure VTD. But at the con-
ditioning circuit, you end up measuring VTD + VR1-1 + VR1-2.

R

R

TD2

R

NULL

R

TD1

VTD

v

R

R

TD2

R

NULL

R

TD1

VTD

V

CC

V

CC

R2-2

R1-2

R1-1

R2-1

v

background image
background image

62

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

eliminate (or minimize) the errors associ-
ated with the current solution. I also
wanted to simplify system calibration
and make it easy to service the system
components. In addition, I sought to
remove the affect of the sensor cables on
the temperature readings, improve the
power supply rejection ratio, and digitize
the temperature value reference to the

stressed. Replacing a cable requires
the bridge to be recalibrated, which is
a task not easily performed in the
field without affecting the results of
the experiment.

Referring back to Figure 1, note that

the magnitude of the voltage differential
across the bridge is also a function of the
supply voltage (V

SUPPLY

). The higher the

applied voltage across the bridge, the
higher the differential voltage between
the two bridge arms for a given tempera-
ture differential. The power supply rejec-
tion ratio of this type of circuit is poor.

The voltage across the RTD sensor

RTD1 is used for the dry temperature
measurement. RTD sensors have
excellent linearity. However, because
this circuit is not excited with a con-
stant current, the voltage across the
RTD sensor does not vary linearly
with temperature. The sensor voltage
can be expressed as the following:

Correction for the nonlinear trans-

fer function must be made either in
the data acquisition system or during
subsequent downstream data pro-
cessing. When performing subse-
quent A/D conversion on the tem-
perature sensor output voltages,
V

SUPPLY

should be referenced in order to

cancel out the effects of the low-power
supply rejection ratio. Failure to account
for the power supply rejection ratio will
introduce unnecessary absolute errors.

DESIGN OBJECTIVES

My design objectives for the new solu-

tion were straightforward. I wanted to

V

R

RTD

NULL

1

100

=

V

+ 0.385T

+ 100 + 0.385T

SUPPLY

(

)

Sensor
head 0

Sensor
head 1

Sensor
head x

Master

acquisition

unit

(logger)

• •

To local
sensors

To local
sensors

To local
sensors

Power distrubution

and RS-485 bus

Figure 2—The sensor heads share an RS-485 commu-
nications bus. Communication between the sensor heads
and the MAU is via a simplex communications protocol.

Photo 1—The PCB is double-sided with the balance of the
passive components mounted on the underside of the PCB.
This sensor head is shown populated with a single signal
processor, but it was designed to support two.

Figure 3—A smaller series microcontroller could be used in place of the PIC18F252. It is clear that most of the PIC I/O is unused. This PIC was selected for the large RAM
and flash memory space. Multiple MAX1463 images could be stored in the PIC.

background image

Schematic and PCB Layout

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

Mixed Mode SPICE Circuit Simulation

• Berkeley SPICE3F5 simulator with custom extensions for

true mixed mode and interactive simulation.

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

Proteus VSM - Co-simulation and debugging for

popular Micro-Controllers

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

controllers.

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

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

• Provides source level debugging for popular compilers

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

R4

www.labcenter-electronics.com

EASY TO USE CAD TOOLS AT FANTASTIC PRICES

MicroChip PIC 18

• Supported models of the PIC 18 includes PIC18F242,

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

Basic Stamp BS1 and BS2

• Proteus VSM for BASIC Stamp contains everything you

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

• See examples in downloadable Demo at

www.labcenter-electronics.com

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

DAN GILL

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

I consider Proteus to be pivotal in the commercial viability

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

ROB YOUNGS, Tempus Consulting

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

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

Electronic & Wireless World CAD Review Roundup

FREE

DOWNLOADABLE

DEMO

Save Time. Save Money.

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

“This is clearly superior in every respect.”

Virtual System Modelling

SYSTEMS
INC

.

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

background image

64

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

sensor-conditioning circuitry. Finally,
I thought it important to generalize
sensor calibration to simplify replace-
ment and to enable single-point tem-
perature reference checks.

The new design is based on the concept

of one or more intelligent sensor heads
connected via a digital communication
bus to a centralized master acquisition
system or logging unit. For temperature
measurement, the sensor heads perform
signal conditioning and data acquisition
as close to the sensor as possible (see
Figure 2). The sensor head was designed
to be as small as practical in order to be
incorporated into existing Bowen ratio
rotating arm assemblies without unduly
adding to the mass (see Photo 1).

Platinum RTD sensor elements were

retained as the temperature sensors
because of their excellent stability, lin-
earity, and interchangeability character-
istics. The major issues associated with
two-wire RTD temperature measure-
ment were addressed by going to a four-
wire sensing system. The RTDs were
excited via a constant current source
that also forms part of the referencing

ISRC

INP1

INM1

INP2

INM2

V

DD

ISRC

Temperature

sensor

MUX

CO

DAC

Σ

+

ADC

PWM

1

DAC

1

LG

+

+

SM

LG

+

+

SM

PWM

2

DAC

2

16-bit

CPU

Serial

interface

AMP1P

OUT1LG

SCLK

DI

D0

*CS

4-KB

Flash

memory Power

on

reset

V

DD

V

DDF

V

SS

Digital

I/O

External

reference

input

Bandgap

reference

output

AMP1M

OUT1SM

AMP2P

OUT2LG

AMP2M

OUT2SM

VBG

V

REF

CKI0

CKSEL

GPI02

GPI01

PGA

Figure 4—As you can see, the MAX1463 functional diagram outlines the major building blocks.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

65

system. Data acquisition is performed
against a ratiometric measurement of
the voltage across the RTD against a
reference resistor. The schematic for
the sensor head is shown in Figure 3.

The sensor head has five subsystems,

comprising the power supply, the RS-
485 communications system, the
PIC18F252 sensor head controller, and
the MAX1463 signal processors. The
schematic and the PCB layout support
two MAX1463 signal processors per
PCB; however, the lower signal proces-
sor, U1, is not yet supported in software.
The PIC is connected to the MAX1463
signal processors via a serial peripheral
interface. This interface is used for
transferring data from the MAX1463 to
the PIC and also for downloading code
from the PIC to the MAX1463.

The PIC is responsible for supporting

the basic simplex communications proto-
col over the RS-485 communications bus
to the master acquisition unit. Its inter-
nal EEPROM holds sensor head-specific
calibration information, and it performs
offset and span adjustments for the
acquired data. The PIC has been imple-

mented with an embedded bootstrap
loader (bootloader), which enables new
code to be downloaded to the PIC via the
RS-485 interface. The bootloader imple-
mented in the PIC is conceptually simi-

lar to the bootloader described in my arti-
cle “Ethernet Bootloader” (Circuit Cellar,
issue 166, May 2004). The bootloader has
been extended to support bootloading of
the MAX1463 signal processor over the
interconnecting SPI bus between the
PIC and the MAX1463 signal processors.

MAX MAGIC

The MAX1463 is where the magic is

performed. This is an amazing device
for the price. The MAX1463 is a high-
ly integrated, low-power, two-channel
sensor signal processor with all the
necessary building blocks to support a
diverse range of signal conditioning
and data acquisition (see Figure 4).

The MAX1463 signal processor

includes analog multiplexers and an A/D
converter with programmable gain and
course offset. It contains two D/A con-
verters, two pulse-width modulators,
four op-amps, and a voltage reference. An
external reference input, programmable
current source, an internal temperature
sensor, and SPI interface are also fea-
tured. Finally, note that in addition to
two I/O lines and a 4-MHz oscillator,

V

CC

ISCR

R1-1

R1-2

R1-3

R1-4

R2-2

R2-3

R2-1

R

TD2

R2-4

R

REF

V

REF

V

TW

V

TD

R

TD1

Figure 5—This simplified schematic shows the constant
current, I

SCR

, generated by the MAX1463 excited by both

of the RTD sensors attached to the head. It generates
the reference voltage used for the A/D conversion.

background image

66

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

the processor contains a 16-bit RISC
CPU with 4 KB of flash program mem-
ory and 128 bytes of flash user memory.

What isn’t obvious from the diagram

is the power control subsystem enabling
the different elements to be powered
down for low-power applications. The
CPU is a 16-bit RISC processor on a
diet. It has just 16 instructions and is
therefore relatively easy to learn the
instruction set. Maxim also provides an
extremely simple free C compiler,
although I think it is more accurately
described as a proof-of-concept tool.
Having said that, the MAX1463 code
used by this application was written
using the supplied C compiler.

The MAX1463 user’s application pro-

gram controls the operation of the ana-
log subsystems. It is possible to drive the
analog subsystems directly via the SPI
interface. The control interface between
the MAX1463 CPU and the outside
world is via 16 ports—each 16 bits
wide—accessed via the SPI interface.
Through these ports, the PIC’s applica-
tion program extracts the sampled data
from the MAX1463 and programs the

MAX1463’s flash memory. The
MAX1463 also includes 128 bytes of
memory that can be accessed only via
the SPI. This is intended to store infor-
mation, such as calibration coefficients,
to be accessed by external devices like
the PIC18F252 but not the internal
processor of the MAX1463.

Maxim positions the MAX1463 as a

dual-channel signal processor; but, in
reality, it handles many channels. The
chip has two differential input channels
that can be sampled both as differential
inputs and as single-ended inputs. The
chip also allows several internal nodes
to be measured including the outputs of
the op-amps. Your application program,
running in the MAX1463, could config-
ure one or more of the uncommitted
op-amps as unity gain followers,
enabling the corresponding voltage on
the op-amp’s INP pin to be presented at
the output of the op-amps, thus making
them available to be processed by the
embedded ADC subsystem.

Figure 5 shows the simplified schemat-

ic implemented with the MAX1463 for
the temperature conditioning and acquisi-

tion. RTD1 and RTD2 are the tempera-
ture sensors. R1–1 to R1–4 and R2–1 to
R2–4 represent the lead resistance of the
cables between the sensor head electron-
ics and the sensors for RTD sensors 1 and
2, respectively. The input impedance of
the MAX1463 differential inputs is orders
of magnitude higher than the resistance
of the RTD probes and the wire resist-
ance. Therefore, the current into these
inputs—as well as through R1–2, R1–3,
R2–2, and R2–3—can be ignored.

The MAX1463 is configured to gen-

erate a constant current of approxi-
mately 1 mA. This current flows
through both RTD probes and the ref-
erence resistor R

REF

(actually R13 in

Figure 3). The voltage presented to the
MAX1463 differential input is the
voltage developed across the corre-
sponding RTD sensor because the
voltage drop across the cable RW1–2,
RW1–3 (RW2–1, RW2–3) resistance
between the RTD probe and the differ-
ential inputs is insignificant.

I

SRC

excites the RTD probes and gen-

erates the reference voltage used in the
A/D conversion process. Therefore, any

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

67

drift associated with I

SRC

is cancelled.

The resulting conversion, which is a
ratiometric conversion of the sensor
and reference voltages, is essentially
independent of the supply voltage. The

reference resistor R

REF

(R13) is a 0.1%

precision resistor. In fact, the compo-
nent’s tolerance is not important.
What’s important is the resistor’s stabil-
ity—its temperature coefficient.

The MAX1463 provides programma-

ble course offset and gain to the select-
ed sensor differential input. The A/D
converter operates on the selected
input. The output from the conversion
process is then written, under applica-
tion control, to one of the output ports
for subsequent transfer to the PIC.

The PIC is responsible for the final off-

set and gain corrections. It wasn’t neces-
sary for these corrections to be made in
the PIC; they could have been made in
the MAX1463. This was a design choice.
At this point, the sensor head provided
the necessary sensor conditioning to
enable the sensor head to deliver the
overall performance approaching the
inherent repeatability of the sensor. This
enables sensor heads to be changed with-
out recalibration. Additional offset cor-
rection can then be applied by the PIC to
correct for sensor-specific transfer coeffi-
cients if required.

MAX1463 CODE

Listing 1 contains an extract of the

source code for the MAX1463. Enough
of the source code has been included
here to show how it works and to
demonstrate the versatility of the
device. You may download the code
from the Circuit Cellar ftp site.

The MAX1463 performs initialization

code, powering up the ADC, setting the
I

SCR

to 1 mA, and setting the general-

purpose I/O pins (GPIO) low. The pro-
gram enters the main loop where it
waits for 5 ms before asserting GPIO1
low, signifying that the MAX1463 is
busy. The PIC monitors this pin to
determine when the MAX1463 is ready
to be read by the PIC.

The ADC is then initialized to perform

a differential conversion of channel 1
with the appropriate resolution, conver-
sion clock rate, gain, and course offset
settings for the RTD sensor connected to
channel 1. The ADC reference for the
conversion is the external reference pin
that connects to R13. The program then
initiates an A/D conversion and stores
the result in port P0. The MAX1463 CPU
is automatically shutdown during the
conversion process. This prevents any
noise generated by the CPU subsystem
from influencing the conversion result.

The next section of code shows the

same channel being used for a single-

Listing 1—This code snippet for the MAX1463 is enough to show you how it works.

// Port assignments

// Port P0 = ADC result RTD Probe A

// Port P4 = ADC result INP 1

// Pin 16 GPIO1 = Interface to RTD PIC

// Pin 17 GPIO2 = Interface to RTD PIC

// Pin 24 ISRC = about 1mA - RTD excitation.

main () {

// Enable ADC

A_PO_CONTROL = PWR_ADC;

// Pin 24 ISRC = about 1 mA

A_CS_CNTROL = CS_1099uA;

// Turn off the GPIO LEDs.

A_GPIO1_CONTROL = GPIO_OUTLOW;

A_GPIO2_CONTROL = GPIO_OUTLOW;

loop:

// Set up the timer 5 ms between samples

A_TMR_CONFIG = TMR_CONFIG_5ms;

// Clear the MAX1463 idle flag

// This output is set high at completion of conversion and is

// used by the PIC to initiate a read of the MAX1463 ports.

A_GPIO1_CONTROL = GPIO_OUTLOW;

// Initialise ADC Channel 1 for RTD sensor measurement

// ADC Gain = 22.2 V/V

// ADC clock 31.25 kHz

// ADC resolution = 16 bits

// CO = –117%

// Bias = Full

// ADC reference = external

A_ADC_CONFIG_1A = CONFIGA_PGA03 | CONFIGA_CLK5 | CONFIGA_RES16 |

CONFIGA_COF;

A_ADC_CONFIG_1B = CONFIGB_BIAS7 | CONFIGB_REF1;

A_ADC_CONTROL = CNVTADC1;

// Trigger an ADC conversion

P0 = A_ADC_DATA_1;

// Raw value read from ADC

// Perform Unity Gain Measurement of INP1

// Initialise ADC Channel 1 for single ended sensor measurement

// ADC gain = 0.94 V/V

// ADC clock 31.25 kHz

// ADC resolution = 16 bits

// CO = +3%

// Bias = Full

// ADC reference = VBG x 4 = 5.0 volts

A_ADC_CONFIG_1A = CONFIGA_PGA00 | CONFIGA_CLK5 | CONFIGA_RES16 |

CONFIGA_CO0;

A_ADC_CONFIG_1B = CONFIGB_BIAS7 | CONFIGB_REF2;

A_ADC_CONTROL = CNVT_SE_INP | CNVTADC1;

// Trigger an ADC conversion

P4 = A_ADC_DATA_1;

// Raw value read from ADC

A_TMRCONTROL = TMRCONTROL_TMEN | TMRCONTROL_ENAHALT;

// Signal at the end of the active processing loop

A_GPIO1_CONTROL = GPIO_OUTHIGH;

// Set up the timer 1 ms between samples

A_TMR_CONFIG = TMR_CONFIG_20ms;

// Halt the CPU until the timer expires

// During the period, the MAX1463 CPU is halted the PIC can

// non-disruptively read all the ports.

A_TMRCONTROL = TMRCONTROL_TMEN | TMRCONTROL_ENAHALT;

goto loop;

}

background image

ended conversion with completely dif-
ferent conversion metrics. In this case
an input voltage on INP1 in the range
of 0 to 1 V is being converted. This
code segment demonstrates some of
the flexibility of the MAX1463. It is
capable of converting signal sources
spanning a wide dynamic range with-
out hardware changes.

After completion of the final conver-

sion, the GPIO line is set high, thus sig-
naling to the PIC that the MAX1463 has
completed the current conversion loop.
The MAX1463 now lays idle for 20 ms
while the PIC reads the MAX1463 ports
to the PIC via the SPI bus. The PIC only
reads the MAX1463 after a low-to-high
transition has been seen on the GPIO1
pin. This ensures the PIC only reads the
MAX1463 during idle times to prevent
the PIC from corrupting a conversion in
progress. After the 20-ms idle period has
elapsed, the MAX1463 repeats the data
acquisition loop.

PIC OPERATION

The PIC has two basic modes of

operation, Bootloader mode and User
mode. The former is used to download
user programs to the sensor head over
the RS-485 interface. It is entered
whenever the PIC is reset and remains
there for 2 s before executing the code
in your memory space.

The bootloader remains in Bootloader

mode if it receives a capture command
via the RS-485 interface. In Bootloader
mode the PIC accepts Intel format hex
files records and uses them to program
itself or program the MAX1463 via the
SPI bus. Sensor head coefficients are
transferred to the PIC EEPROM in
Bootloader mode. Programming the sen-
sor head is a four-part process: First, the
bootloader code is programmed into the
PIC via standard in-circuit serial pro-
gramming (ISCP) techniques. Header
J2 is the ICSP header. Following this,
the MAX1463 code is programmed via
the bootloader.

Next, the sensor head PIC code can be

programmed into the PIC via the boot-
loader. The RTD_Head.HEX file is the
PIC’s application program. Finally, the
sensor head coefficients are programmed
into the PIC’s EEPROM via the boot-
loader. This contains sensor head serial
number and channel information as

well as specific gain and offset correc-
tion to be applied to data read from the
MAX1463. The generic_head.asm file is
an operational example coefficient file.

The sensor head record structure for

records transmitted from the sensor
head is defined in the RTD head.asm
file. You may download the project
files from the Circuit Cellar ftp site.

PIC USER PROGRAM

The PIC program is responsible for

managing communications to the
master acquisition unit (MAU), or any
controlling device, over the RS-485
interface. The communications proto-
col is simplex-based. A sensor head
does not initiate communications, it
responds to commands received via
the RS-485 interface.

There are two types of commands,

directed and broadcast. A directed
command is sent specifically to the
serial number of the sensor head. The
sensor head responds immediately to
a directed command.

The sensor head serial number infor-

mation is stored in the PIC’s EEPROM,
as is the channel number or window
used for arbitration to the RS-485 bus.
A window is a 26-ms time slot. When a
sensor head receives a broadcast com-
mand it waits for its time slot before
responding. For example, if a sensor
head is assigned channel 2, it responds
to a broadcast command between 52
and 78 ms after receipt of the broadcast
command. In reality, it responds with-
in 5 ms of its window start time, so
the sensor head in this example will
respond 52 to 57ms after receipt of the
broadcast command.

Why did I implement this time divi-

sion multiplexed system? It was sim-
ple, reliable, and did not require spe-
cial tools to support the application.
Provided you have access to a RS-485
interface, you can communicate to
the sensor head with a basic terminal

or terminal emulation program. The
master acquisition unit (MAU), which
isn’t described in this article, has both
RS-232C and RS-485 ports. The MAU
also has a bootloader, and can be put
into Transparent mode, where it
echoes all characters between the RS-
232 and RS-485 interfaces.

All serial communications use stan-

dard printable ASCII characters.
Although inefficient because a hex value
must be sent in two ASCII characters,
it’s extremely simple to code and debug.

The current software supports a sin-

gle broadcast command, which is a sin-
gle character (*). After receiving this
character, all the sensor heads start their
channel timers. When a sensor heads
channel timer expires, it transmits the
processed data to the RS-485 interface.

The PIC is in a continuous loop,

scanning to see if the MAX1463
requires service and searching for com-
mands, broadcast or directed, from the
RS-485 interface. When a low-to-high
transition is detected on GPIO1 from
the MAX1463, the PIC uploads all
16 user ports from the MAX1463 via
the SPI interface. The PIC then per-
forms local signal conditioning by
applying the zero and span coefficients
as defined in the EEPROM.

CALIBRATION

Generic sensor head calibration is

required to produce a standard output
for a given input. Let’s examine a real-
world example to see what’s required
to perform a calibration.

On channel 1 of the MAX1463, you

have an RTD sensor with a nominal
resistance of 100

at 0°C and the

resistance changes 0.385

per 1°C. I

am interested in producing an output
in the range of 0 to 10,000 correspon-
ding to 0° to 100°C (1 bit per 0.01°C).
The MAX1463 has been configured for
the RTD sensor as per Listing 1 for
gain, offset, and so on. First, apply a
precision 100-

resistor in place of the

RTD and initiate a conversion noting
the result (ideally multiple readings
averaged over time). I use 1-s samples
averaged more than 5 min. for this pur-
pose. Note the average reading is
Reading_R0. Second, replace the 100-

resistor with a 138.5-

precision resis-

tor and repeat for Reading_R100. Third,

68

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Parameter

Hex value

Reading at 100

20CD

Calculated offset adjustment

DF31

Reading at 138.5

6582

Calculated gain

48C5

Table 1—These coefficient parameters condition a
generic RTD sensor channel.

background image

sor with a feature-rich microcontroller.
Moving the sensor conditioning and
processing to the sensor and imple-
menting a shared power and commu-
nication bus architecture removed sev-
eral sources of error compared to the
original system. At the same time,
this greatly simplified the process,
spanning calibration, field deployment,
and ongoing field support. Hopefully,
there are sufficient information and
tools available on the Circuit Cellar
ftp site as well as Microchip and
Maxim’s web sites for you to quickly
get up to speed with these products
and the overall system architecture. If
you have any comments or sugges-
tions, feel free to drop me a line.

I

calculate the offset. The offset is the
two’s complement of the zero reading.
Fourth, calculate the following.

Table 1 is an example of coefficient
parameters used to condition a generic
RTD sensor channel.

But wait, I wanted better zero adjust-

ment than a generic calibration could
afford me. I required something better
than what can be achieved with just
standard sensor interchangeability. One
of the unicast (directed) commands sup-
ported by the PIC is a user-configurable
zero offset adjustment. The base gain
and offset parameters are stored in EEP-
ROM via the bootloader, whereas the
user zero offset adjustment is handled
by the user’s application program in the
PIC. This is used when a calibrated
generic head requires an offset adjust-
ment to compensate for offsets of a spe-
cific sensor. The user-configurable off-
set adjustment is added to the base
offset adjustment, and then added to
the reading being conditioned.

PIC18F252 BOOTLOADER

The bootloader code resides in the

upper 4 KB of the program memory
space. Because the program memory is
flash memory-based, user-configurable
optional parameters are stored in this
space. The EEPROM memory space
internal to the PIC is preserved by the
bootloader, which transparently uses

_

(

)

calculate the gain =

Reading_R0

10,000 × 32,768

100

Reading R

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 four instructions. The
bootloader code includes a

RESET

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

GOTO instruction

in the first four instructions, then the
RESET instruction is executed. More
information on the operation of the
bootloader and supporting application
along with a step-by-step example of
using the bootloader to download code
and data to the sensor head is described
in the “Intelligent Sensor Head” file
located on the Circuit Cellar ftp site.

MAU & RTD LOADER UTILITY

The loader utility works in conjunc-

tion with the bootloader in the
PIC18F252. It’s used for transferring pro-
gram code and coefficients to and from
the PIC18F252 and MAX1463. Photo 2
shows that the sensor head’s bootloader
has been captured and the Max-
RTD.hex file has been programmed into
the MAX1463 via the bootloader. The
status information is displayed in the
right-hand memo pane. The MAU Reset
buttons and the Set Transparent buttons
are not used by the sensor heads.

WINDING DOWN

The MAX1463 and the PIC18F252

make a formidable pair, combining the
strengths of a powerful signal proces-

Photo 2—The MAU and sensor head programmer utility is used to program the user code and calibration coeffi-
cients into the PIC as well as to program the MAX1463 application code into the signal processor.

Andrew Smallridge is a keen electron-
ics enthusiast. He holds a diploma in
Electronic Engineering and a post-
graduate diploma in Computer
Science. You may contact him at
asmallri@westnet.com.au.

PROJECT FILES

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

RESOURCES

P. Cruiziat and H. Richter, “Heat
Dissipation from Leaves: The Bowen
Ratio,” Plant Physiology Online,
2002, www.plantphys.net/article.
php?ch=t&id=132.

Honeywell, “Temperature Sensors:
Platinum RTDs,” content.honeywell.com
/sensing/prodinfo/temperature/technical
/c15_136.pdf.

Maxim, “Low-Power Two-Channel
Sensor Signal Processor,” 19-2549, rev. 0,
2002.

Max1463 development software,
www.maximic.com/tools/evkit/software
/1463R13.ZIP.

SOURCES

MAX1463 Two-channel signal processor
Maxim Integrated Products
www.maxim-ic.com

MPLAB IDE, PIC18F252 Microcontroller
Microchip Technology, Inc.
www.microchip.com

Issue 171 October 2004

69

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

heavyweights trade blows, it is ASICs
that are going down for the count.

OPENING BELL

Understanding where we are requires

understanding where we started. The
modern era of programmable logic began
in the 1970s when a somewhat small
and obscure Silicon Valley company
called Monolithic Memories leveraged
its niche bipolar (fast) PROM know-how
into what they called programmable
array logic (PAL). Essentially, PALs were
a variation of PROMs comprised of
AND gates feeding OR gates with a
fuse-programmable interconnect (see
Figure 2). A PAL, programmed with a
few Boolean equations (i.e., sum of prod-
ucts) could replace a handful of the then
popular 74xx TTL chips.

Founded in 1983, Altera took the

concept of what they called a pro-
grammable logic device (PLD) further
by using a CMOS EPROM process
that not only consumed much less

70

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

I

n terms of a marketing slogan, “We’re

Number Two” doesn’t really strike a
chord. Thus, it was way back in 1963
that the Avis rental car company, in
their quest to overtake leader Hertz,
came up with the “We Try Harder”
catchphrase, thereby morphing their run-
ner-up status into a virtue. According to
Advertising Age

magazine, it’s one of the

top 100 advertising mottos of all time.

[1]

This story comes to mind as I con-

template the latest rash of announce-
ments from Altera. With revenues of
$827 million in 2003, Altera is cur-
rently number two in the programma-
ble logic business behind leader Xilinx
($1.16 billion revenue in 2003). But it
wasn’t always so. Indeed, during the
late 1990s, Altera was number one
(see Figure 1).

If “We’re Number Two” doesn’t cut it,

certainly “We Once Were Number One,
But Now We’re Number Two” would be
even worse. How about “We Try Harder
To Try Harder”? Just kidding.

Putting the financial pages

aside, suffice it to say that the
competitive jockeying is good
news for customers. Between
the battle for bragging rights and
the march of silicon, designers
everywhere are the winners as
these programmable logic
heavyweights trade punches.

Altera recently countered

with a flurry of parts that
could well close the gap. Of
course, Xilinx can take a
punch and will no doubt
return the favor. Rather, as
these programmable logic

power, but also allowed parts to be
erased (albeit with an ultraviolet
lamp) and reprogrammed in the field.

At about the same time, Xilinx intro-

duced what they called the field-
progammable gate array (FPGA) with
two unique differences. First, the all-
important reprogrammability was
achieved by using SRAM rather than
EPROM. Second, the FPGA’s internal
architecture was rather different than
that of PAL’s and PLD’s, relying on look-
up table (i.e., SRAM-based) configurable
logic blocks rather than simple AND
and OR gates. With small packages (e.g.,
20 pins), PLDs were typically used for
discrete signals and random logic, while
higher pin-count FPGAs could handle
buses and datapath processing.

Thus, in the early years Xilinx and

Altera didn’t really directly compete
with each other. PLDs weren’t too
dense, but they were fast and relatively
inexpensive to buy and use as a TTL
replacement. By contrast, FPGAs were

expensive and kind of fussy
(what with the need to initial-
ize the SRAM at power-on), but
could handle larger roles that
would otherwise require a cus-
tom chip or gate array.

But it was only a matter of

time before the company’s
sales forces began bumping
into each other in purchasing
lobbies. In the mid-to-late
1990s, both Altera and Xilinx
made grass-is-always-greener
moves onto the other’s turf.
Xilinx came up with its own
flash memory-based PLD (the

Try Hard with a Vengeance

SILICON UPDATE

by Tom Cantrell

Altera and Xilinx are fighting for the largest share of the programmable logic market. This
month, Tom brings you up to speed on this protracted game of tit-for-tat. Read on to learn
about the newest parts Altera has brought into the fray.

Figure 1—What a difference a year makes. In 2000, Altera was comfortably
in the lead, only to fall to barely half the sales of archrival Xilinx by 2001.

0

200

400

600

800

1,000

1,200

1,400

1,600

1,800

Altera 402 497 631

654 837

839

712 827

355 561 568

614 662

1995 1996 1997 1998 1999 2000 2001 2002 2003

Year

Xilinx

1,377
1,021 1,659 1,016 1,156

Re

ve

nu

e (millions of dollars)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

71

XC9500) and reinforced the move in
1999 by acquiring the Coolrunner
PLD line from Philips. Meanwhile,
Altera was giving SRAM-based FPGAs
a go with their FLEX lineup.

My take is that the late 1990s saw

Xilinx get the better of the exchange.
Considering the relative device and
tool complexity, it was somewhat eas-
ier and cheaper for Xilinx to get into
PLDs than Altera into FPGAs. Put it
all together and I think it explains the
shift in bottom lines, with Xilinx
moving into the lead.

STRUT YOUR LUT

It’s no surprise that Altera would

try harder by reinforcing their historic
PLD leadership with the new MAX II
line. The only surprise is that MAX II
isn’t a PLD.

Altera calls MAX II a CPLD, with the

C standing for “complex.” Certainly, they
have the right to call it whatever they
want. But lift the hood, and you’ll see
something that looks a lot more like an
FPGA than a traditional PAL-like PLD.
Most notably, MAX II is look-up table-
based—a clear break from the PALs of
yore (see Figure 3). According to Altera,
the traditional macrocell everything-con-
nects-to-everything routing approach
explodes as device density increases,
compelling the switch to LUTs.

That’s just the start. A comparison

between MAX II and the company’s earli-
er MAX devices, not to mention any
other traditional PLD, shows there’s little
similarity beyond the names. The trans-
lation from LUT-based logic elements
(LE) to macrocell equivalents is a little
subjective (Altera estimates 1.3 LE per
macrocell), but any way you cut it, densi-
ty is way up, peaking at something on
the order of 100× the original PAL. The
marketing brochures no longer talk about
replacing TTL, but instead set MAX II’s
sights on small ASICs and ASSPs.

The FPGA-lite aspects are even more

obvious when it comes to packaging.
Remember when the original PALs
came in 20-pin packages? With MAX II,
even the entry-level device comes in
a 100-pin package, and the lineup
migrates to 300 pins and beyond at the
high end. That makes MAX II uniquely
well suited for I/O-intensive applica-
tions that need more brawn (i.e., pins)

but not necessarily more brains.

Historically, the fact that MAX II is

flash memory-based and live at power-
up would put it squarely in the PLD
camp versus SRAM-based FPGAs that
require initialization. However, Actel,
with its flash memory-based ProASIC
FPGAs, has already muddied that water.

MAX II goes one step further by

integrating 8 Kb of user flash memory.
That means MAX II may be able to
replace the low-density EEPROMs used
in many systems to store system set-
tings, ID information, calibration data,
etc. However, I noticed the endurance
spec for the flash memory—both con-
figuration and user—is only 100 cycles.
That’s likely adequate for chip bug fixes
and upgrades, but not robust enough
for frequently changed data.

The user flash memory is split into

two sectors that can be erased and pro-

grammed independently. The width of
the user flash memory port is 16 bits
(256 × 16), but this is a programmable
logic chip after all, so it’s easy enough
to front the memory with a little cir-
cuitry to change the width (512 ×8 and
8,192 × 1). On-chip programming volt-
age generation allows the flash memory
to be programmed without requiring a
special voltage or separate supply. The
program and erase algorithms are han-
dled by dedicated circuitry.

Welcome attention is paid to the sub-

ject of in-system programmability and
dynamic reconfiguration. At power-on,
the contents of the configuration flash
memory are copied to the SRAM-based
logic array, a process that takes just 100 to
300 ms depending on the particular part
(longer for larger parts). Subsequently, the
configuration flash memory can be repro-
grammed even as the part continues to
operate in the previously initialized con-
figuration. The switch to a new configura-
tion can take place immediately or be
deferred to the next power cycle.

PRACTICAL PINS

In an era of multiple I/O standards,

Altera furthers the pin-rich orientation of
MAX II with I/O that’s versatile and
highly programmable. MAX II pins are
divided into four banks, each of which
has its own power supply (V

CCIO

). That

means a single part can support up to
four different I/O regimes simultaneous-
ly: 1.5, 1.8, 2.5, and 3.3 V. With an exter-
nal current limiting resistor, the higher
end parts (the EPM1270 and ’2210, which
have PCI capability) can accommodate 5-
V I/O (with an external resistor) as well.

The logic array is powered by a sec-

Programmable

AND array

03

02

01

00

Fixed OR array

I3
I2

I1
I0

Figure 2—There are various ways to arrange AND and
OR gates to implement logic functions. For instance, a
PROM is a fixed AND array (address decoder) feeding
a programmable OR array (data). The most successful
proved to be the PAL comprising a programmable AND
array feeding a fixed OR array.

(1)

Four-input

LUT

ADDNSUB (LAB wide)

DATA 1
DATA 2
DATA 3

C

IN

(from C

OUT

of previous LE)

DATA 4

Register chain

connection

sload

(LAB Wide)

sclear

(LAB Wide)

ALD/PRE

ADATA Q

D

ENA

CLRN

CLOCK (LAB Wide)

ENA (LAB Wide)

ADR (LAB Wide)

Register feedback

Register

chain output

Row, column,

and direct link routing

Row, column,

and direct link routing

Local routing

LUT chain
connection

sload

(LAB Wide)

Figure 3—The MAX II uses LUTs under the hood, marking the end of the macrocell (i.e., PAL) era for programmable logic.

background image

72

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

an aggressive mass marketing posture
that has lured customers in with ameni-
ties like free samples and cool evalua-
tion tools (see Photo 1). It’s a recipe that
works, and no doubt the reason why lit-
tle has changed in the new Cyclone II.
Unlike the rash of other II parts being
announced, there are no significant
architectural changes to speak of. In this
case, the gains (more LEs and more
speed) are mainly attributable to Moore’s
law (more silicon for less)—namely, the
switch to a state-of-the-art, 90-nm low-k
dielectric manufacturing process.

GIGANTICHIP

High-end FPGAs are amazing chips,

and Altera’s latest Stratix II is no excep-
tion. These are the Ferraris of FPGAs for
the elite few who demand and can afford
performance at any price. And speaking
of price, just like the slinky red road-
sters, if you have to ask they’re probably
out of your league. A triple-digit price
tag is typical, and the top of the line will
set you back more than $1,000.

In return, Altera hands you the keys

to a shiny new chip like the EP2S180
that’s breathtakingly extravagant. What
can you do with 180,000 LEs, 9-plus Mb
of RAM, and 384 18 × 18 multipliers in
a 1,500-pin package? A better question
might be, what can’t you do?

As with MAX II, boosting the Stratix II

logic density to more than twice that of
the top-of-the-line Stratix predecessor
called for changes under the hood beyond
just shrinking the transistors to cram
more of them on-board. From the begin-
ning, traditional FPGAs like Stratix (not

to mention the aforemen-
tioned MAX II CPLD) have
relied on a relatively fine-
grained (i.e., small) logic
element based on a four-
input LUT. The choice
isn’t mere whimsy, but
rather is supported by
research indicating that a
four-input LUT strikes a
good trade-off between
cost and performance (see
Figure 5). To which the
Stratix II designers pre-
sumably responded with
something along the lines
of, “Trade-offs? We don’t
need no stinkin’ trade-

the chip’s power supply lines (V

CCIO

or

V

CCINT

).

Even if your application doesn’t

require hot swap capability per se, the
features make for an easier and more
robust system design. For example, there
aren’t any finicky power sequencing
requirements so the V

CCINT

and V

CCIO

pins

can be powered in any order without spe-
cial timing (ramp rate). Remember that a
MAX II could well be powered by two (or
conceivably three or four, with separate
I/O banks) power supplies, so not having
to worry about power sequencing and
timing is well appreciated.

A MIGHTY WIND

Altera may have stumbled out of the

blocks with their earlier forays into the
FPGA market, but now they’re getting
their second wind with the Cyclone
family (see Figure 4). One reason for the
success is that Cyclone hits the spot in
terms of the market requirements,
with enough density to do meaningful
things, but with notably aggressive pric-
ing that makes it a viable contender for
mainstream applications.

For those of you who think FPGAs

are only suitable for price-is-no-object
rocket science apps, Cyclone parts with
prices as low as $4 in volume should
make you think again. Cyclone II may
be a bargain, but it isn’t stripped down
by any means. It’s got most of the high-
end bells and whistles like the DSP fea-
tures, PLLs, and high-speed differen-
tial I/O you’ll find on a real (as in
“real expensive”) FPGA.

Another factor in Cyclone’s success is

ond supply (V

CCINT

), which can be 3.3,

2.5, or 1.8 V. Because the actual inter-
nal supply is 1.8 V in all cases, the
3.3- and 2.5-V power options rely on a
built-in voltage regulator.

Even though there are a lot of pins,

each can be individually tuned with a
variety of options, including program-
mable drive and slew rate control, open-
drain output, Schmitt-trigger input, a
pull-up resistor, and so on. There’s a bus
hold feature that keeps a pin at its last
driven state to counter the possibility of
unintended (and power consuming)
switching of floating inputs. Unused
inputs can be defined as additional
grounds or tri-stated inputs.

Another nice touch is the attention

paid to the issue of hot swap. MAX II
parts can be plugged into or removed
from a powered system without dam-
aging the chip or disrupt-
ing system operation.

MAX II relies on three

technical features to
serve as the basis for hot
swap capability. First, the
I/O pins can be driven
before or during power-
up/down without damag-
ing the chip. Second, the
pins are automatically
tristated during power
cycles to prevent interfer-
ence with ongoing bus
operations. Finally,
inputs on the pins of an
unpowered MAX II do
not backfeed power to

1 2

3 4 5 6 7 8 9 10 11 12 13 14 15

Months after introduction

Units shipped

Cyclone

FLEX 6000

ACEX 1K

Figure 4—After some false starts, the popularity of
Cyclone shows that Altera has successfully made the
transition from PLDs to FPGAs.

Photo 1—Who says FPGAs have to be boring and expensive? At only $149, the Cubic
Cyclonium is not only a cool demo, but a credible development platform as well.

background image
background image

74

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

offs.” Or maybe, “Give me perform-
ance, or give me death.”

Simply expanding the width of the

LUT is indeed a brute-force way to
achieve higher performance. Generally
speaking, the advantage is realized in
reducing the stages (i.e., critical path)
a signal must traverse. However, going
wide by itself causes granularity and

fragmentation problems (i.e., lots of
partially used LUTs).

Thus, for Stratix II, Altera came up

with a new adaptive logic module
(ALM) architecture that mixes and
matches two adaptive LUTs (ALUTs) to
accommodate functions with up to
seven inputs. It’s an approach that aims
to achieve the best of both worlds (i.e.,
the performance of a wide LUT com-
bined with the gate-maximizing effi-
ciency of two narrower ones).

As a result, an ALM can handle a

complete range of logic functions, as
shown in Figure 6. Admittedly, some
combinations are rather off-the-wall,
depending on, for example, the ability
to share specific inputs between the
two ALUTs. Nevertheless, with so

much logic on-board, the toolchain has
ample opportunity to seek such oppor-
tunities and shuffle things around to
get the most out of the silicon.

More logic means more design intel-

lectual property goes into each chip,
boosting the concern over piracy. Who
wants to slave away crafting 180,000 LEs
worth of design know-how only to have

Slowest

performance

Low
cost

Fixed

four-input LUT

Highest

performance

High

cost

2

3

4

5

6

7

Number of inputs to LUT-based logic structure

Relativ

e perf

or

mance or cost-eff

ectiv

eness

Figure 5—Go wide young chip. The classic four-input
LUT strikes an optimal trade-off between cost and per-
formance, but Stratix II is all about the latter.

4-LUT

4-LUT

5-LUT

3-LUT

5-LUT

4-LUT

5-LUT

5-LUT

6-LUT

6-LUT

4

4

4

7-LUT

Figure 6—With dual LUTs sharing inputs, the Stratix II
adaptive logic block (ALB) is capable of handling func-
tions of up to seven inputs.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

75

a nefarious pirate copy it, a trivially
easy rip-off? To that end, another new
Stratix II feature is advanced encryp-
tion standard (AES) encryption for the
configuration bitstream.

FPGA bitstream encryption isn’t a new

concept, but earlier designs have had
problems. In some cases, the decryp-
tion key is stored on-chip in volatile
SRAM, requiring battery backup, so a

dead battery effec-
tively makes a
dead chip, or at
least one in a coma
until it’s repro-
grammed with the
proper key. By con-
trast, Stratix II
stores the key in a
special nonvolatile
memory on-chip,
so there’s no need
to worry about a
dead battery
because there’s no
need for a battery
at all.

ROUND II

Altera still may be number two (and,

for that matter, so is Avis), but as the
rash of II announcements demonstrates,
it isn’t for want of trying (see Table 1).
It’s all the more impressive when you
consider that the overall trend in the
market is toward FPGAs and away from
PLDs. I think Altera has successfully
made the transition to FPGAs (even the

Tom Cantrell has been working on chip,
board, and systems design and marketing
for several years. You may reach him by
e-mail at tom.cantrell@circuitcellar.com.

SOURCE

MAX II, Cyclone II, Stratix II FPGAs,
Cubic Cyclonium evaluation system
Altera Corp.
www.altera.com

REFERENCE

[1] “Quotable Facts,” Avis Rent A Car

System, Inc., www.avis.com/Avis
Web/JSP/US/en/aboutavis/corp_info/
quotable_facts.jsp, August 2004.

MAX II

Cyclone II

Stratix

Logic structure

Four-LUT

Four-LUT

Seven-LUT

Logic density (LEs)

240–2.2 K

4.6–68.4 K

15.6–179.4 K

Block RAM (Kb)

N/A

120–1,150

420–9,400

Multipliers

N/A

13–150

48–384

PLLs

N/A

2 – 4

4 – 12

I/O

Single-ended

Single-ended

Single-ended

and differential

and differential

Logic power supply

3.3 or 2.5 V

1.2 V

1.2 V

or 1.8 V*

I/O Power supply

1.5–3.3 V,

1.5–3.3 V,

1.5–3.3 V,

5 V**

5 V**

5 V**

Package

100–324 pins

144–896 pins

484–1,508 pins

*Versions with internal voltage regulator support 3.3- and 2.5-V operation.

**Some restrictions apply for 5-V I/O.

Table 1—Altera enters round II of the programmable logic wars well armed with a
new arsenal of chips across the board.

ones they still call PLDs like MAX II).
Not bad for a company that started with
little more than a tiny EPROM PAL chip.

Of course, the silicon is just half the

battle. There’s still the critically impor-
tant issue of tools, not to mention use-
ful intellectual property to keep the
transistors busy. Next month, we’ll
delve into those subjects a bit. Make
that 32 bits to be exact.

I

background image

76

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

N

owadays, more and more people

carry cellular phones, which are handy
for conducting business outside the
home and office. But, for reasons of pri-
vacy, most people don’t release their cell
phone numbers to the public. As a
result, it’s a common occurrence to miss
time-critical phone calls placed to home
and office lines. To solve this problem,
we built the Telephone Message
Watchdog, which is a smart device that
instantly forwards a caller’s information
from a home or office line to a pager.
With the pager information, you can
contact the caller with your cell phone.

The Telephone Message Watchdog is

connected in serial between a telephone
port and an answering machine. When
you are out, an incoming call
triggers the answering machine,
which gives the caller two
options: either leave a voice mes-
sage or enter a callback number.
The smart device monitors the
answering machine’s status and
holds a touch-tone signal until
the calling process terminates.
Then, the device automatically
dials your pager number. If a
caller leaves a phone number, the
system sends it to your pager. If
not, the system sends your home
number so you know to call it to
hear the voice message.

Before starting the project,

we made a list of the functions
we were shooting for. As you’ll
see, we met all of our goals.
The result is a low-cost system

tal domain. Because the telephone audio
signal frequency bandwidth is approxi-
mately 3 kHz, the embedded ADC must
be able to digitize the audio signal at a
minimum of 6,000 samples per second.
(The sampling rate must at least twice
the highest signal frequency.)

Second, the MCU should contain a

two-channel digital-to-analog convert-
er (DAC) for the touch-tone generator.
Both the DAC and pulse width modu-
lation (PWM) units can be used for
audio signal generation. However, the
audio signal generated from the DAC
has less harmonic distortion than that
of the PWM unit. The touch-tone sig-
nal generated with lower order har-
monic frequencies is easier to distin-

guish from voice signals.

Third, the MCU’s CPU core

should possess adequate compu-
tation power to handle digital
signal processing. In the touch-
tone detection process, the sig-
nal is fed to as many as eight
digital filters in a short period of
time. Each digital filter is imple-
mented using a series of 16-bit
fixed-point multiplication and
accumulation (MAC) operations.
Therefore, a fast 16-bit multipli-
er in the CPU core is required.

Based on the aforementioned

requirements, we selected the
Renesas H8S/2398 microcon-

troller, which contains an
eight-channel, 10-bit ADC con-
verter with a sampling rate of
up to 150 kHz. It also has a

Telephone Message Watchdog

FEATURE ARTICLE

by Jingxi Zhang, Yang Zhang, & Huifang Ni

that complies with part 68 of the FCC
rules to provide safe operation.

H8S/2398 ADVANTAGE

To build this smart device, we knew

we needed a microcontroller to moni-
tor and control the telephone calling
process. We decided not to use a hard-
ware touch-tone detector and genera-
tor in order to reduce the chip count,
simplify the hardware design, and
lower the project’s overall cost.

Using software to detect and generate

touch-tones requires the MCU to meet
particular criteria. First, the MCU must
contain an analog-to-digital converter
(ADC) for converting audio signals,
including touch-tone signals, to the digi-

The Telephone Message Watchdog is an H8S/2398-based message-forwarding system for
home telephones. The touch-tone detection system triggers when your answering machine
picks up a call. After the caller hangs up, the system contacts you on your cell phone or pager.

Figure 1—IC2 is a bidirectional optocoupler for the answering machine’s loop
current sensor. IC3 is for line-engage control. IC4 is for delivering line voltage
condition information to the MCU.

Line condition

detection circuitry

Port for setting

pager/home numbers

V+

Telephone

Ring

Normal

Answer machine

condition

ADC

Dial tone
output

Line busy

Line engage

IC4

Line

busy

Off

hook

IC3

Loop current
sensor

IC2

Answering

machine

Tip

MCU

Setting

S1

CONTEST WINNER

An Intelligent Call-Forwarding System

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

77

collector voltage rises. The rising volt-
age triggers the MCU to stop the

two-channel, 8-bit DAC converter.

The H8S/2398’s CPU performance is

attractive. The system clock is 20 MHz,
and a 16-bit addition operation takes
one cycle (50 ns). The CPU instructions
contain signed and unsigned multiplica-
tion and division operations. The 16-bit
multiplication takes 1 µs, which is ade-
quate for touch-tone detection.

An embedded DMA controller fur-

ther enhances the CPU’s performance.
With the DMA controller, the digitized
data is transferred automatically to the
digital filter frame buffer without CPU
involvement. This feature liberates the
CPU of the burden of servicing frequent
data transfer interrupts and frees up
power for the CPU to perform digital
signal processing. The 8 KB of RAM
storage make the digital filter frame
buffers easier to design. There are 256 KB
of flash memory for instruction storage,
which is plenty for a small MCU.

Of course, the biggest incentive for

selecting the H8S/2398 MCU was the
H8 Renesas Design 2003 Contest.
Renesas offered a free H8 starter kit. We
selected the H8S/2398 starter kit from
Basic Micro. The kit came with an eval-
uation board, LCD module, and soft-
ware package for Renesas MCU devel-
opment. The evaluation board simpli-
fied the hardware construction process.

PHONE LINE INTERFACE

The telephone message watchdog

system contains the H8S/2398 evalua-
tion board from the kit and analog
telephone interface circuitry. The
MCU in the evaluation board handles
touch-tone signal processing.

Figure 1 is a simplified diagram of the

device interface to a telephone line. In
compliance with part 68 of the FCC
rules, the MCU circuitry is isolated
from the telephone line by an isolation
transformer and optocouplers. An AC
optocoupler (IC2), which is connected
between the telephone input line and
the answering machine, serves as a line
loop-current detector. When the answer-
ing machine engages the line, a 20-mA
loop current flows through the optocou-
pler LED emitter, causing the optically
coupled photosensitive transistor to
conduct. The transistor collector voltage
V

CE

drops and triggers the MCU to enter

the touch-tone detection state.

When the switch is set to the normal

position, the system is in working con-
dition. The touch-tone audio signal is
coupled to the system through an isola-
tion transformer. In order to prevent
the system from drawing a DC current,
a capacitor is used in series with the
isolation transformer. An op-amp con-
ditions the incoming audio to optimal
voltage for the MCU’s A/D converter.

After the caller hangs up the tele-

phone receiver, the loop current drops
and the IC2 photosensitive transistor

1,209 Hz 1,336 Hz 1,744 Hz 1,633 Hz

697 Hz 1

2

3

A

770 Hz 4

5

6

B

852 Hz 7

8

9

C

941 Hz *

0

#

D

Table 1—The DTMF matrix consists of a lower frequency
group represented as rows, containing four distinguished
frequencies, which are below 1 kHz, and a high-frequency
group represented as columns, containing four distin-
guished frequencies above 1 kHz. Each signal is combined
with a high-frequency tone and a low-frequency tone.

background image

78

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

touch-tone detection state and start the
message forwarding. First, the line condi-
tion detection circuitry checks the line
condition. When the line is free, there is
approximately –48 V across the tip and
ring lines. If anyone is using the line, the
voltage is dropped to a lower level and
the line condition circuitry turns the
photocoupler IC4 photosensitive transis-
tor on to signal a “line busy” condition
to the MCU. If the phone line is free, the
MCU drives another photocoupler (IC3)
to close a resistor path across the tip and
ring lines. This action draws a 20-mA
DC loop current and engages the tele-
phone line. When the remote telephone
switching office senses the loop current,
it acknowledges by sending a dial tone
and preparing to receive touch-tones.
The MCU, in turn, starts the touch-tone
generator and dials your pager number.
The generated touch-tone is amplified by
an op-amp and coupled to the telephone
line by the isolation transformer.

If you turn S1 to the setting position,

it allows a telephone to connect to the
device. You can then use a regular
telephone’s touchpad to preset the
pager number and home phone number.

DTMF DETECTION

The telephone tone dialing system is

called dual-tone multi-frequency (DTMF)
signaling. It’s a standard telecommu-
nication system developed by Bell
Laboratories. In this system, a matrix is
used to compose a signal, which consists
of a lower frequency group, containing
four distinct frequencies that are below
1 kHz, and a high-frequency group, con-
taining four distinct frequencies above
1 kHz (see Table 1). Each telephone key
is represented by a pair of simultaneous
low- and high-frequency tones.

To detect DTMF signals by software

in the digital domain, many algorithms
have been proposed. The modified
Goertzel algorithm is one of the most
efficient computing techniques for
detecting a limited number of frequen-
cies. In the case of DTMF tone detection,
the Goertzel algorithm analyzes only
eight frequencies instead of performing
an entire transform using something like
FFT. This saves a lot on computational
resources, which are critical for lower-
power processors. Its noncomplexity is
easy to adapt into small MCUs and

Listing 2—And here you see the Goertzel DFT filter assembly codes.

// Function: GoertzelDFT

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

GoertzelDFT:

PUSH.L ER2

//ER0 and ER1 don't to save

PUSH.L ER3

PUSH.L ER4

PUSH.L ER5

MOV.W R0, COE

//save coefficient on R3

SUB.L SKN1, SKN1

//initial SKN1

SUB.L SKN2, SKN2

//and SKN2

MOV.L @_DTMFBUFFPTR,SAMPLEPTR //pointer to first sample

MOV.B #DTMFCOUNT, LPCOUNT //set loop counts

GozertzelLoop:

MOV.L SKN1, ER0

//use ER0 for temp reg

BPL ?0010

//if Sk[n-1] is positive, go ahead

NEG.L ER0

//else change it to positive number

?0010: SHAL.L ER0

//Sk[n-1] * 2

;Multiply lower portion of Sk[n-1] with cosine coefficient

MOV.L ER0, ER5

//ER5 for fraction(Sk[n-1])

MULXU.W COE, ER5

//fraction(Sk[n-1])*2*Coefficient

MOV.W E5, R5

//move upper word to lower

EXTU.L ER5

//clear upper word

;Multiply upper portino of Sk[n-1] with cosine coefficient

MOV.W E0, R0

MULXU.W COE, ER0

//temp=integer(Sk[n-1])*4*Coeff

ADD.L ER0, ER5

//result is in ER5

MOV.L SKN1, ER0

//test Sk[n-1]

BPL ?0020

//if postive, do nothing

NEG.L ER5

//else change result to positive

?0020 SUB.L ER0,ER0

//clear ER0

Listing 1—Here you can see the Goertzel DFT filter register usages and the variable definitions.

// GoertzelDFT function Parameters:

// R0: Cosine coefficient of the frequency (premultiplied by 2^16)

//

// Return:

// R0 Magnititude^2 of the filtered frequency

//

// Note:

//

// Gozertzel algorithm:

// Sk[n] = x[n] + 2*coefficient*Sk[n-1] - Sk[n-2]

// Only last N (do once):

// Mag^2 = SK[N]^2 - 2*coefficient*SK[N]*SK[N-1] + SK[N-1]^2

//

// The operation is using fixed point data format

// Upper 18bit is integer part of the real data

// Lower 14bit is fraction port of the real data

//

// Register usage:

// ER0: Sk[n]

// ER1: Sk[n-1]

// ER2: Sk[n-2]

// E3 coefficient * 4

// R3L loop count

// ER4 input sample pointer

// ER5 for temp reg

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

SKN1 .REG (ER1)

SKN2 .REG (ER2)

COE: .REG (E3)

LPCOUNT .REG (R3L)

NEGFLG .REG (R3H)

SAMPLEPTR .REG (ER4)

SKN1HIGH .REG (E1)

SKN1LOW .REG (R1)

SKN2HIGH .REG (E2)

SKN2LOW .REG (R2)

(Continued)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

79

DSP. Therefore, we selected the modi-
fied Goertzel DFT for our design.

Like an infinite impulse response (IIR)

filter, a Goertzel algorithm contains a
recursive feedback path. For a DTMF
tone filter, the following calculation
step is performed on incoming data:

where n = 0, 1, …, N – 1. N is the block
size, and k = f

DTMF

/f

SAMPLING

. (f

DTMF

is a

DTMF tone frequency. f

SAMPLING

is the

ADC sampling frequency.) x[n] is the
newly arrived sampled data.

Initially, Sk[n – 1] = 0 and Sk[n – 2] = 0

when n equals zero. In the last step,
the modified Goertzel algorithm cal-
culates the power of the frequency:

For computation efficiency, DTMF

2

Y k

n

k

N

Sk N ×

Sk N

N

( )

[ ]







[ ]

[

]

[

]

2

2

= Sk

1 + Sk

1

2

2

cos

π

Sk n = x n + 2

1

2

[ ]

[ ]







[

]

[

]

cos

2

π

k

N

Sk n

Sk n

×

detection is implemented using the H8S
assembler language (see Listing 1 and
Listing 2). Each filter uses precal-
culated coefficients from a differ-
ent K value corresponding to the
DTMF basic frequency. The
input audio signal is digitized by
the on-chip ADC at an 8-kHz
sampling rate. The 20-MHz H8S
MCU computation speed is ade-
quate to handle the input data at
this sampling rate. The A/D sam-
pling clock arrives from an on-
chip 16-bit timer (see Figure 2). A
DMA channel is used to feed the
converted data to a 115-word
buffer. A double-buffered memo-
ry storage scheme is used. When
the DTMF filtering process is
working on a data-filled buffer
(first buffer), the DMA controller
is feeding data to a second buffer
from the ADC. The interrupt
service routine then sets the
DMA pointing to the first buffer

and instructs the DTMF filtering
process to start working on the second
buffer. This ping-pong buffering is
repeated every 14 ms.

DTMF GENERATION

The DTMF tone generator is imple-

mented using a D/A converter and
sine wave look-up table, which is a
50-entry byte array representing a com-
plete precalculated sine wave. Two
16-bit timer units drive D/A convert-
ers with accurate clock rates. When a
DTMF tone is requested, the two
basic frequencies are selected. The
clock rate for each DAC is determined
with the following equation:

For example, 38,500 Hz = 770 Hz × 50.
The timer units are set to generate
the required clock rate for each fre-
quency. Two channels of DAC output
are mixed at the op-amp in the tele-
phone line interface circuit.

MCU OPERATION

We mixed H8S/2600 assembly and C

languages. Figure 3 is the program flow
chart. When the device is powered on,
the MCU starts a reset process and sets
up the on-chip peripheral I/O modules,

including 16-bit timer units, an ADC, a
DMA controller, D/A converters, and I/O

D A

/ clock rate =

basic DTMF frequency 50

×

A/D output

buffer (one word)

ADC

DTMF

8,000 Hz

TPU

φ

/2,500

System

clock

φ

20 MHz

End of

transfer

interrupt

Buffer block 1

(115 words)

Buffer block 2

(115 words)

Double

buffering

Interrupt

service

routine

697 MHz

770 MHz

852 MHz

941 MHz

1,209 MHz 1,336 MHz 1,477 MHz 1,633 MHz

Row filters

Column filters

Goertzel DFT filters

DTMF analysis logic

Swap

Start

Hardware resource

DMA

Figure 2—An A/D converter at 8,000 samples per second digi-
tizes the DTMF tone signal. It’s then delivered to one buffer block
of the double-buffered memory through the DMA channel. An
interrupt service routine triggered by an end-of-transfer signal
from the DMA controls the double-buffered memory in a ping-pong
manner. The filled buffer block is sent to eight filters to determine
a single low frequency and a single high frequency, which are sent
to DTMF analysis logic to convert to a DTMF symbol.

Listing 2—Continued.

MOV.W @SAMPLEPTR+, E0 //Get next sample (integer potion)

SHLR.L #2, ER0

//divide by 4

ADD.L ER5, ER0

//Sk[n]=Sample+Sk[n-1]*2*Coefficient

SUB.L SKN2, ER0

// - Sk[n-2]

MOV.L SKN1, SKN2

//Sk[n-2] = Sk[n-1]

MOV.L ER0, SKN1

//Sk[n-1] = Sk[n]

DEC.B LPCOUNT

//count--

BNE GozertzelLoop

//if count != 0, repeat

SUB.B R0L, R0L

//clear R0L for sign indicator

MOV.W SKN1HIGH,SKN1LOW

//only integer portion is used

BPL ?0030

//check if negtive

NEG.W SKN1LOW

//if change it to positive

INC.B R0L

//neg indication

?0030: MOV.W SKN2HIGH,SKN2LOW

//only integer portion is used

BPL ?0040

//check if negative

NEG.W SKN2LOW

//if change it to positive

INC.B R0L

//neg indication

?0040: MOV.L SKN1, ER5

//

SHAL.L ER5

//Sk[n-1] * 2

MULXU.W COE, ER5

//integer(Sk[n-1]) * 2* Coefficient

MOV.W E5, R5

//take the integer portion of result

MULXU.W SKN2LOW, ER5

//2*Coeff*(Sk[n-1])*integer(Sk[n-2])

MULXU.W SKN1LOW, SKN1

//integer(Sk[n-1])^2

MULXU.W SKN2LOW, SKN2

//integer(Sk[n-2])^2

ADD.L SKN2, SKN1

//Sk[n-1]^2 + Sk[n-2]^2

BTST #0, R0L

//check the sign of product term

BEQ ?0050

//if positive, do subtraction

ADD.L ER5, SKN1

//else, do addition

BRA ?0060

?0050: SUB.L ER5, SKN1

//- 2*Coeff*Sk[n-1]*Sk[n-2]

?0060: MOV.L SKN1, ER0

//result in ER0

POP.L ER5

POP.L ER4

POP.L ER3

POP.L ER2

RTS

background image

80

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

pins. The MCU then enters Sleep mode.

A loop current sensor interrupt (IRQ7)

wakes up the MCU when the answering
machine loop current increases in case
an incoming call has arrived. The ring
signal pattern is on for 2 s and pauses
for 4 s. To check if the answering
machine is turned on, the IRQ is dis-
abled temporarily, and the loop-current

condition is continuously monitored.
Only when a loop current stays on after
the ring on-off period does the MCU
enter DTMF Tone Detection mode.

In DTMF Tone Detection mode, the

ADC continuously samples the line
signal, and the DMA control feeds the
converted data into one of the DTMF
detection buffers. For each 14-ms frame,

all eight Goertzel filters—four for the
low-frequency group and four for the
high-frequency group—are executed. If
any of these filters detects a significant
tone, a validation test is performed. The
validation test includes the process of
verifying that both the high- and low-fre-
quency tones are simultaneously present.
It also verifies that only one tone is pres-
ent in the low-frequency group and only
one tone is present in the high-frequency
group. Finally, the test verifies that the
dual-tone duration lasts at least three
14-ms frames (greater than 40 ms, as
required by the FCC). The pause between
the DTMF tones also should be verified
in order to recognize two separate DTMF
numbers with the same value. If the vali-
dation test passes, the number is cap-
tured and stored in a memory location.

When the caller terminates the call,

the loop current sensor generates another
interrupt at IRQ7. The MCU stops
DTMF Detection mode and starts
Message Forwarding mode, during which
the line condition is checked first. If the
line is free, the MCU sets the output pin
(PC0) to logic high. This action engages

Photo 1—The bottom is the telephone interface board, which connects to the top evaluation board by a 14-conduc-
tor ribbon cable.

background image
background image

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

83

the telephone line. Then the
DTMF tone generator sends your
pager number through the DAC
to the telephone interface. Then
the MCU listens to the incoming
audio signal for the pager’s beep.
A few seconds after the beep, the
captured phone number is sent
to the output by the DTMF tone
generator. Finally, the MCU frees
the phone line and returns to
Sleep mode and waits for the
next calling process.

CIRCUIT CONSTRUCTION

As we mentioned, we used

Basic Micro’s H8S/2398 starter
kit board. The telephone line
interface circuit was construct-
ed on a separate board. The
starter kit board piggybacks on
top of the interface board. A
14-conductor ribbon cable electronically
connects both boards (see Photo 1).

Figure 4 is a schematic of the telephone

line interface circuit. T1 is a 600-

isola-

tion transformer. T1 and C1 compose the

audio coupling circuit. C1’s voltage rating
should be higher than 100 V. We selected
a 1-µF, 250-V metal polyester capacitor.
D1 and D2 provide surge protection.

IC1 is a Texas Instruments dual single-

supply, rail-to-rail (I/O) op-amp,
OPA2340. One channel of the
OPA2340 (IC1a) is for a touch-
tone detection signal-conditioning
amplifier. It provides a 5-V out-
put range, which is optimal for
the ADC. OPA2340 also accepts
rail-to-rail input. That makes
the DTMF tone generator design
easier. The DAC can directly
drive the 5-V ranged DTMF sig-
nal to the op-amp. Two channels
of generated basic DTMF tone
are mixed by IC1b, the other
half of the OPA2340. The mixed
signal is then fed into the isola-
tion transformer T1.

IC2 is an AC optocoupler for the

loop current sensor. Because the
loop current can be as high as
70 mA in a short circuit situation,
we selected the Fairchild H11AA3

optocoupler, which has a good IF rating
(IF = 100 mA). IC3 is Toshiba’s TLP222G
optocoupler, which contains an infrared-
emitting diode coupled with a bidirec-
tional photo-MOSFET circuit with a

Figure 4—JP1 and JP2 are the connectors of the starter kit board. The power supply block is connected to the evaluation board power supply switch 5-V regulated source and
9-V unregulated source. Note the point in-between T1 and R2 is a connection point to the optional audio monitor circuit.

Power on

Initialization

Line loop

current

sensor

Interrupt

Watchdog wakeup

DTMF Detection

capture number

DTMF Generator

Home number

Captured number

Loop current

== 0?

Line busy

?

Delay N seconds

N

Y

Y

Dial pager

DTMF generator

Engage telephone line

Any captured

number?

N

Y

N

Figure 3—The MCU is in Sleeping mode after initialization. The line loop
current sensor wakes it up and it starts to detect the DTMF signal. After
the loop current drops, the MCU starts dialing the pager number and
delivers the message.

background image

84

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Jingxi Zhang graduated from
Zhongshang Medical University,
Guangzhou, China. He earned an
M.S.E.E. at the University of California,
Irvine and a Ph.D. in Neuroscience at
UCLA. He is currently the Chief
Technologist at JVC North America R &
D Center in California. You may con-
tact him at zhang@jvclab.com.

Yang Zhang is an undergraduate study-
ing electrical engineering and computer
science at the University of California,
Berkeley. Yang recently completed an
internship at Microsoft. You may con-
tact Yang at yang.zhang@overbored.net.

Huifang Ni graduated from Zhongshang
Medical University, Guangzhou, China.
She holds an M.S. in pharmacology
from Zhangshang Medical University.
Previously, she worked as a researcher
at the UCLA Brain Research Institute
and medical school at the University of
California, Irvine. Huifang currently
works as a senior staff researcher at
Elan Pharmaceuticals in California. You
may contact Huifang at huifang.ni@
elan.com.

RESOURCES

FCC, Part 68 of the FCC rules,
www.fcc.gov/wcb/iatd/part_68.html.

SOURCES

MC34119 Low-power audio amplifier
Freescale Semiconductor, Inc.
www.freescale.com

H8S/2398 Microcontroller
Renesas Technology Corp.
www.renesas.com

OPA2340 Op-amp
Texas Instruments, Inc.
(972) 644-5580
www.ti.com

350-V/120-mA rating. Therefore, it’s
safe to use as a relay to connect a 600-

resistor (R7) across the tip and ring lines
when the MCU engages the phone line.

Bridge rectifier D4, Zener diode D5,

high-voltage transistors (V

CE

= 400 V) Q1

and Q2, and optocoupler IC4 comprise a
phone line condition detector. When the
phone is on the hook, there is a –48-V
voltage across the tip and ring lines. D4
routes the positive voltage polarity to
the 16-V Zener diode D5. Because the
on-hook line voltage is higher than the
Zener diode’s breakdown voltage, the
Zener diode conducts and the small cur-
rent flowing through D5 causes Q1 to
conduct. As a result, Q2 is shut off and
no current flows through the IC4 emitter
LED. The IC4 photosensitive transistor
is therefore turned off, and the line input
to the MCU stays high. If the line is in
use, the line voltage drops to a lower
level in the range of 5 to 10 V. In this
case, D5 is not conducting, and therefore
causes Q1 to shut off. As a result, Q2
turns on and the IC4 emitter LED lights
up. This causes the line input to the
MCU to drop to logic 0, indicating
that the phone line is busy.

S1 is a 4PDT mode switch. In Normal

mode, the telephone line is connected to
the DTMF tone detector. When it is
switched to Setting mode, a specific
phone port is connected to the DTMF
tone detector. This allows a regular tele-
phone (no power) connected to this port
to dial the owner’s preset pager number
and home phone number. To allow the
regular telephone to be used, the port is
also fed a power supply through resistor

PROJECT FILES

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

R2. D1 is a protection diode to prevent
damage from mistakenly connecting a
48-V phone line to this port. In that
case, D1 becomes nonconductive.

USAGE AND PRESETTING

You have to preset your pager and

home numbers before use. To do so,
first connect a regular telephone to
the presetting port J1. After the device
is powered on, push in the mode
switch (S1) to enter Presetting mode.
The device now waits for you to enter
the pager number and phone number
using the telephone’s keypad (see
Table 2). Punching the 0 key followed
by the * key enters Pager Number
Setting mode. The 1 key followed by
the * key enters Home Phone Number
Setting mode. Then the pager or home
phone number can be entered and ter-
minated by pressing the # key.

The LCD will show the number you

entered. Each number entered is
instantly saved even if the mode
switch is changed back to Normal
mode before the # key is pressed to
stop either of the setting modes.

Connect J2 to the telephone port and

J3 to an answering machine. After the
system is preset, switch S1 back to nor-
mal. Now the system is ready to use.
To test it, you can use a second line or

cellular phone to
dial this line num-
ber. After the
answering machine
triggers and waits
for a message, you
can punch in a call-
back number. The
LCD should cor-
rectly display the
number you
entered. After you
hang up the phone,
the system will
enter Information
Forwarding mode
and dial out the
pager number as

Figure 5—This optional audio monitor uses the Freescale low-power audio amplifi-
er MC34119. With this chip the audio monitor can be built with only a few external
resistors and capacitors. The speaker is directly connected to the output of the chip
without an impedance matching transformer.

Mode

Selection Setting

Pager number setting

0 + *

numbers + #

Home number setting

1 + *

numbers + #

Table 2—Presetting the system is a cinch. Use this
table as a guide.

well as the number you entered. To
monitor Information Forwarding mode,
you can add an audio monitoring circuit
to the system (see Figure 5). You can
then hear the generated touch-tone.

I

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

85

IDEA BOX

THE

DIRECTORY

OF

PRODUCTS AND

SERVICES

AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.
ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2

″″ ××

3

″″

FORMAT. Call for current rate and deadline information. Send your disk and digital submission

sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail kc@circuitcellar.com. For more information call Sean Donnelly at (860) 872-3064.

The Suppliers Directory at www.circuitcellar.com/suppliers_dir/

is your guide to a variety of engineering products and services.

background image

86

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

87

background image

88

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

89

background image

90

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

91

background image

92

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 171 October 2004

93

background image

94

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

Simple Four-Channel Network Video Server

Wi-Fi Sunlogger

Network Security for Small Systems

Interfacing 100-Mbps Ethernet and Embedded Systems

Math Coprocessor for Robotics Applications

Build a VGA Monitor Controller

APPLIED PCs

TCP/IP Stack Solution: A Detailed Look at the CMX-MicroNet

FROM THE BENCH

USB DMX

SILICON UPDATE

Easy to be Soft

89

Abacom Technologies

89

All Electronics Corp.

88

Animated Lighting, L.C.

46

AP Circuits

23

Arcturus Networks

7

Atmel

91

Bagotronix, Inc.

88

Basic Micro

43

Bellin Dynamic Systems, Inc.

85

BusBoard Prototype Systems

15

CadSoft Computer, Inc.

87

Carl’s Electronics

43

CCS-Custom Computer Services

92

Conitec

9

Cypress Contest

1

Cypress MicroSystems

65

CWAV

91

DataRescue

85

Decade Engineering

85

DLP Design

22, 49

Earth Computer Technologies

90

EE Tools

(Electronic Engineering Tools)

75

EMAC, Inc.

14

ExpressPCB

85

FDI-Future Designs, Inc.

92

Front Panel Express

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page

93

Futurlec

89

Grid Connect

86

Hagstrom Electronics

61

HI-TECH Software, LLC

74

ICOP Technology, Inc.

89

IMAGEcraft

73

Imagine Tools

85

Intec Automation, Inc.

91

Intrepid Control Systems

90

Intronics, Inc.

81

Jameco

64, 86

JK microsystems, Inc.

42

JR Kerr Automation & Engineering

42

LabJack Corp.

42

Lakeview Research

91

Lawicel HB

89

Lemon Studios

39

Lemos International

2

Link Instruments

8, 77

Linx Technologies

49

MaxStream

88

MCC (Micro Computer Control)

57

Microchip

93

MicroControls

92

microEngineering Labs, Inc.

82

Micromint

88

MJS Consulting

90

Mosaic Industries, Inc.

41

Mouser Electronics

95

MVS

86

Mylydia, Inc.

C2

NetBurner

88

OKW Electronics, Inc.

92

Ontrak Control Systems

64

PCB123

10

PCBexpress

87

PCB Fab Express

C4, 66 Parallax, Inc.

85

Phytec America LLC

87

Phyton, Inc.

90

Picofab, Inc.

89

PTLogica

93

Pulsar, Inc.

86

Quality Kits & Devices

86

Quantum Composers, Inc.

87

R2 Controls

63

R4 Systems, Inc.

47, 87

Rabbit Semiconductor

90

Radiotronix

22

Remote Processing

59

R.E. Smith

93

Rogue Robotics Corp.

Page

Page

Page

31

Saelig Company

89

Scidyne

3

Scott Edwards Electronics, Inc.

88

Sealevel Systems

5

Sierra Proto Express

19

Silicon Laboratories, Inc.

91

Softools

93

TAL Technologies

C3

Tech Tools

24, 25

Technologic Systems

87

Technological Arts

90

Tern, Inc.

29

Texas Instruments

86

Trace Systems, Inc.

91

Triangle Research Int’l, Inc.

75

Trilogy Design

35

Tri-M Systems Inc.

93

Weeder Technologies

8

Wittig Technologies

92

Zagros Robotics

91

Zanthic Technologies, Inc.

53

ZARX

11

Z-World

December Issue 173

Deadlines

Space Close: October 11

Material Due Date: October 20

Theme:

Embedded Development

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 November Issue 172

Theme: Internet & Connectivity

background image
background image

I

received an interesting e-mail this week from Eric Soulsby, special assistant to the vice provost for undergraduate education at the University

of Connecticut, asking about an editorial I wrote a long time ago. He had heard someplace that I am a UConn engineering graduate. (And,
yes, there is more than basketball there.) He said he likes to give a speech to engineering students that when effectively translated says, “You
can spend your time being jerks, or you can make something out of yourselves.” Apparently, I had written something to the same effect a while
back.

It’s somewhat embarrassing to feel that I’m being used as an example of engineering success, but I appreciate Eric’s attitude of trying to

encourage social goals along with all the technology. I also rarely if ever repeat an editorial because ideas in this business are never the same
month to month. However, after rereading the editorial I wrote 11 years ago, I have to say that I still believe it just as strongly now.

“I can hardly believe it, but fall has rolled around and another summer has passed. September always reminds me of back to school. Could

it be all of those ads for school supplies and the like that make me think that way? Maybe.

“To all of you who are going back to school, I hope your professors took advantage of the special deal we offer to colleges and universi-

ties. If so, I hope you enjoy reading Circuit Cellar along with all of the other materials you will be expected to absorb this semester. I trust you
will have a successful semester.

“Speaking of successful semesters, I can’t emphasize enough how important it is that you apply yourself. Let me tell you a tale of two engi-

neering students. One student stayed out late every night playing around, doing just enough to get by with slightly better than average grades.
Content with his lot, this student couldn’t wait for all of this agonizing homework to end so he would never have to think about those compli-
cated subjects ever again. Another student faces the same material as a personal challenge, trying to learn all he can; trying to absorb as
much as he can; trying to rise to the best of his abilities.

“Well, finally the day comes that it is over. Graduation. I won’t give you the song and dance about which one of these two impressed the

job interviewers and received the better offer. That would be trite. Instead, I’ll ask you to consider which of these students has formed better
self-development skills. Which of these two do we want the country and economy to depend on?

“I won’t tell you which of these students I was. Let’s just say I saw the light very early and decided a career as a bum was self-defeating.

Instead, I ask you to examine yourself to see which kind of student you are. Take this to heart, because after you are out of the collegiate pro-
gram, the rest of your intellectual and financial development is up to you. Perhaps you will get ‘lucky(?)’ and land a job in an organization where
all of your efforts are strictly guided by the needs of the company and you can hide in the bureaucracy. Perhaps you’ll get ‘lucky(?)’ and land
a job in an organization where you are in charge of whatever you do. Of course, the responsibilities in the latter position mean you get the ‘bul-
let’ as well as the praise.

“I always prefer the second career path because that’s just who I am. Personally, I couldn’t begin to think of myself in any kind of position

where I couldn’t apply unrestricted drive and motivation. Being ‘invisible’ and taking the easy road always catches up with people.

“So, try to see beyond the immediate tasks of homework or dull career assignments. Look for a deeper lesson in this challenge you have

accepted for yourself. Is your challenge, ‘How little can I do and still manage to sneak past?’ or is your challenge, ‘How good at this can I
become?’ Be true to yourself and honestly appraise your approach.

“Those of us who don’t have to go through the grueling rigors of classwork (thank heavens) sympathize with you, but the end result puts

you in a minority among men and women. How long you stay in this elite group just depends on how you apply it.”

The Collegiate Challenge

PPRRIIOORRIITTYY IINNTTEERRRRUUPPTT

steve.ciarcia@circuitcellar.com

96

Issue 171 October 2004

CIRCUIT CELLAR

®

www.circuitcellar.com

by Steve Ciarcia, Founder and Editorial Director

background image
background image

Wyszukiwarka

Podobne podstrony:
circuit cellar1990 10,11
circuit cellar2002 10
circuit cellar1996 10
circuit cellar1995 10
circuit cellar1991 10,11
circuit cellar1992 10,11
circuit cellar1994 10
circuit cellar2003 10
circuit cellar1993 10
circuit cellar1997 10
circuit cellar2001 10
circuit cellar2000 10
circuit cellar1990 10,11
circuit cellar1991 10,11
circuit cellar2003 10
circuit cellar1994 10
circuit cellar1997 10
circuit cellar1993 10

więcej podobnych podstron