circuit cellar2003 09

background image

7

9

25274 75349

0 9>

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)

#158 September 2003

INTERNET & CONNECTIVITY

RS-485 Network

RS-232 Concentrator Box

Verilog Custom Logic

Text-to-Speech

background image
background image

Use the Cypress PSoC

instead of an MCU for

more flexibility, fewer parts and lower cost.

The versatile PSoC

Programmable System-on-Chip

is

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

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

software

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

Reduce BOM cost by reducing the number
of external components

MCU

later.

Cypress,

PSoC,

Programmable-System-on-Chip

and

PSoC

Designer

are

trademarks

of

Cypress

Semiconductor

Corporation.

©2002

Cypress

Semiconductor

Corporation.

All

other

Trademarks

are

the

property

of

their

respective

owners.

There are many more blocks to work with—

and thousands of configurations to choose from.

PSoC Designer

software is free for download, with

full-featured emulation hardware starting at $248.

Option #8926

8-bit PWM

Inverting Amplifier

IrDA

Transmitter

11-bit

Delta Sigma A/D

Band Pass Filter

Analog

Comparator

8-bit Counter

8-bit DAC

24-bit Timer

Low Pass Filter

Option #1530

Analog

Comparator

Instrumentation

Amplifier

12-bit

Incremental A/D

Notch Filter

16-bit CRC

Option #625

Analog

Comparator

16-bit PWM

Programmable

Gain Amplifier

Instrumentation

Amplifier

IrDA

Transmitter

11-bit

Delta Sigma A/D

8-bit DAC

12-bit

Incremental A/D

Band Pass Filter

8-bit Counter

Option #4237

CPU

Analog

Comparator

Your Customized Mixed Signal

platform in 60 minutes or less

Build your custom PSoC

with programmable analog

and digital functions from our extensive library.

To learn more about our innovative PSoC solutions

and to enter a drawing to win a PSoC Development

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

.

background image

Digital Oscilloscopes

2 Channel Digital Oscilloscope

100 MSa/s

max single shot rate

32K samples per channel

Advanced Triggering

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

Small, Lightweight, and Portable

Parallel Port

interface to PC

Advanced Math options

FFT Spectrum Analyzer options

DSO-2102S

$525

DSO-2102M

$650

Each includes

Oscilloscope

,

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

40 to 160 channels

up to 500 MSa/s

Variable Threshold

8 External Clocks

16 Level Triggering

up to 512K samples/ch

Optional Parallel Interface

Optional 100 MSa/s Pattern Generator

LA4240-32K (200MHz, 40CH)

$1350

LA4280-32K (200MHz, 80CH)

$2000

LA4540-128K (500MHz, 40CH)

$1900

LA4580-128K (500MHz, 80CH)

$2800

LA45160-128K (500MHz, 160CH)

$7000

www.LinkIns4.com

Link Instruments

369 Passaic Ave

Suite 100

Fairfield, NJ 07004

(973) 808-8990

Fax (973) 808-8786

Logic Analyzers

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

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

$800

All prices include Pods and Software

background image
background image

A

s we were putting this issue together, the first responses from our lat-

est survey started trickling in. Surveys help us keep in touch with you, our
readers. You tell us what you do, what you buy, and whom you buy from,
and we use the results for a variety of purposes. For instance, our sales
representatives present the information gleaned from surveys—what kinds
of products you buy and what kinds of industries you work in—to our
advertisers, so they know their ad campaigns are reaching their target
audience.

As managing editor, I’m not terribly interested in the numbers. I skip the

multiple-choice answers and head to the comments section. Reading the
comments gives me insight into what’s working in the magazine. Overall
the message from this year’s survey is clear: stick with what you’re doing.

Michael Coulson wrote, “Circuit Cellar reminds me why I got into this

business. The dull, dry environment of work, with its overuse of process-
es and procedures, can be left behind while raw creativity is allowed to
flow, i.e. how can I make this device better, faster, more powerful, more
efficient? How can I make this thing really sing?”

Many of you remarked about the usefulness of our project articles,

because they include the code and schematics necessary to really learn
from them. One respondent noted, “I like the detail the authors include in
their articles, they generally don’t just gloss over the difficult or the easy
part.” A few of you specified that you’ve found the solutions offered by our
authors helpful in your own designs. I think that’s what sets Circuit Cellar
apart. We don’t just want to entertain you with ideas; we want you to be
able to apply the techniques presented.

“CCI’s ‘inside the box still counts’ attitude drew me into believing that

microprocessor technology was accessible, adaptable, and usable in
everyday life,” wrote Allan C. Lane. “The end-to-end approach is a refresh-
ing change from the partial, incomplete, or intentionally ‘crippled’ examples
often given by other magazines or vendors.”

In particular, many of you mentioned that you enjoy reading about the

projects entered in our design contests, both on our web site and in the
magazine. Those of you who have entered some of our contests noted that
they inspired you to try a new application or a new part that you might not
have tried otherwise. Your continued interest and participation in the con-
tests are what help us attract sponsors for future design contests.
Manufacturers have realized that, if they want to launch a product, there’s
no better audience than the engineers who read Circuit Cellar.

In the survey, a number of you reflected on the years of great articles,

noting that you’ve subscribed since the first issue came out. Some of you
also mentioned that you were hooked early on by Steve’s column in Byte,
and haven’t missed an issue of Circuit Cellar in our 15 years of publication.
We appreciate your comments and take pride in your loyalty.

On behalf of the entire Circuit Cellar staff, I would like to thank every-

one who participated in the survey.

4

Issue 158 September 2003

www.circuitcellar.com

CIRCUIT CELLAR

®

EDITORIAL DIRECTOR/FOUNDER
Steve Ciarcia

MANAGING EDITOR
Jennifer Huber

TECHNICAL EDITOR
C.J. Abate

WEST COAST EDITOR
Tom Cantrell

CONTRIBUTING EDITORS

Ingo Cyliax
Fred Eady
George Martin

George Novacek
Jeff Bachiochi

NEW PRODUCTS EDITOR
John Gorsky

PROJECT EDITORS
Steve Bedford
Ken Davidson
David Tweed

ADVERTISING

PUBLISHER

Dan Rodrigues

E-mail: dan@circuitcellar.com

ASSOCIATE PUBLISHER/DIRECTOR OF SALES

Sean Donnelly

Fax: (860) 871-0411

(860) 872-3064

E-mail: sean@circuitcellar.com

Cell phone: (860) 930-4326

ADVERTISING COORDINATOR

Valerie Luster

Fax: (860) 871-0411

(860) 875-2199

E-mail: val.luster@circuitcellar.com

ADVERTISING ASSISTANT

Deborah Lavoie

Fax: (860) 871-0411

(860) 875-2199

E-mail: debbie.lavoie@circuitcellar.com

CONTACTING CIRCUIT CELLAR

SUBSCRIPTIONS:

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

GENERAL INFORMATION:

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

AUTHOR CONTACT:

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

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

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

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

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

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

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

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

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

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

For information on authorized reprints of articles,

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

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

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

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

CHIEF FINANCIAL OFFICER

Jeannette Ciarcia

CUSTOMER SERVICE

Elaine Johnston

ACCOUNTANT

Jeff Yanco

ART DIRECTOR

KC Prescott

GRAPHIC DESIGNER

Mary Turek

STAFF ENGINEER

John Gorsky

QUIZ COORDINATOR

David Tweed

Cover photograph Chris Rakoczy—Rakoczy Photography

PRINTED IN THE UNITED STATES

Survey Says

jennifer.huber@circuitcellar.com

TASK MANAGER

background image
background image

6

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

September 2003: Internet & Connectivity

12

RS-485 Network for Embedded Systems

Shubhangi Ambekar

24

Design a Wide-Range RS-232 Concentrator Box

Daniel Wiklund & Tomas Henriksson

32

Audio Spectrum Analyzer with a Twist

Veselin Koev

42

The XY-Plotter

Drive High-Resolution LCDs For Less
Robert Lacoste
Mad Dash for Flash Cash Contest Winner

52

Microprocessor Glue Logic with Verilog HDL

Mark Balch

62

APPLIED PCs

Speed Racer

Stand-Alone, Track-Timing Pinewood Derby Computer
Fred Eady

70

FROM THE BENCH

Next-Generation Text to Speech

Winbond Makes Strides with the WTS701
Jeff Bachiochi

4

TASK MANAGER
Survey Says

Jennifer Huber

8

NEW PRODUCT NEWS

edited by

John Gorsky

11

TEST YOUR EQ

edited by

David Tweed

94

INDEX OF ADVERTISERS

October Preview

96

PRIORITY INTERRUPT
Getting Ripped

Steve Ciarcia

78

SILICON UPDATE

ESCape to SF

Tom Cantrell

FEATURES

COLUMNS

DEPARTMENTS

background image

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

Introducing the Atmel AVR

®

. An 8-bit MCU that

can help you beat the pants off your competition.

AVR is a RISC CPU running single cycle instructions.

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

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

With up to 128 Kbytes of programmable Flash and EEPROM,

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

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

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

AVR comes in a wide range of package and performance

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

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

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

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

(It’s also smarter.)

AVR 8-bit RISC Microcontrollers

Memory Configurations (Bytes)

Debug and

Processor

Package

Flash

EEPROM

RAM

Development Tools

tinyAVR

8-32 pin

1-2K

up to128

up to128

Available Now

low power AVR

8-44 pin

1-8K

up to 512

up to1K

Available Now

megaAVR®

32-64 pin

8-128K

up to 4K

up to 4K

Available Now

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

R

background image

8

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Edited by John Gorsky

NEW PRODUCT NEWS

The USBee EX is a new family of USB development

boards. The USBee EX 2.0 supports the development of USB
2.0 high-speed devices, and the USBee EX supports USB
full-speed development. Both platforms use the compact
development board combined with the USBee Toolbuilder
software libraries and drivers to quickly design custom USB
solutions. The USBee EX Experimenter’s
Board is the newest addition to the USBee
Digital Test Pod family.

With USB being the dominant external

PC interface, embedded designs are natu-
rally moving to utilize the bus for connec-
tivity. Using the USBee EX Experimenter’s
Boards, every embedded application can
now gain the benefits of the higher data
rates (480 and 12 Mbps), simple installa-
tion, and self-powered capabilities without
the headaches traditionally found with
USB development.

Unlike other USB development systems,

the USBee EX Experimenter’s Board com-

bined with the included drivers and libraries is a ready-to-
embed solution that’s already optimized for size and cost.
It can be transferring data in minutes, not days.

USBee EX Experimenter’s Boards are fully compatible

with applications written around the familiar USBee
Toolbuilder software frameworks used with the USBee

Digital Test Pods. The USBee Toolbuilder
software allows for the creation of cus-
tom interfacing and test tools using
Visual Basic or C.

The software for the USBee EX

Experimenter’s Board is provided for free
on the company’s web site. In single
units, the USBee EX 2.0 high-speed
Experimenter’s Board costs $199. The
USBee EX full-speed Experimenter’s
Board costs $99.

CWAV
(909) 693-3065
www.cwav.com

RS-232-TO-BLUETOOTH ADAPTERS

The SMART Serial Port Adapter adapts a standard RS-

232 serial port to Bluetooth. The RS-232 adapters include
an on-board antenna and the auto-switching of power
between an external and host supply. The serial module is
a solder-down, Class 1 device with a 50-

antenna output

and 8 MB of flash memory for embedded applications and
Bluetooth upper layer stack.

The RS-232 adapters are designed to enable industrial

customers to integrate Bluetooth functionality into legacy
equipment. The Class 1 adapter supports serial port profile
(SPP), dial-up networking (DUN), generic access profile
(GAP), and service discovery application profile (SDAP).
The Class 2 adapters are simple cable replacements sup-
porting SPP. Both adapters are designed to auto-detect a
power source, allow-
ing the same device
to use either RS-232
power (via pin 9) or
an external power
source. The serial
modules are
designed to enable
industrial customers
to integrate
Bluetooth into their
product offerings,
providing maximum flexibility in antenna placement and
Bluetooth stack support. The adapter costs $81.

SMART Modular Technologies
(978) 988-8848
www.smartm.com

PORTABLE LOGIC ANALYZER

DigiView is a new 18-channel, 100-MHz logic analyzer

that uses a deep capture buffer and real-time hardware
compression to achieve long period captures (up to 5 min.)
with 10-ns resolution. DigiView uses a USB interface and
Windows software for low-cost and highly portable opera-
tion—perfect for lap-
tops, crowded bench
tops, or your desk.
DigiView is about the
size of a deck of cards
and does not require
an external power sup-
ply.

DigiView’s combina-

tion of deep buffer and
high compression
enables capturing
events with 10-ns resolution that could be as far as 5 min.
apart. Having a high compression ratio also means that
bursts of activity interspersed with long dead times (such
as serial data transmissions) can be captured with 10-ns
resolution.

Captured data from real embedded systems is available

for evaluation and can be downloaded from the TechTools
web site. The software and examples will function with-
out a DigiView attached so that users can see the effect of
compression and deep data buffer.

The package includes the hardware, software, cables,

and micro grabbers. The DigiView costs only $499.

TechTools
www.tech-tools.com

USB HIGH-AND FULL-SPEED DEVELOPMENT BOARDS

background image

phyCORE

®

-

ARM7/AT91

subminiature Single Board Computer (53 x 60 mm) in low EMI phyCORE design

Atmel AT91M55800A

ARM7TDMI 32-bit RISC microcontroller (uBGA package)

all signals extend to high-density (0.635 mm) Molex connectors on two sides of board

2 (to 8) MB SRAM, 4 (to 16) MB Flash, 2 (to 8) KB EEPROM

3x RS-232, 2x CAN, JTAG interfaces

CS8900A Ethernet controller (10BaseT)

$299

single unit,

$224.25

unit/100 units, Rapid Development Kit price

$459

http://www.phytec.com/sbc/32bit/pcat91m55800a.htm

(800) 278-9913

www.phytec.com

info@phytec.com

phyCORE

®

-

MPC565

32-bit

Motorola MPC565 PowerPC

with 3x on-chip CAN on an advanced PCB layout

all applicable controller signals extend to two high-density Molex connectors on two sides of board

2 (to 16) MB Flow-Through synchronous Burst-SRAM, (0 Wait-States, 2-1-1-1 Burst-Mode)

to 4 MB synchronous Burst-Flash (optional)

2 (to 8) MB asynchronous Burst-Flash

4 (to 32) KB I

2

C EEPROM

CS8900A Ethernet controller (10BaseT)

4x UART, 1x J1850, 3x CAN interfaces

BDM/Nexus Test/Debug interface

$699

single unit,

$524.25

unit/100 units, Rapid Development Kit price

$859

http://www.phytec.com/sbc/32bit/pc565.htm

phyCORE

®

-

XC161/167

High-speed 16-bit Single Board Computer subassembly based on C166 V2 Core with CAN & Ethernet

in low EMI design

Infineon XC161CJ, XC167CI

microcontroller with on-chip Flash, CAN, JTAG

all signals extend to high-density (0.635 mm) Molex connectors on two sides of board

512 KB (to 2 MB) SRAM (15 ns access), 256 KB Flash, 4 (to 8) KB EEPROM

2x RS-232, JTAG, 2x CAN interfaces

CS8900A Ethernet controller (10BaseT)

$279

single unit,

$209.25

unit/100 units, Rapid Development Kit price

$439

http://www.phytec.com/sbc/16bit/pcxc161.htm

http://www.phytec.com/sbc/16bit/pc167hse.htm

(actual size: 53x60mm)

(actual size: 84x57mm)

(actual size: 53x60mm)

NEW PRODUCTS!!

Fall 2003

Single Board Computer
subassemblies

from evaluation...
... to OEM integration

background image

10

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

NEW PRODUCT NEWS

FREQUENCY-HOPPING TRANSCEIVER

The ER900FHTRS transceiver is a complete subsystem

that combines a high-performance, extremely low-power
RF transceiver, a microcontroller, and a voltage regulator.
The microcontroller programs the functions of the RF
transceiver, controls the frequency-hopping algorithm, and
provides the interface to the host system via a serial
input/output. It also contains programmable EEPROM
memory that holds configuration data for the various
transceiver operating modes. The microcontroller also
relieves the host from the intensive demands of searching
for signals within the noise, recov-
ering the received data, and trans-
mitting data in a suitable format.
An RSSI output can be used to
measure received signal levels.
The module connects to a 50-

antenna such as a whip, helical, or
PCB loop.

The ER900FHTRS intelligent

radio transceiver incorporates Easy
Radio technology to provide a
high-performance, simple-to-use
radio device that can bidirectional-
ly transfer serial data over a range

of up to 500-m LOS. It is intended for use in U.S. markets
on the 900-MHz frequency band and uses frequency-hop-
ping techniques to permit power outputs (allowed under
FCC regulations) greater than similar fixed-frequency
devices.

The transceiver operates from a 3.6-V supply and is pin-

compatible with other industry-standard devices. Serial
input and output simplify the interface to host systems,
and the embedded software significantly reduces design
and development time.

Features include a 120-mW trans-

mit RF power output, a high-sensi-
tivity receiver (typically –100 dBm),
serial input and output for transpar-
ent data transmission, low-power
consumption of less than 18 mA
receive and 150 mA transmit, and
industry-standard DIL style. The
ER900FHTRS costs less than $30 in
OEM quantities.

Easy Radio USA
(207) 286-1600
www.easyradiousa.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

11

What’s your EQ?

The answers are posted at

www.circuitcellar.com/eq.htm

You may contact the quizmasters at eq@circuitcellar.com

CIRCUIT CELLAR

Test Y

Your E

EQ

Problem 3

For a signal that is amplitude modulated

to a depth of 100% by a sinusoidal signal, what is the
ratio of the power of the modulated signal to that of the
carrier alone?

Contributed by Naveen PN

Problem 4

What is the Boolean function realized by

the following DTL circuit?

Edited by David Tweed

Problem 1

A newly hired engineer asked one of his

coworkers how to recognize the byte value 01111110.
The coworker suggested the following circuit.

The company guru, overhearing the conversation, sug-
gested the following change. Why?

V

CC

1

1

1

1

1

1

V

CC

0

0

V

CC

Out

V

CC

1

1

1

1

1

1

V

CC

0

0

V

CC

Out

V

CC

V1

V2

V0

Q

Problem 2

What is Hoth noise?

Contributed by David Tweed

Contributed by David Tweed

Contributed by Naveen PN

background image

tem human machine interface (HMI)
is usually a PC with a complex GUI
that displays various parameters, sys-
tem status, on-line graphs (with a
facility to log important events),
alerts, and alarms.

RS-485 BASICS

Table 1 shows the specifications of

various serial standards currently
available on the market. The RS-485
standard is unique in that it allows
multiple nodes to communicate bidi-
rectionally over a single twisted pair.
No other standard combines this capa-
bility with equivalent noise rejection,
data rate, cable length, and wide com-
mon-mode range.

The standard uses a balanced or dif-

ferential transmission with a pair of
signal lines. The transmitter emits a
true signal on line B and an inverted
signal on line A. The receiver detects

12

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

A

s a lecturer in electrical engineer-

ing, I have covered subjects ranging
from power electronics to network
analysis. Recently, a former student of
mine approached me for help with an
industrial automation project. At the
time, he was working as a consultant,
offering instrumentation solutions to
the industry, and he was having a
problem integrating distributed micro-
controller-based systems in an indus-
trial environment. A commercial
solution was available, but it was
expensive, and cost was a sensitive
issue for his client. Moreover, few
controllers were developed locally.
The integration of these custom con-
trollers with the commercially avail-
able one was another hurdle.

After evaluating various schemes

and multiprocessor architectures, I
finally settled for one that could be
used with an RS-485 serial bus to
interconnect distributed microcon-
trollers. I developed a protocol for
their communication and then deliv-
ered it as a complete package. In this
article, I will explain how to design
and establish a network of micro-
processor-based, widely distributed
intelligent controllers.

PRELIMINARY CONSIDERATIONS

The industrial environment is full

of radio frequency interference (RFI)
and electromagnetic interference
(EMI). Because an industrial plant is
usually spread out over a wide area,
the distribution of the control system
and monitoring instrumentation
offers considerable savings in terms

RS-485 Network for Embedded Systems

Integrating distributed microcontroller-based systems can be a difficult task, especially if
you’re trying to do so in an industrial environment. In this article, Shubhangi shows you how
she helped a former student automate a solar panel production facility with an RS-485 net-
work for embedded systems.

of installation and the maintenance
cost of long cables.

The control system must be highly

reliable. A plant is typically operated
from a remote control room. The
decentralization of control requires
extra networking hardware and soft-
ware but adds to the flexibility. In
addition, distributed control offers less
computing power at the control loca-
tion (node) as it handles a small dedi-
cated control task, which suggests
using an inexpensive single-chip
microcontroller would make it highly
configurable as well.

Today, a variety of microcontrollers

offer sufficient computing power,
extensive Boolean processing capabili-
ties, an optimized instruction set, sin-
gle-cycle instruction execution, and
plenty of on-chip resources. The result
is a complete embedded control sys-
tem on a single chip. The control sys-

FEATURE ARTICLE

by Shubhangi Ambekar

Table 1—

Serial communication is popular, and there are a few standards that are commonly used. Compare how

these standards differ in their specifications. Choose the most appropriate according to your own requirements.

Parameter

Serial standard

RS-232

RS-423A

RS-422A

RS-485

Mode

Single-ended

Single-ended

Differential

Differential

Drivers

1

1

1

32

Receivers

1

10

10

32

Maximum cable length (m)

15

1200

1200

1200

Maximum data rate

20 kbps

100 kbps

10 Mbps

10 Mbps

Transmit levels

±

5-V minimum

±

3.6-V minimum

±

2-V minimum

±

1.5-V minimum

±

15-V maximum

±

6-V maximum

Receiver sensitivity

±

3 V

±

0.2 V

±

0.2 V

±

0.2 V

Load Impedance

3 to 7 k

450-

minimum 100-

minimum 60-

minimum

Output current limit

500 mA to V

CC

150 mA to GND

150 mA to GND

150 mA to GND,

or GND

250 mA to –8 V,
or 12 V

Driver Z

OUT

minimum (power off) 300

60 k

60 k

120 k

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

13

resistor should be placed only at the
far ends of the data line.

A terminator resistor adds DC load-

ing to the system. An AC terminator
adds a small capacitor in series with
the termination resistor to eliminate
the DC loading; however, the value of
the capacitor is system-dependent.

A unit load (UL) allows 1 mA of

current under a maximum common-
mode voltage stress of 12 V or 0.8 mA
to –7 V. [1] Unit loads may consist of
drivers, receivers, and fail-safe resis-
tors, but they do not include the ter-
mination resistors. The RS-485 stan-
dard recommends a maximum of
32 UL per line. The 32 UL can include
many devices but is commonly com-
prised of 32 transceivers. You must
observe a 32-UL limitation, because
the load appears in parallel and adds
to the load that the termination resis-

voltage difference between both the
inputs. The receiver output is logic
high if line A is at least 200 mV high-
er than line B. The receiver output is
logic low if line B is at least 200 mV
higher than line A.

Note that there is a ground return

line in addition to signal lines. The
ground line carries a current that
results from small imbalances (if any)
in the balanced line. The common
ground connection keeps the com-
mon-mode voltage at the receiver
within safe range. The RS-485 stan-
dard recommends connecting a 100-

Ω,

0.5-W resistor in series with the signal
ground of the transceiver to the net-
work ground. Thus, if the ground
potential between two nodes differs,
the resistor limits the current.

The use of balanced lines suggests

better noise performance because
noise is coupled in both wires of a sig-
nal pair in much the same way and is
common to both signals. Because of
the common-mode rejection capabili-
ty of the differential receiver, this
noise will be rejected. Additionally,
the signal line emits a signal that’s
the opposite of the adjacent signal
return line, so the emissions cancel
each other. This is true in the case of
crosstalk between neighboring signal
lines. It is also true for noise from
other sources as long as the common-
mode voltage does not go beyond the
common-mode range of the receiver.
Because ground noise is also common
to both the signals, the receiver rejects
this noise as well.

The standard is suitable for transfer-

ring small blocks of data over long dis-
tances. The network nodes can be PCs,
microcontrollers, or any other devices
capable of asynchronous communica-
tion. Several vendors offer RS-485 trans-
ceivers with various combinations of fea-
tures. Unlike the RS-422 that allows for
a single driver with multiple receivers,
RS-485 supports multiple drivers and
receivers in a multipoint configuration.
The recommended specification
(TIA/EIA-485A) does not define a con-
nector layout or software protocol, it
only describes the electrical specifica-
tions of the drivers and receivers. It
briefly suggests the characteristics of
line and termination requirements.

The twisted-pair cable used in this

interface in combination with the cor-
rect line termination (to avoid line
reflections) of the bus offers high data
rates (10 Mbps) and a long cable length
(1.2 km), but not simultaneously. If you
have a short cable that behaves like a
lumped line instead of a transmission
line, you don’t need a termination. A
good rule is if the rise time of the sig-
nal is much greater than the propaga-
tion delay (this value is specified by
the cable manufacturer as approxi-
mately 60% of the speed of light) of
cable, it behaves like a lumped line.
Otherwise, the line behaves like a
transmission line.

If you do not terminate a transmis-

sion line in its characteristic imped-
ance, the load (receiver) will not com-
pletely absorb the signal and reflec-
tion will occur. The termination

D

R

T

R

A

A

B

B

100

0.5 W

D

R

T

R

A

A

B

B

100

0.5 W

D

R

T

R

A

A

B

B

100

0.5 W

Rt

Rt

Two-wire RS-485 network

Node 1

Node N

D

R

T

R

A

A

B

B

100

0.5 W

D

R

T

R

A

A

B

B

100

0.5 W

D

R

T

R

A

A

B

B

100

0.5 W

Rt

Rt

Four-wire RS-485 network

Node 1

Node N

Rt

Rt

Figure 1a—

A two-wire multipoint topology is one way to configure the RS-485 network to enable the half-duplex

data transfer.

b—

A four-wire multipoint topology is required for a full-duplex data transfer.

a

)

b

)

background image

14

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

(typically 50 to 120

) is added, only a

few millivolts (insufficient) of bias
voltage are differentially generated by
the on-chip circuit, which suggests the
use of an external circuit.

The tristate capability of the RS-485

enables a single wire pair to share
transmit and receive signals for half-
duplex communication. This two-wire
configuration (one additional wire is
required for signal ground) requires a
single twisted pair (see Figure 1a). If
full-duplex communication is neces-
sary, the transmitters and receivers
must have separate differential input
and output lines. The transmit lines of
a master node connect to the receive
lines of the slave nodes and vice versa
(see Figure 1b).

For a sender node to transmit its

data within a network to a receiver
node, the latter must be informed that
it should listen for incoming data.
During the transmission of data, no
other node in the network should
initiate another data transmission
unless previous data transmission
has finished.

All of the nodes in the RS-485 net-

work share a common (two- or four-
wire) serial bus, so there must be
some entity (i.e., bus controller) to
control the bus ownership so that the
data can be communicated successful-
ly. The bus controller (typically one
node) grants a bus to a sender node
with a command response type of

tors present to the driver.
Exceed 32 UL, and the loads
will load the drivers excessive-
ly, forcing them into current-
limiting and attenuating the
differential signal. This reduces
the differential noise margin.

You can obtain transceivers

with a 0.5- or 0.25-UL rating
that allows for 64 or 128 trans-
ceivers; however, such frac-
tional, high-impedance UL
devices typically operate slow-
er (~100 kbps) than single UL
devices (10 Mbps). You can use
repeaters that power the line to
overcome 32-UL limitations.

The protocol is left up to

you. You may use the asyn-
chronous data transmission
protocol supported by the
UART in microprocessors and PCs.
Thus, the node CPU doesn’t need to
spend time periodically sampling the
input serial bitstream and converting
it to parallel words. This may be one
of the reasons for its popularity. You
may opt for a simpler protocol as per
your application needs.

NETWORK IMPLEMENTATION

You can wire an RS-485 network as

shown in Figures 1a and 1b. If all the
drivers in an RS-485 are disabled (tris-
tated) and all the receivers are enabled,
the network is in an idle state. Without
an active driver, the state of the line is
unknown, and voltage along the line is
indeterminate. If the voltage level at
the receiver’s A and B inputs is less
than

±

200 mV, the receiver can be

falsely triggered (into either a logic-
high or logic-low state), depending on
the presence of noise and the last
polarity of the floating line. It is best
to place the receiver output in a pre-
determined state. To maintain a prop-
er idle voltage state (i.e., a minimum
of 200 mV), two bias resistors are
used: a pull-up to 5 V on line B, and a
pull-down to signal ground on line A
(see Figure 2).

The value of bias resistors is

dependent on termination and the
number of nodes in the system.
Device manufacturers provide a bias
circuit on the chip with 100-k

bias

resistors. If an external terminator

interaction. The sender node
owns the bus, transfers its
data, and relinquishes the
bus back to the bus con-
troller. The bus controller
grants the bus to the some
other node in the network.
Thus, it finds out which
requires the bus, grants it,
and allocates the bus owner-
ship on a round robin basis,
ensuring that only one node
owns a bus at a given time.

The data blocks, which the

nodes exchange normally,
have a predefined byte order,
so the receiving node under-
stands the meaning of the
data. The sending and the
receiving node follow a com-
mon bit-error checking algo-

rithm (e.g., cyclic redundancy check or
checksum computation) to track the
errors introduced (if any) in the long
transmission channel.

In the absence of a bus controller,

more than one node may attempt to
transmit the data simultaneously,
which would force data bits to collide
and create contention. In such a situa-
tion, the receiving node doesn’t inter-
pret the data correctly, and the trans-
mitted data is corrupted and lost. It is
possible to detect such a collision con-
dition by monitoring the network data
by the sender node or by comparing
the computed checksum with the
received one by the receiving node. As
the number of network nodes increas-
es, the number of collisions increases,
and each receiving node spends signifi-
cant time rejecting the corrupted data.

The bus controller implements com-

plete bus arbitration logic in the soft-
ware to avoid the possibility of colli-
sion. This type of network configura-
tion resembles master (bus controller)
and slave (network nodes) architecture.

Intel MCS51 microcontroller archi-

tecture has an on-chip UART, which
supports multiprocessor serial com-
munication in hardware. In mode 2 or
3, the UART transmits a 9-bit charac-
ter (8 data bits and 1 control bit).

The processor can be programmed

to generate a serial interrupt if the
control bit is received as a one. I
have used this feature to implement

D

R

T

R

A

A

B

B

Bias resistor

Two-wire

twisted pair

RS-485 cable

Driver enable

Bias resistor

+5 V

One shot

circuit

C

+5 V

R

One character length at select data rate

Data bits + parity bit

Stop bit

Start bit

Serial data at D
input

One shot driver
enable output

12 k

Figure 2—

You must enable a single driver to avoid RS-485 bus contention. You

can use software, but the hardware solution keeps the CPU free for more impor-
tant control tasks, particularly at lower data rates. A biasing resistor network
works well for idle line conditions.

background image
background image

16

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

a master/slave RS-485 network using
an 8x51 microcontroller. Each network
node is assigned a unique 8-bit address.

The MCS51 architecture has a spe-

cial function register (SCON) for serial
port control and configuration (see
Figure 3). SM0 and SM1 bits specify
the serial port mode. The SM2 bit
enables the multiprocessor communi-
cation feature in modes 2 and 3. If
the SM2 bit is set to one, the receiv-
er interrupt flag (RI) will not be acti-
vated if the ninth data bit (RB8)
that’s received is zero.

An RI or transmitter interrupt flag

(TI) bit can generate a serial interrupt,
and the interrupt service routine has
to find out which one generated it.
The TB8 bit holds the control bit (the
ninth bit), and the SBUF special func-
tion register holds the 8-bit data to be
transmitted or received. The serial
port is full-duplex, which means it
can transmit and receive simultane-
ously; it is also receive-buffered, so it
can commence the reception of a sec-
ond byte before a previously received
byte has been read from the register.
Listing 1 shows how to initialize the
MCS51 on-chip UART for multi-
processor communication (mode 3).

When the bus controller

wants to communicate with
one of several slaves (nodes),
it first sends out an (node)
address byte with the con-
trol bit (TB8) set to one,
which identifies the target
slave. The address byte dif-
fers from a data byte in that
the control bit (ninth bit) is
one in the address byte and
zero in the data byte.

When SM2 equals one, a

data byte will not interrupt
a slave. An address byte,
however, will interrupt all
slaves, so each slave will
examine the received byte
and see if it is being
addressed. The addressed
slave will clear its SM2 bit
and prepare to receive the
incoming data bytes. The
slaves that aren’t being
addressed leave their SM2
bit set and go about their
business, ignoring the

incoming data bytes. This scheme
minimizes software overhead of pro-
cessing unwanted network data by
each slave without an address.

The bus controller sends one byte

address (8 bits) to a node (see Listing 1).
The node responds with one byte indi-
cating its further action or operation.
The bus controller uses the MSB (bit 7)
of the address byte to signal the cause
of the node’s interruption. If the bit is
set to one, the node is interrupted to
show that the bus is free and can take
over the bus control. If the bit is set
to zero, the network data is pending
for the node, and it should prepare to
receive data.

If the node has data pending in its

output buffer for transmission to the
network, it responds with
GRANT_BUS_REQ status (see Listing 2).
The bus controller issues a
BUS_GRANTED command, and the
node proceeds with its data transmis-
sion. Otherwise, if the node does not
need the bus control, it responds with
NODE_NOP (i.e., no operation). If the
bus controller isn’t acknowledged, it
assumes that the node is not free to
communicate and proceeds to inter-
rogate the next node. This may hap-

pen when the node is executing a
critical section of code and has dis-
abled its interrupts.

When a sender node owns the bus

control for data transmission, it can
transmit the data directly to the
receiver node, or it can first transfer
the data to the bus controller node,
which later relays it to the receiver
node. Choosing a method depends on
the network topology—either two-
wire or four-wire. The former is suit-
able when the sender node requires
the frequent transmission of data,
whereas the latter works well during
protocol development because the
data passes through the bus controller,
which is easily logged and examined
for detecting bugs.

After the data transfer, the bus

controller interrupts the node and
transmits a

BUS_RELINQUISHED

response. The bus controller regains
the bus control and transfers its con-
trol to the next node in the
sequence. If the node detects that it is
interrupted for data reception opera-
tion, it responds with the

NODE_READY

status. Then, the node begins the data
block reception. If the node discovers
that it is not ready to accept network

data, it responds with the
NODE_BUSY status. A lack of
space for new data could
cause this.

The bus controller (with

one additional RS-232 port)
can be configured as a gate-
way to the host PC for
remote control of the slave
nodes. The block data trans-
fer routines at the bus con-
troller and nodes use a pre-
defined byte order (e.g.,
block length, destination
address, and data bytes block
16-bit checksum) so that
data can be exchanged in an
organized manner. The data
bytes are usually emitted as
an 8-bit binary quantity,
assuming the sending and
receiving nodes know how
to interpret the data.

During data transmission,

the transmitting node
enables its driver. This is
done by connecting one port

SM0 SM1 SM2 REN TB8 RB8

TI

RI

MSB

LSB

where SM0 and SM1 specify the serial port mode as follows:

SM0 SM1 Mode Description Data

rate

0 0 0 Shift

register

f

osc

/12

0 1 1 8-bit

UART

Variable

1 0 2 9-bit

UART

f

osc

/64 or f

osc

/32

1 1 3 9-bit

UART

Variable

SM2—Enables the multiprocessor communication feature in modes 2 and 3.
In modes 2 or 3 if SM2 is one, RI will not be activated if the receiver ninth
data bit (RB8) is zero. In mode 1, if SM2 is one, RI will not be activated if a
valid stop bit was not received. In mode 0, SM2 should be zero.

REN—Set by software to enable serial reception. Cleaned by software to
disable reception.

TB8—The ninth data bit that will be transmitted in modes 2 and 3. Use the
software to set or clean TB8.

RB8—The ninth data bit that was received in modes 2 and 3. In mode 1, SM2
is 0, and RB8 is the stop bit that was received. In mode 0, RB8 is not used.

TI—Transmits interrupt flag. Set by hardware at the end of the eighth bit time
in mode 0 or at the beginning of the stop bit in the other modes (in any
transmission). Must be cleared by the software.

RI—Receives interrupt flag. Set by the hardware at the end of the eighth bit
time in mode 0 or halfway through the stop bit in the other modes (in any
serial reception except SM2). Must be cleared by the software.

Figure 3—

Intel’s MCS51 UART supports multiprocessor communication using a

9-bit communication protocol. The protocol is easy to adopt for the RS-485 network
and requires little software overhead.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

17

Listing 1—

The code snippet shows the logic of the bus controller node. The DS80C320 on-chip UART ini-

tialization for 9-bit protocol is also included.

#define MAXIMUM_NODES 7

//Define maximum nodes available in the network

int max_nodes, thisnode;

//General-purpose variables

int i, response, Bus_Idle;

//Used for storing intermediate results

void Init_MCS51_UART(void)

//Port 0 and Port 1 at 19.2 kbps for 11.059 MHz

{

asm ("MOV PCON, #080H");

//Port 0 make SMOD = 1 for 19.2 kbps

asm ("MOV WDCON, #080H"); //Port 1 make SMOD = 1 for 19.2 kbps

asm ("MOV TMOD, #020H"); //Init timer #1 auto reload

asm ("MOV TH1, #0FDH");

//Timer high byte 11.059 MHz,19.2 kbps

asm ("MOV TL1, #0FDH"); //Reloaded automatically in this mode

asm ("MOV SCON, #052H");//Port 0 mode 1, clear RI

asm ("MOV SCON1, #0faH");

//Port1 mode 3, TB8_1 = 1, clear TI, RI

asm ("setb TR1 ");

//Run timer #1

}

main()

{

while (1) {

//Scan the network continuously

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

//Do a serial polling for

each node sequentially

response =SendData(i|0x80); //Intimate bus is free

switch (response) {

//Check how node responds to the

above command

case GRANT_BUS_REQ:

//Node want the bus for data transfer

{

SendData(BUS_GRANTED);

//Bus is granted

response = RecvNetData(buf);

//Read the network data for relaying to other node

if (response == SUCCESS) {

//Relay received data to destination only on success

response = XmitNetData (buf, destination);

}

}

break;

case NODE_NOP: //Node does not require a bus

{

Bus_Idle++;

//Estimate bus bandwidth currently being used

}

break;

case TIME_OUT:

//Add code to notify timeout error

break;

}

}

}

}
void XmitNetData (char *buf, char destination)

{

SendData(destination & 0x7f);

//Inform the node to receive the network data

response = RecvData();

//Wait for node response

switch (response) {

case NODE_READY:

SendNetData(buf);

//Node is waiting so send data

break;

case NODE_BUSY:

//Save the data in waiting queue as node is busy

break;

case TIMEOUT:

//No response from the node. Report time out error.

break;

}

}

background image

18

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

line to the transmitter ENABLE pin
and controlling it with the software
(see Listing 2).

The timing of the ENABLE signal

should be precise so that the sender
node relinquishes the bus and the other
node takes over. If the sender node
takes more time, it may miss the begin-
ning of a response. Thus, the sending
node’s CPU must wait until the TI flag
is set to one (transmission of one char-
acter) and the software implementa-
tion wastes valuable CPU time (1 ms

for one character at 9600 bps). A way
around this problem would require a
responding driver to wait before it
begins sending the response. This
would ensure that the previous driver
has been disabled and there is no bus
contention.

You can set the CPU free by provid-

ing a hardware timer (a monostable,
one-shot circuit), which can automati-
cally enable the driver for one charac-
ter period instead of keeping it enabled
for entire data block transmission.

The circuit in Figure 2 enables the
driver on the falling edge (start bit) at
the driver input. The driver remains
enabled for the entire character peri-
od and is automatically disabled. The
timing of the one-shot circuit can be
adjusted by changing either the R or
the C lines.

If you want to operate on a variety

of data rates, you can have different
registers (one for each data rate), or
even a variable register, and select the
required RC combination using short-
ing jumpers. The timer’s output con-
trols the transceiver’s enable input. A
falling edge at the data output line (D)
indicates a start bit and triggers the
timer (see Figure 2). The timer output
goes high, enabling the driver for one
shot period. To avoid the extension of
the driver enable time beyond one
character length, the timer should not
be retriggerable.

If you want to connect a PC to a

two-wire RS-485 network, you need
an RS-232-to-RS-485 converter. The
half-duplex RS-485 network suggests
the data flow between the RS-485 net-
work and PC in one direction at a
time, however, the PC’s RS-232 port is
bidirectional. The converter handles
this problem using the RS-232 flow
control signal RTS/CTS line. It uses
this handshake line to enable the RS-
485 transmitter (or disable the receiv-
er) and choose the data flow direction.
Thus, you can write a Win32 applica-
tion (using Visual Basic) to monitor
and debug RS-485 network code.

ACHIEVE AUTOMATION

The aforementioned protocol was

employed to automate a solar panel
production facility. A solar cell panel
consists of an array of photocells that
are connected (in a parallel and serial
combination) to achieve the required
output. Each cell is chemically grown
over an area of about 100 mm × 100 mm
on a glass substrate. The cell’s output
depends on the area and thickness of
the deposition. Initially, the substrate
is uniformly deposited with the pho-
tosensitive material and suitable pat-
terns are cut with a laser.

After this, the photocell is subjected

to the automated inspection system,
which measures various parameters

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

19

and performs qualifying tests for qual-
ity assurance and control. Finally, the
solar cells are mounted on a carrier
board to form a solar panel. After the
electrical connections are complete,
load testing is performed to evaluate
each panel’s performance. The aim of
automation was to increase through-
put and reduce production cost.

Because the unit is spread out in a

100-m hall, I chose a two-wire, half-
duplex, master-slave configuration for
the distributed control system. I used
MCS51-based controllers to control
various processes (e.g., the conveyor
belt system, temperature control of
the disposition system, the position
sensing and counting of cells, chiller
control, etc.).

Table 2 shows various parameters

associated with the different process-
es, the nature of control required,
and the information flow of the net-
work. I dedicated one MCS51 micro-
controller to each process. Each node
has a similar hardware configuration
with a CPU card, analog I/O card,
and digital I/O card. The bus con-

Figure 4—

Optical isolation provides improved noise performance. I’ve depicted one RS-485 node with the isola-

tion barrier. You’ll need a similar circuit at each network node.

background image

20

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

troller node has only one CPU card
based on Dallas’s 80C320 microcon-
troller because it has two on-chip
UARTs. One serial port is used for
the RS-485 network; the other is
used with the RS-232 interface for
connection to the operator PC in the
control room.

Most of the information flow takes

place between the PC (bus controller)
and network nodes. The conveyor
belt node needs to talk with the
laser-cutting system node and inspec-
tion/ATE node to notify the arrival

and departure of the cell. Because
each conveyor belt segment is located
adjacent to the laser-cutting system
or ATE, I opted for hardware notifi-
cation using the optocoupler to pass
the information from the conveyor
belt node controller. I went this
route because it involved a few short
cables (shorter than 1 m).

Depending on the specific nature

of the cell application, its output
voltage, and current information
from a load test, the inspection/ATE
marks the cell as qualified or reject-

Listing 2—

The RS-485 network interaction at the node is carried out as a background process using a

serial interrupt. You can implement the control task as the foreground task and even disable the serial inter-
rupt during critical code execution. The code fragment is a part of the interrupt service routine at the node.

The code must be made part of serial interrupt handler at the

node. Code assumes LastChar contains a char received with TB8=1.

The serial interrupt must be enabled and, if possible, assigned

the highest priority.

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

if ((LastChar & 0x7f) != MY_NODE_ADDRESS) return;

//Data not for me

if (LastChar & 0x80) {

//Is it bus free intimation ?

if (Bus_Is_Required) {

//Output buffer is full!

TB8=0;

//Clear TB8 bit for data transmission

SendData (GRANT_BUS_REQ); //Make a formal bus request

If (RecvData() == BUS_GRANTED) {

//If the bus is granted, transmit pending data to bus controller

SendNetData(buf);

}

}

}

else {

//This is data reception request

if (Room_For_new_data) {

//Input buffer is empty

TB8=0;

//Clear TB8 bit for data transmission

SendData(NODE_READY);

//Inform that you are ready to receive the data

response = RecvNetData(buf); //Go receive the network data

}

else {

TB8=0;

//Clear TB8 bit for data transmission

SendData(NODE_BUSY); //Ready to receive the network

data

}

}

//End of (serial interrupt handler) network access algorithm

at the node

void SendData ( unsigned char ch)

//Function to transmit one character to network

{

asm ("jnb TI,$");

//Wait for previous transmission to complete

TI =0;

//Initiate new transmission

TxEN = 1;

//You must enable transmitter

SBUF = ch;

//RS-485 transmission begins here

asm ("jnb TI,$");

//CPU must poll and wait until character transmission

TxEN =0;

//Do not forget to disable it

}

background image

ed. The conveyor belt controller is
then told to transfer the cell to the
corresponding container.

OPTICALLY ISOLATED NETWORK

Galvanic isolation is a proven route

to improved noise performance for any
interface system. The entire RS-485
network shares a common ground line
and all the transceivers must operate
with common-mode voltages between
–7 and 12 V. The common-mode volt-
age at the receiver is the algebraic
mean of the two signal voltages ref-
erenced to the receiver’s signal
ground, which means it contains a
contribution from the coupled noise
on both signal wires and the ground
potential difference between the
node and active driver on the bus.
Hence, the common-mode voltage
varies with the differential signal volt-
age, noise on the line, and the ground
potential difference between driver
and receiver.

For a network with a long cable, it

may be difficult to satisfy the com-
mon-mode specification. The isolation
in data communication systems is
achieved without direct galvanic con-
nection or wires between the drivers
and receivers. A magnetic linkage
from the transformer provides the
power for the system; optocouplers
provide the data connection.

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

21

REFERENCE

[1] Texas Instruments, Inc.,

“Interface Circuits for
TIA/EIA-485,” SLLA036, 1998.

Shubhangi Ambekar earned a
B.S.E.E. from The Regional College
of Engineering, Nagpur University,
India. She currently heads the
Electrical Engineering Department
at Nagpur. Her interests include
power electronics and embedded
systems. You may reach Shubhangi
at ambekar_ss@hotmail.com.

RESOURCES

Intel Corp., MCS51 Microcontroller
Family User’s Manual

, 272383-002,

1994.

T. Nelson, “The Practical limits of
RS-485,” Application Note 979,
National Semiconductor Corp.,
1995.

RS-422 and RS-485 Information,
B&B Electronics, www.bb-elec.com.

SOURCES

MCS51 Microcontroller
Intel Corp.
(408) 765-9904
www.intel.com

Galvanic isolation removes the

ground loop currents from data lines;
therefore, the impressed noise volt-
age that affects the signal is elimi-
nated. With this technique, com-
mon-mode noise can be removed and
many forms of radiated noise can be
reduced to negligible limits. Figure 4
shows a scheme for implementing
such an interface.

Using three devices, three optocou-

plers isolate the D line, transmitter
and receiver ENABLE line (DE/*RE),
and R line. A high-speed device is
required for transmit and receive lines
(during operation at higher data rates).
The inexpensive MCT2E can be used
for transceiver-enable operation. The
isolated power is obtained using a DC-
DC converter module. Many vendors
offer such modules, which have wide
input and single or multiple output
options. Maxim’s MAX 1480 provides
a similar interface as a single chip
solution. If the output is any value
other than 5 V, then a regulator IC
(e.g., LM78L05) can be employed. The
dashed vertical line in Figure 4 shows
the isolation barrier.

Now it is time for you to start

thinking about ways to distribute the
control in your embedded applica-
tions. Using this article as your
guide, you are sure to construct a
highly reliable system.

I

Process/Entity

Parameters controlled/monitored

Nature of control

Node number

Information flow

Chemical deposition

Temperature

PID

1

Temperature set point

Coolant temperature and flow monitoring

Coolant temperature and flow

switch status

Deposition thickness

Thickness value

Conveyor belt system

Motion control

Proportional

2, 3, 4 (one for each segment)

Motor speed set point input

(three segments)

Cell detection and positioning

Cell drier control

On/off

Cell cutting system

Start signal

5

Start cutting operation input

Coolant flow and temperature monitoring

Coolant temperature and flow

switch status

Cutting complete status

Cutting operation over status

Inspection/automatic

Cell voltage, current, layer conductivity

6

Photocell parameters (e.g.,

test equipment (ATE)

Use of computer vision for automatic

voltage, current, conductivity,

inspection of cracks, defects, etc.

area, size, etc.)

Cell acceptance criteria as set

of parameters

Measurement of actual cell size, area, etc.

Counting of accepted and rejected cells

Chiller for coolant supply

Flow (input and output)

Proportional

7

Flow set point and status

to various subsystems

Inlet and outlet temperature in each branch

Temperature status at various

locations

Leakage detection

Leakage status

Table 2—

The processes are linked together, and their physical location and data flow decides the allocation of the intelligent controller.

background image
background image
background image

details. An overview of our system is
shown in Figure 1.

A control post never needs more

than four electronic punching units. A
data packet is sent out when a com-
petitor punches. The data packets con-
sist of a maximum of 25 bytes. The
punching units use a transmission
speed of 4800 bps, and the minimum
time between two consecutive pack-
ets from one punching unit is at
least 500 ms (for practical reasons).
Thus, the maximum data rate for
one punching unit is 500 bps (2 ×
25 × 10). Refer to the sidebar for
information concerning the
Sportident packet format.

We wanted to collect four punching

units on one serial line, so the total
data rate is, at most, 2000 bps, which
is well below 4800 bps. Thus, we were
able to use the same speed for the link
from the concentrator box to the PC.
This was advantageous because we
could use a built-in UART. The built-
in UART is restricted to the extent
that reception and transmission can-
not use different data rates. Because

the incoming and outgoing data rates
could be the same, it was possible to
use the UART for one incoming as
well as the outgoing channel.

We implemented an Atmel

AT90S2313 for the concentration of
the data packets. Initially, we consid-
ered a small FPGA, but the microcon-
troller has a simpler booting proce-
dure with the program stored directly
in flash memory.

The AT90S2313 is an 8-bit micro-

controller with one hardware UART.
We can use the same speed for input

24

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

F

or years, orienteering has been a

popular outdoor sport in Scandinavia,
and now it’s gaining attention in other
countries. Put simply, orienteering is a
cross-country race in which competi-
tors have to find their way through a
forest by checking in at numerous con-
trol posts marked on a special map.
After stopping at each control post (in
a particular order), the competitors
must run to the finish line, which is
also marked on the map. At the finish
line, an announcer reads the results to
the spectators. Normally, cooperation
between contestants isn’t allowed, so
start times are roughly 3 min. apart. A
runner may use a compass, but all
other forms of navigational equipment
(e.g., GPS) are forbidden.

The event organizer’s job is to prove

that each competitor has completed the
course and has visited all the control
posts in the correct order. Competitors
used to carry small paper cards, which
were punched with metal clips at each
control post. Nowadays, electronic
punching systems are implemented.

Electronic systems are advantageous

because the splits are made available
after the race, and spectators and com-
petitors can have thorough analysis of
the competition. For these purposes,
each electronic punching unit has an
RS-232 connection. A data packet is
sent each time a competitor punches
on the control post. Having the ability
to obtain splits from a control post is
advantageous for several reasons.
Spectators enjoy the additional infor-
mation because it increases the over-
all excitement of the race. In addi-
tion, relay runners appreciate the

Design a Wide-Range RS-232 Concentrator Box

In the popular Scandinavian sport of orienteering, competitors race through a forest and
record their progress via an electronic punching system. In an effort to generate a bit more
excitement amongst the spectators, Daniel and Tomas designed a concentrator box that
immediately reports the competitors’ split times to the contest administrator at the finish line.

information because it helps them
prepare for the upcoming legs of the
races they’re running.

Our design project has allowed us to

address two problems. First, many
control posts have more than one
punching unit, but the computer soft-
ware for speaker support only accepts
data packets on one serial port, so the
data packets must be concentrated to
one single RS-232 connection. The
second problem has to do with dis-
tances. Some control posts used for
automatic reporting are situated sev-
eral hundred meters from the finish
line, which is well beyond the range
of the RS-232 connection. As we
thought about ways to address these
problems, we came across a system
for wireless packet transmission. We
soon discovered, however, that the
system is expensive and requires an
operating license. Thus, we designed a
cost-sensitive wired alternative.

DESIGN CONCEPT

Let’s put the sports talk on hold and

take a closer look at the technical

FEATURE ARTICLE

by Daniel Wiklund & Tomas Henriksson

Receiver

Alternative 2

Alternative 1

Concentrator

box

Punching

units

1000 m

Figure 1—

There are two alternatives for connection to

the PC. The first uses the RS-232 port of the concentra-
tor box for short-distance connections. The second uses
the current-loop port on the concentrator box, a 1000-m
cable, and the receiver for long-distance connections.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

25

diode, D1, is there for the protection of
the transistor. The software receivers can
handle the inverted levels directly and
do not need the hardware inversion.

The components only limit the cur-

rent and voltage levels presented at the
microcontroller. The Zener diodes (D2,
D3, and D6) will limit the voltage in
the reverse direction to 4.7 V and in the
forward direction to approximately 0.7
V, thus relieving the ESD protection
diodes in the microcontroller.

The concentrator box has two out-

puts. One output is used for direct con-
nection to a serial port on a computer;
the second is for the long-distance con-

nection in combination with the
receiver box. Only one of the outputs is
normally used at a time, and that
depends on the distance between the
computer and punching units.

There are two cases when the punch-

ing units are close to the computer.
First, there are always punching units
on the finish line, which are close to
the announcer’s booth. Second, control
posts situated farther than 1000 m from
the finish line are monitored via a lap-
top. The operator uses an analog radio
to report the split times to the speaker.

The RS-232 output levels were a big-

ger problem than the inputs. Because

and output, so the UART can be used
for one receiving channel as well as
the output transmission. The other
three input channels must be received
in the software. With 4800 bps, four
incoming channels, and a 7.3728-MHz
clock frequency, we have 384 cycles
per channel per bit. With an oversam-
pling of eight on the software imple-
mentations, we have 48 cycles of pro-
cessing per sample, which is definitely
possible to implement.

For long-distance communication,

we had access to 1000-m one-pair
wire, so we choose to design a simple
current loop. Because we tend to be

paranoid, we decided to optically iso-
late the link in the receiver.

BOX HARDWARE

The project started with a schematic

(see Figure 2). We were on a tight budg-
et, so we did not go for the simple solu-
tion of two MAX202s for the RS-232-to-
logic level conversion. Instead, the input
levels are adapted to the 5-V logic levels
with the discrete components to the left.

The RS-232 standard uses inverted lev-

els compared to normal logic, so the
input must be inverted for the hardware
UART to work properly. This is achieved
with the R1-Q1-R5 combination. The

Figure 2—

The four circuits with resistors and diodes on the left are the concentrator box’s RS-232 receivers. Note that the uppermost circuit is connected to the AT90S2313’s

hardware USART and must be inverted. The circuit to the lower right is the current-loop transmitter.

Figure 3—

The current-loop receiver is incredibly simple. The input is connected to an AC-mode optocoupler to

take care of arbitrary polarity on the inputs.

background image

26

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

somewhat protected using a 100-

resistor in series with the LEDs.
The output of the optocoupler is
fed directly to an input on a
MAX202 chip for the transfer to
RS-232 levels. The receiver box
schematic is shown in Figure 3.

The receiver box is connected to a

PC, so we decided to draw the power
from the PC. The receiver box oper-
ates on a nominal 5-V level, which is
available directly on the joystick port
on most PCs. If there isn’t a joystick
port, you could use the PS/2 or USB
ports for power. They both carry 5 V.

SOFTWARE ARCHITECTURE

All of the software was written in

assembly language. The most chal-
lenging task was to manage with only
32 registers and 128 bytes of data
memory. One of the inputs was handled
by the hardware UART. The other three
inputs were connected to the microcon-
troller’s general-purpose inputs. Thus,
the program had to sense the inputs at
regular intervals and check for start bits.

The entire program executes in

Interrupt mode. The main loop pro-

only 6 V was available, there was a
need for charge pumping to the

±

12 V

needed for RS-232 transmission. The
simplest and cheapest solution was to
use one MAX202 chip with an integrat-
ed charge pump for the transmission.
The chip has two receiver stages, but
they are unused. We could have used one
receiver to convert the first input chan-
nel—the one connected to the hardware
UART—but we did not. All the RS-232
inputs and outputs are available through
ordinary nine-pin D-SUB connectors.

The current loop is a simple on/off

loop that drives an optocoupler with
AC input (using double cross-coupled
LEDs), which also makes the current
loop insensitive to polarity. The driver
uses a low-side switch, Q2, and resis-
tors to protect the box in case of a
short circuit in the loop. The current
loop is available on the box using
rugged 4-mm banana connectors.

Power for the concentrator is delivered

by the 6-V rechargeable battery com-
monly used by orienteerers during the
dark winters of northern Scandinavia to
drive their headlamps. The batteries
deliver only 6 V and the system runs on
5 V, so we needed a low-dropout voltage
regulator. National Semiconductor’s
LM2931 was readily available and inex-
pensive. The LM2931 drops 0.6 V at
100 mA. The project doesn’t consume
more than 25 mA, so the dropout voltage
may be down to 0.3 V, which allows the
batteries to become nearly flat without
the concentrator box giving up its breath.

RECEIVER HARDWARE

The current loop receiver has an

optocoupler input. The optocoupler is

grams only a built-in timer to generate
interrupts at constant intervals corre-
sponding to eight times the oversam-
pling of 4800-bps serial communication.

There are three status levels for each

of the inputs: bit level, byte level, and
packet level. At bit level, with the
oversampling of eight, an average of
the three middle samples is taken to
decide the bit value. Listing 1 shows
the interrupt routine that handles this
part. After a bit has been received, it is
shifted to the reception byte, and the

STX

TYPE

PTWD

CSI

SNS

SN1

SN0

QL

PTH

PTL

PT0

CRC1

CRC0

ETX

Mnemonic Value Description

STX

0×02 Start of transmission

TYPE

0×53 Packet type is punch data

PTWD

Punching time TWD value

CSI

Control station identifer

SNS

Start number series byte/card number

SN1

Start number low byte/card number

SN0

Start number low byte/card number

QL

Queue length

PTH

Punching time value

PTL

Punching time value

PT0

Punching time value (0.05-s increments)

CRC1

Cyclic redundancy check

CRC0

Cyclic redundancy check

ETX

End of transmission

0×03

SPORTIDENT PACKET FORMAT

The Sportident units communicate

over an asynchronous serial interface
at 4800-bps 8N1 data (i.e., 8 bits, no
parity, 1 stop bit, using RS-232 levels).
All of the commands and data use a
packet-based protocol that is framed
with start-of-transmission (STX or
0x02) and end-of-transmission (ETX or
0x03) characters. To separate the STX
and ETX from the data, all of the pay-

Figure s1—

The Sportident

packets use a straightforward
format with start, end, and
escape characters. The packets
also use a CRC to find trans-
mission errors, but that is
ignored in the concentrator box
and passed on to the receiver.

load characters below 0x20 must be
escaped using the delimiter (DLE or
0x10) character (see Figure s1).

In a punching packet, the packet-type

identifier is always 0x53. The other
fields identify the punching unit, the
card used, and the punching time.
Thus, the packets can vary from 14 (i.e.,
no DLE characters needed) to 25 bytes
(i.e., all 11 non-fixed bytes need DLE).

Photo 1—

As you study the innards of the concentrator

box, note the surface-mounted processor and MAX232
line driver. We used photoetching for the homemade
PCBs. They have nice sharpness.

Photo 2—

What do you think of the finished concentrator

box? The five D-SUB connectors are for the RS-232 connec-
tions. The two black 4-mm lab connectors on the side are for
the polarity-independent current loop. The current loop receiv-
er is housed in the small aluminum casing on the right.

background image
background image

28

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

byte-level status is checked. If the newly
shifted bit is the last bit, the byte is put
in the packet buffer that corresponds to
the input channel. Then, the packet sta-
tus is checked. If the newly received byte
is the ETX, a complete packet has been
received, and the packet is put in the
transmit queue. The input that uses the
hardware UART only implements the
packet-level status handling.

For each input there is one dedicated

packet buffer. This can lead to problems
if another packet is received before
the previous one has been transmit-
ted. That can never occur because the
minimum interval between two consec-
utive packets on one input is 500 ms,
and the maximum time to empty all
four buffers is the time it takes to send
four packets with, at most, 25 bytes that
each consume 10-bit times at 4800 bps.
This time turned out to be roughly
210 ms. We were home free.

The packet buffers are only 14 bytes

long because the STX and ETX do not
need to be stored. Instead of being stored,
the DLEs are added during transmission
whenever a data byte has a value of less
than 0x20. A common code snippet han-
dles the packet processing for all inputs.
The packet status and pointers used as
parameters to the function are copied to
specific registers before it is called. They
are saved after the function returns.

The packet status is a state machine

with three states: “Wait for STX,”
“Receive,” and “Last was DLE.” At
start-up, the concentrator box status is
Wait for STX. When the STX byte is
received, the status changes to Receive.
In this status, the bytes are received and
stored in the packet buffer. For each
byte, the packet pointer is increased by
one. If a DLE (0x10) is received, the sta-
tus changes to Last was DLE, and the
DLE is not stored in the packet buffer.
When a byte is received in Last was
DLE, it is stored in the packet buffer
and the status is changed to Receive. If
an ETX is received in Receive, the pack-
et is placed in the transmit queue and
the status is changed to Wait for STX. If
the transmit queue is empty, the STX
byte is sent directly, and the interrupt
for UART transmission register empty
wakes up the transmission procedure.

Likewise, the transmission procedure

has a status, which keeps track of when

a DLE has been sent and a whole pack-
et has been transmitted. After sending
the ETX after the last data byte of the
packet, the transmission procedure
checks if there are any more packets in
the transmit queue. If there are, an STX
is sent and the first packet in the queue
is transmitted. If the queue is empty,
the transmission procedure finishes

and won’t execute again until there is
an interrupt from the UART, which is
triggered after a new STX byte is sent.

TESTING PROCESS

For our first test, we had connected

a couple of Sportident punching units
to the concentrator box and moni-
tored the output on a PC. The initial

Listing 1—

The core part of the software receiver runs periodically based on a timer interrupt. This code

snippet is called for each of the three software receivers; it uses eight times oversampling together with an
average of over three samples to decide the value of each incoming bit.

i_handlebit:

cpi tmp, 0x00

;Check if status is waiting for

;start bit

breq i_handlebit_waitstart

inc tmp

sbrs tmp, 2

;Check if count[2..0] in 4..7

ret

;Return if not 4..7

mov i_tmp, tmp

;Check that count[2..0] != 7

ori i_tmp, 0xF8

com i_tmp

brbc 1, i_handlebit_skip1

;Zero flag

ret

;Return if seven

i_handlebit_skip1:

;The bit should be sampled

tst XH

;Add inverted input

brbc 1, i_handlebit_skip2

;Zero flag

inc YH

;Increase YH

i_handlebit_skip2:

sbrs tmp, 1

;Check count(2..0) = 6

ret

;Return if count in 4..5

clc

;Clear carry

sbrc YH, 1

;Check bit 1 in YH

//Sum of three samples is two or three

sec

;Set carry

ror in_buffer

;Rotate right, shift new bit

;into buffer

clr YH

;Clear the bit counter

cpi tmp, 0x06

;Check count = 6

breq i_handlebit_startbit

sbrs tmp, 6

;Check count = 70

ret

;Return if less than 8 bits have

;been received

cpi tmp, 0x4E

;Check if stop bit arrives

breq i_recvloop_stopbit

mov i_tmp, in_buffer

;A new byte is in in_buffer,

;move to i_tmp

clr XH

rcall i_packet_update

;Call i_packet_update

ret

i_recvloop_stopbit:

;Receive stop bit

clr tmp

ret

i_handlebit_startbit:

;Check that the start bit was

;correct

sbrs in_buffer, 7

ret

clr tmp

;If not, clear the status

ret

i_handlebit_waitstart:

;Check the input for beginning

;of startbit

tst XH

;Check if input = 1 (startbit!)

brbs 1, i_handlebit_skip3

;Zero flag

ldi tmp, 2

;Set status that startbit has

;arrived

i_handlebit_skip3:

ret

background image
background image

30

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

PROJECT FILES

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

SOURCES

AT90S2313 Microcontroller
Atmel Corp.
(408) 441-0311
www.atmel.com

LM2931 Voltage regulator
National Semiconductor Corp.
(800) 272-9959
www.national.com

Punching unit
Sportident International
+46 (0) 8 654 71 40
www.sportident.se

Daniel Wiklund holds an M.S. in
Electronics Engineering. He’s current-
ly studying toward a Ph.D. in
Computer Engineering at Linköping
University, Sweden. His technical
interests include digital systems and
architectures for on-chip communica-
tion. He enjoys working on small elec-
tronics projects in his spare time. You
may reach Daniel at danwi@isy.liu.se.

tests looked promising, and we con-
cluded that the system could be tested
in a real-world situation.

For the real-world simulation, we took

the boxes to an orienteering clubhouse,
where a small indoor competition with
plenty of punching was taking place. We
initially believed the test would be a
breeze, particularly because we, like
most programmers, always write bug-
free code! But the process went badly.
When two punches were made simulta-
neously, one of them was sent twice and

the other one wasn’t transmitted. In
addition, the punching data was offset,
so the initial byte was missing.

It turned out that there was a bug in

the code: a pointer was not incremented
in the case of two concurrent punches.
After correcting the problem, we restart-
ed the session. Everything worked per-
fectly the second time around.

GREAT RESULTS

All in all, we built four concentra-

tor boxes and two receivers, which

worked like a charm at a competition
where they were used to generate
results and split times (see Photos 1
and 2). The live commentary was
streamed over the Internet so specta-
tors all over the world had the oppor-
tunity to follow the live action.

Some of our fellow orienteerers have

shown interest in our concentrator
boxes and are considering using them
in competitions of their own. We antic-
ipate that the concentrator boxes will
soon have the ability to report the splits
from the control posts in the forest via
GPRS cell phones and the Internet.

I

Tomas Henriksson earned an M.S. in
Computer Science and Engineering as
well as a Ph.D. in Computer
Engineering at Linkopings University,
Sweden. He is currently a research
scientist at Philips Research,
Eindhoven, Netherlands. Tomas is an
active orienteer and is involved with
computer support for his club. You
may contact him at tomhe@isy.liu.se.

background image
background image

32

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

T

he nine-band audio spectrum

sound analyzer was my first microcon-
troller-based project. I built the ana-
lyzer when I was in school studying
for a Master’s degree. Recently, I went
back to make improvements. In this arti-
cle, I’ll describe my audio spectrum ana-
lyzer’s design. I hope you enjoy reading
about it as much as I enjoyed building it.

NONTRADITIONAL APPROACH

Digital signal processing requires spe-

cialized processors capable of multiplica-
tion within one machine cycle. The mul-
tiplication of numbers is the main opera-
tion in the digital filters. Controllers
without hardware multipliers use soft-
ware library funcitons, which are slower.

I chose the Atmel AT90S2313 for

this project because it’s specified to

tret microphone. When the LEDs move
to the opposite side, a clock is displayed
as an additional function. If you’re inter-
ested in learning more about mechani-
cally scanned LED clocks, visit Bob
Blick’s web site (www.bobblick.com).

Despite the problems with this

method, there are significant advan-
tages. Basically, it resolves the prob-
lem every engineer deals with when
using one-chip computers: the con-
troller’s limited number of I/O pins.

DESIGN BASICS

As you can see in Figure 1, all of the

I/O pins are used. Sound enters the
electret microphone (M1) and is con-
verted into an electric signal. Then, it
passes through the two coupling
capacitors C15 and C17 to the input of

Audio Spectrum Analyzer with a Twist

FEATURE ARTICLE

by Veselin Koev

Veselin has developed a nontraditional approach to building a digital nine-band audio ana-
lyzer. This month, he shows you how to use an AT90S2313 to build one for yourself.

deliver up to 10 MIPS at 10 MHz. The
Atmel datasheet states that it has
been tested up to 15 MHz, and even
this seems to be far from its upper
limit. It seemed enticing, so I decided
to use the microcontroller.

Optimizing the program code, choos-

ing appropriate algorithms, and actual-
ly putting the pieces together were the
most difficult steps in the process of
building the audio spectrum analyzer. I
chose to take a nontraditional approach
by mounting the device’s circuit
board on the axle of an electric motor.

I arranged eight LEDs on the circuit

board. When the board spins, the LEDs
paint an image of the spectrum, and
they turn quickly enough to make the
generated image look like it’s hanging
in midair. Sound is received via an elec-

Figure 1—

Use my audio spectrum analyzer’s schematic as a guide for your own project.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

33

fasten the board and graphite brush.

The insulating washer and positive

contact should be tight as well. The for-
mer is fitted between the circuit board
and the negative contact. I placed the
same type of washer between the electric
motor and the graphite brush, because
I used a small PCB for the prototype.

The infrared LED D1 is situated on

the same PCB; therefore, the rotating
circuit board’s controller receives the
signal at the start of every revolution.
When you stand in front of the device
and look at it, the infrared LED should
be on the left, and the circuit board
should be revolving counterclockwise.
If the board is revolving clockwise, an
upside-down image will appear.

It’s important that the spinning cir-

cuit board is balanced properly. After
mounting all of the components on the
circuit board, place it carefully on the
tip of a knife. The point of the knife
should be inserted in the hole intended
for the electric motor shaft. Determine
which part of the board is lighter and
then add ballast. You can use a hot
glue gun as the ballast, but it should be
applied only to the rear side of the cir-
cuit board. This will prevent you from
spoiling the device’s appearance when
it’s shut off. If you don’t have proper
balance, the rotating circuit board will
vibrate, which could modulate the
supply voltage on the circuit board
because of the varying resistance of the
graphite brush. You’ll get poor results
in terms of the spectrum display and
the stable operation of the device.

the preamplifier (transistor Q2 and
the components around it). From the
preamplifier’s output, the signal is
delivered to the positive input of the
microcontroller’s analog comparator.

The analog comparator, along with its

external components C10 and R12–R14,
and the microcontroller’s on-chip hard-
ware timer are used to implement an
A/D converter. The firmware periodical-
ly drives pin PB1/AIN1 low to discharge
C10, and then releases it to create a ris-
ing ramp voltage. The ramp follows an
exponential curve, but the initial part
is linear enough for this purpose. The
timer is used to measure the interval
between the start of the ramp and the
moment it crosses the voltage from the
preamplifier, giving a number that’s pro-
portional to the audio input voltage.

The last operation is performed by the

analog comparator’s ISR. The elements
R13 and R14 set the DC offset voltage at
the positive input of the comparator. It
should be set to half the peak value of
the ramp voltage at the negative input.
You can increase the sensitivity of the
A/D conversion by replacing capacitor

C10 with a larger one. At the same time,
you should recalculate resistor R13’s
new value so that the DC offset at pin
12 is 40% higher than the DC voltage at
pin 13 of the microcontroller. (This is
half of the new peak ramp value.)

The controller’s PWM output

(OC1/PB3) is used for automatic level
control. With this output, the con-

troller operates transistor Q3, which is
used as a regulated resistance and
decreases the signal coming from the
microphone. Thus, there is no danger
of overloading the spectrum analyzer.

In order to synchronize the image,

the controller uses the signal coming
from phototransistor Q1. The con-
troller is informed of every new revo-
lution and the speed of the rotation.

The driver chip, a ULN2803A, is an

octal buffer with TTL-compatible inputs
and open-collector outputs that can sink
500 mA. This allows the LEDs to be
driven with considerably more current
than the pins of the micro can handle,
increasing the brightness of the display.

Regulator U3, a 78L05, stabilizes the

processor’s supply. R19, C14 and C16
provide additional filtering for the
analog circuitry. Switch S1 allows you
to stop the rotation of the propeller so
that you can set the clock with buttons
S2, S3, and S4 (hours, tens of minutes,
and minutes, respectively).

You also need a small direct-current

electric motor. The diameter of the axle
should be at least 3 or 4 mm. The speed
of rotation should be about 1500 rpm.
Speeds higher than this will cause the
circuit board to produce a whistling

sound. At lower speeds, the flickering
of the image will increase considerably.
The electric motor should be a quiet
one. In addition to creating an unpleas-
ant sound, a noisy motor will interfere
with the operation of the spectrum ana-
lyzer, limiting its dynamic range. The
circuit board should be tightly fitted
to the motor’s shaft; for this, you’ll
need a special mechanical part.

The board’s power supply can be

another problem. The negative supply
is delivered through the axle of the
electric motor. The positive supply is
connected through the small graphite
brush, which you can make from a
thin sheet of iron and a graphite pen-
cil. Figure 2 shows the best way to

Figure 2—

As you can see, I used a small PCB, an

insulating washer, and graphite from a pencil as a
brush. The copper contact is used for the positive sup-
ply, and the motor shaft is for the negative supply.

b0

b1

Z

–1

X(n)

X(n–1)

b0.X(n)

Σ

–a1

–a2

Z

–1

Z

–1

b1.X(n–1) –a1.Y(n–1)

–a2.Y(n–2)

Y(n)

Y(n–1)

Y(n–2)

b0

b1

Z

–1

X(n)

X(n–1)

b0.X(n)

Σ

–a1

–a2

Z

–1

b1.X(n–1)

–a1.Y(n–1)

–a2.Y(n–2)

Y(n)

Y(n–1)

Z

–1

–a2.Y(n–1)

Figure 3a—

You can refer to this diagram as you study

the second-order infinite impulse response (IIR) filter.

b—

Execute the multiplications with a1 and a2 at the

same time to cut the number of right-shift operations
in half.

a)

b)

Photo 1—

The numbers seem to be floating in midair.

This display is typical for a 1-kHz tone.

background image

34

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

CONTROLLER OPERATION

When I started this project, I wasn’t

sure about the exact number of spec-
trum bands to use or their center fre-
quencies. After briefly examining the
literature, I became convinced that
the FFT would be a slow and unac-
ceptable option. [1, 2]

The frequency bins of an FFT are

equal-sized, but an audio spectrum ana-
lyzer requires a logarithmic display,
where octaves occupy equal spaces. In
order to achieve adequate resolution

at low freqeuncies, a high-order FFT
would be required. In addition, it is
necessary to use a windowing function

on the input data in order to get good
results with an FFT. It just isn’t possible
to do this without a hardware multipli-
er and more RAM than the ‘2313 has.

The most acceptable option is to

use second-order recursive filters in
which all multiplications are by con-
stants. This creates many opportuni-
ties for optimizing the program code
for speed. Figure 3a depicts the block
diagram for such a filter. The frequen-
cies of the filters are easily arranged at
equal intervals on a logarithmic scale,
making them compatible with the
perception of the human ear.

As you know, multiplication of

binary numbers is accomplished by a
sequence of shifts and additions. The
result is created as a sum of partial
products, each having the value of the
multiplicand shifted by an amount
corresponding to each set bit in the
multiplier. Figure 4a shows how the
multiplication of the binary numbers
011101 (the multiplier) and 0101 (the
multiplicand) is represented.

Some algorithms such as Booth’s

Algorithm can reduce the number of
arithmetic operations required to per-
form multiplication.[3] The algorithm
optimizes operation when long succes-
sions of ones appear in the multiplier,
because it uses both addition and sub-
traction of powers of two. Figure 4b
depicts another way the multiplier
can be represented.

In this example, the number of arith-

metic operations is decreased by one.
The other approach I used to optimize
the program was to find and remove any
repeated calculations made during the
calculation of the filter outputs (see
Figure 3b). The operations are remem-
bered, and the coefficients used in the
reiterated operations are simply
exchanged. This works because the block
diagram’s links are arranged sequentially.

Let’s have a look what you gain from

this exchange. Multiplication by the two
coefficients a1 and a2 is performed at the
same time on a single value of Y(n – 1).
Thus, parallel operations are possible,
because the bits of the input value
will be logically shifted only once to
create both results. The number of
shifting operations saved is equal to the
number of bits in the shorter multiplier.

This method of improving the per-

0101 = 0101 x 1

0101 = 0101 x 100

0101 = 0101 x 1000

+ 0101 = 0101 x 10000

10010001

011101 = 100000 – 000010 – 000001 (bin)

Figure 4a—

This is a representation of the multiplica-

tion algorithm.

b—

The multiplier can be represented

this way, too.

a)

b)

Join the conversation.

Give your programmable instruments the command language of
choice, supported by major manufacturers and familiar to customers.

Talk the language. Talk SCPI with JPA-SCPI Parser.

The SCPI command language presents your
instruments with a familiar and professional
programming interface, reducing support
needs and reinforcing your position as a truly
proficient manufacturer.

In the past, the power and flexibility of the
SCPI language meant employing a consultant
or spending days and weeks writing an inter-
preter in-house. Not any more.

Using JPA-SCPI Parser, your own developers
are empowered to build a full SCPI interpreter
for your instruments quickly, easily and at
very low cost.

More than just a source code library, JPA-SCPI
Parser is a complete software toolkit to give
you SCPI capability in the shortest time.

Take a look at some of the highlights

x

Suitable for any peripheral interface
e.g. GPIB, RS232, USB etc.

x

Works on almost any processor/platform

x

Minimal ROM & RAM requirements

x

Written in C, fully ANSI/ISO compliant

x

NO ROYALTIES / RUNTIME FEES

x

Fully compliant to current SCPI standard

What’s

Included

x

C source code comprising the parser itself
and access functions

x

Template command sets for 10 common
types of instrument

x

Base template suitable for all instruments

x

Example source code

x

Comprehensive user manual to take you
through each stage to your SCPI parser

x

Design notes manual

x

Unlimited royalty-free runtime licenses

x

Free technical support and product
upgrades for 1 year





Pricing

Single-brand site license, allowing use of
JPA-SCPI Parser for an unlimited number
of your company’s instruments: $495

A multi-brand site license is available for
consultancy houses:

$2475

JPA Consulting

accelerating product development

Try JPA-SCPI Parser today.

Download our demo application to see

for yourself just what it can do.

Available from our website.

For full details or to purchase, visit

www.jpacsoft.com

background image
background image

36

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

formance of the recursive infinite
impulse response (IIR) and nonrecur-
sive finite impulse response (FIR) fil-
ters can be used for higher-order fil-
ters as well. Keep in mind that you will
need two memory blocks for a third-
order filter, because of the recursive part
of the filter. However, there will be one
third as many logic-shifting operations.

Unlike its analog counterpart, the sig-

nal frequency of a digital filter is limited
at its upper end to half the sample fre-
quency. This frequency corresponds to

infinite frequency for an analog fil-
ter. In this project, I want all of the
analysis filters to have the same
gain (coefficient of amplification,
K) at f

s

/2 as that of the analog

bandpass filter designed for the
same frequency. Other filters, such
as high-pass filters with resonance
in the passband, are ideal for this
purpose. It’s easy to design these
second-order filters, because the
dual-complex root in the denomi-
nator of the transfer function of

the filter is related directly to the
filter’s cutoff freqeuncy and the

resonance in the passband. It also direct-
ly relates to the cutoff slope and the
amount of resonance in the frequency
passband for the corresponding analog
filter. Figure 5 shows the connection
between the coefficients and their
complex roots (rows 3 and 4).

To calculate the value of the other

coefficient, you can use a successive
approximation technique, because it
may be necessary to relax the con-
straints on selecting the upper and lower
cutoff frequencies of the bandpass filters.

Photo 1 shows the response of the

spectrum analyzer to a 1-kHz tone.
Note that all of the pictures for this
article were taken with a digital cam-
era. Regarding this photo in particu-
lar, all of my efforts to take the picture
with an ordinary camera failed because
of the clicking of the shutter, which
showed up in the spectrum display.

I chose to make the audio level step

size between adjacent LEDs 2 dB, which
makes the analyzer’s full dynamic range

+3

0

–3
–6
–9

–12
–15
–18
–21
–24
–27
–30

10

100

1K

10K 16K

Filter before decimation
Filter after decimation

Decimation filter D8

f, Hz

K, dB

Figure 6—

The filter frequency responses shown here

include only the digital calculations. The frequency

response of the analog circuitry is ignored.

Figure 5—

Use these equations for the connection between the

coefficients and their complex roots.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

37

14 dB. I selected small steps to make
the display of music more dynamic.

If the filters had the same passband

width and center frequencies arranged
at equal intervals, their a2 coefficients
would be identical, which could save
multiplication operations. But then
the filters wouldn’t be arranged loga-
rithmically along the frequency axis
the way you want.

With a logarithmic arrangement of

the filter frequencies, the filters at
lower frequencies have narrower band-
widths, which means that the coeffi-
cients for the recusive parts of the fil-
ters must be larger, and that wider
variables must be used for the filter
calculations in order to avoid overflow.

The solution is to use decimation.

By using 8× decimation, the input
sample rate for the filters intended for
the lower part of the sound range is
reduced by a factor of eight. After the
decimation, the filters are calculated at
one-eighth the clock frequency, and the
size of the coefficients for the lowest
frequency is reduced (see Listing 1).

If you’re wondering about the loca-

Listing 1—

Two parallel multiplications create the recursive part of the IIR filter in Figure 3b.

F2KA2: ;2 clocks,input: y13=y(n-1);SUM=x(n)–x(n–1);y23=a2*y(n–2)

sub16 SUMh,SUMl,y23h,y23l ;SUM=SUM–y23=SUM–a2*y(n–2)

F2KA1: ;24 clocks

add16 SUMh,SUMl,y13h,y13l ;Add y(n)*1

asr y13h

;a1=–1,10011(bin)

ror y13l

;a2=0,10111(bin)=0,1+0,01–0,00001

add16 SUMh,SUMl,y13h,y13l ;Add y(n)*0.1 multiply by a1

mov y23h,y13h

;Add y(n)*0.1 multiply by a2

mov y23l,y13l

asr y13h

ror y13l

add16 y23h,y23l,y13h,y13l ;Add y(n)*0,01

asr y13h

ror y13l

asr y13h

ror y13l

add16 SUMh,SUMl,y13h,y13l ;Add y(n)*0,0001

asr y13h

ror y13l

sub16y 23h,y23l,y13h,y13l ;Subtract y(n)*0,00001

add16 SUMh,SUMl,y13h,y13l ;Add y(n)*0,00001

mov y13l, SUMl

;9/10 clocks

mov y13h, SUMh

;Peak detect

ldd temp0,y+peac3

cp temp0, SUMh

brge great3

mov temp0, SUMh

great3:std y+peac3,temp0

background image

38

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

tion of the nonrecursive portion of
the filter, don’t worry—I used coeffi-
cients b0 = 1 and b1 = –1 for all the
filters. In addition, in order to balance
the gains of all the filters, I multi-
plied each detected peak by a scaling
factor immediately before displaying
the result. These multiplications are
not performed at the audio sample
rate, but only once per revolution.
This reduces the computational load
on the processor.

All of this makes it possible to real-

ize the audio spectrum analyzer with
the AT90S2313 microcontroller. The
filters are arranged in octaves with
center frequencies of 63 Hz, 125 Hz,
250 Hz, 500 Hz, 1 kHz, 2 kHz, 4 kHz,
8 kHz, and 16 kHz. The individual
frequency responses are shown in
Figure 6.

The 125-, 250-, and 500-Hz filters

are identical to those at 1, 2, and
4 kHz. The 1-kHz filter and decimat-
ing filter D8 use the same recursive
part (with two multiplications less).
The filters at 63 Hz, 125 Hz, 1 kHz,
and the decimating filter are 24-bit
filters, while the 16-kHz filter uses
8 bits and all of the others use 16 bits.

In the process of writing the program,

I planned that the processor should
work at 12 MHz (see Figure 7).
However, this made the PWM output
frequency different from the audio sam-
ple rate. This created a constant noise
floor in the spectrum indication. When
I changed the CPU clock frequency to
16 MHz, that problem was avoided
because the PWM rate coincided with
the audio sample rate. In fact, they now
share a single hardware timer.

Although the program operated

correctly at 12 MHz, changing to
16 MHz presented new opportunities
for development, such as increasing
the number of analyzed frequency
bands. The interrupt service routine
for Timer1 calculates all filters and
makes one A/D conversion at the
same time. It requires about
330 machine clocks, including enter-
ing and coming out of the interrupt. It
also enables the processing of the ana-
log comparator interrupt, which is
part of the A/D conversion process.
The timer interrupts occur every
510 clocks. The development of

additional filters is limited to one or
two more because of the lack of
memory. When you decide to build
the device, you should look for new
versions of the software on my web
site (vkoev.tripod.com).

I used the wavrasm 1.30 assembler to

assemble the program. It’s free on the
Atmel web site. Also, you can use Jerry
Meng’s FBPRG v1.1 programmer operat-
ing under DOS for the PC’s parallel port,
which is also powered from the same
port (see Photo 2). To see the schematic
diagram of the programmer hardware,
start the software (FBPRG.EXE) and
press “L” on the keyboard.

CLOCK ACCURACY

Once upon a time, I used an elec-

tronic clock that used the 50-Hz fre-
quency of the power mains as its time
base. It was a nice idea, and would
have probably worked well in some
countries. But here, when I built the

project, the power was interrupted
every 10 min. for 24 h, which was irritat-
ing, and I couldn’t do a thing about it.
Even now, things are nearly the same.

In this project, I used a 16-MHz

quartz resonator (Y1) as the time base.
After running the project, I found that
the clock was off by more than 2 min.
per day! Now, you can assume that
whatever the frequency of your
quartz resonator, it is definitely sta-
ble. Therefore, I would like to offer
you an iterative formula with which
you can correct the number of audio
samples used to count off a minute.
With calibration, you should be able
to achieve an accuracy of better than
1 s per two months. You have to
apply the formula several times,
make smaller changes on each itera-
tion, and record the error for a longer
period of time.

The second time around, I achieved

better than 1 s per week. I was satis-
fied with that and didn’t attempt to
continue my work. The formula con-
tains the variable E, which is the error
in seconds per day. It is negative if the
clock is late and positive if it’s fast. To
make the correction, you’ll need an
assembler.

Take the old minute value and

make the calculation according to the

Start
ADC

get old

ADC

value

2–

16 KHz

(nonrecursiv

e par

t)

Filter 1 KHz, D8

(recursiv

e par

t)

1 KHz

(nonrecursiv

e par

t)

D8

(nonrecursiv

e par

t)

250 Hz

(recursive part)

125 Hz

(recursive part)

125 Hz

(continue)

125 Hz (continue)

63 Hz (recursive

part)

63 Hz

(continue)

500 Hz

(recursive part)

63 Hz

(continue)

63–500 Hz

(nonrecursive

parts)

16 KHz

(recursiv

e par

t)

8 KHz

(recursiv

e par

t)

4 KHz

(recursiv

e par

t)

2 KHz

(recursiv

e par

t)

End

ADC

save new

ADC

value

S1

100 Clock cycles

50 Clock cycles

170 Clock cyeles

Figure 7—

Time flows from left to right. Add 10 clock cycles for an A/D conversion executed at the same time. This

flow chart for the digital filters is executed 32,000 times per second, which yields a maximum of 375 clocks avail-
able for each pass at 12 MHz.

Photo 2—

You can use Jerry Meng’s FBPRG V. 1.1 to

program your microcontroller.

background image

MOTOROLA

and

the

Stylized

M

Logo

are

registered

in

the

U.S.

Patent

and

Trademark

Office.

All

other

product

or

service

names

are

the

property

of

their

res

pective

owners.

©

Motorola,

Inc.

2003.

This

product

incorporates

SuperFlash®

technology

licensed

from

SST

.

DURACELL

and

the

colors

copper

and

black

as

applied

to

a

battery

are

registered

trademarks

of

The

Gillette

Company

and

are

used

with

its

permission.

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

2

C

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

• MC9S08GB60 demonstration board

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

small prototype area, and demonstration code

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

free CodeWarrior

®

Development Suite for HC(S)08 Special Edition

through DB9 serial port and included cable

MC9S08GB & GT FAMILY KEY FEATURES

NOW AN 8-BIT MCU THAT’S

BIG ON PERFORMANCE,

LONG ON BATTERY LIFE.

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

MCUs with new additions that operate down to

1.8 V – without sacrificing performance one

bit. Taking advantage of multiple power

management modes – a 20 nA power-down

mode and auto wake-up timer mode – the new

HCS08 MCUs are designed to get the most out of any

battery. They also come with innovative on-chip trigger

and buffer debug hardware, and can be combined

with Processor Expert

TM

auto-code generator. All

that with performance as fast as 50 ns minimum

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

your time to market, because the HCS08 family is

compatible with all Motorola

analog and sensor products.

Big-time performance and

longer battery life – our HCS08

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

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

HCS08 Developer Kit

HCSO8 EXTENDS BATTERY LIFE

background image

Photo 3—

What do you think of the finished product?

Now it’s time for you to start your own.

40

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

PROJECT FILES

To download the code, parts list,
additional clock precision informa-
tion, and the PCB diagram, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2003/158/.

REFERENCES

[1] B. Boyanov and E. Todorov,

“Digital Signal Processing,” Color
Print

, 2000.

[2] O. Zelezov, “Computer Processing

of Signals and Images,” TU Varna,
1994.

[3] A. Lakurski, “Digital Electronic

Computing Machines,” Technica,
1989.

RESOURCES

Booth Multiplication Algorithm
Information, www.cc.gatech.edu/
classes/cs3760b_99_winter/
lectures/lecture5.pdf

S. Smith, “The Scientist and
Engineer’s Guide to Digital Signal
Processing,” California Technical
Publishing, 1997,
www.dspguide.com.

SOURCES

AT90S2313 Microcontroller,
wavrasm 1.30
Atmel Corp.
www.atmel.com

Atmel AVR MCU ISP programmer
Jerry Meng
www.qsl.net/ba1fb/

following formula:

The minute values appear in decimal
form. Put the minute value calculated
here back in the program file (down-
load A16cp.asm from the Circuit
Cellar

ftp site) as the new value. Then,

assemble the file, program the con-
troller, and remeasure the error. You
should use the minute value that you
programmed most recently each time

minute (new) = 1 +

minute (old)

E

86 400

,



 ×

you calculate a new minute value.

Photo 3 shows the front of the fin-

ished product. I enjoyed updating my
original design to build the nine-band
audio spectrum sound analyzer. Now,
you have the tools to build your own.

I

Veselin Koev earned a Master’s degree
in Communications Engineering from
the Technical University of Varna,
Bulgaria. Currently, he’s working in a
machine-building plant in Jambol. You
may reach him at koev_v@yahoo.com.

background image
background image

Accumulate and Hold controls.
Moreover, a set of analog and digital
auxiliary inputs allow you to display
configurable information on the
screen such as center frequency, refer-
ence level, scan time, and so on (see
Figure 1). Lastly, an RS-232 port
dumps hard copies of the screen to a
host computer.

As you can see in Figure 2, the XY-

Plotter’s overall architecture is sim-
plistic: it contains nothing more than
a PIC18F252, a few MCP6022 analog
amplifiers, a low-cost LCD, and sever-
al other low-cost components. I built
an integrated power supply using a
MCP1541 precision voltage reference.

LCD TIMING REQUIREMENTS

I used an FTN reflective Epson

ECM-A0635-2 LCD with a 240 ×
320 pixel black and white screen (see
Figure 3). The display is extremely
dumb, and it should be supplied in
real time with the required pixels.
The host controller must send a new
frame every 15 ms. Each frame
includes 240 lines, and each line
includes 320 pixels grouped into 4-bit
nibbles.

In addition to the 4-bit data input

port, the controller must also supply
three clocks: frame, line, and nibble.
One new nibble must be delivered
every 780 ns, which I arrived at via the
following equation: 15 ms/240/(320/4).
Note that for this project I used the
display turned by 90° in Portrait mode

42

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

I

mplementing a graphical LCD is an

excellent way to drastically change
the look and feel of a project. You can
transition from a classic technician-
oriented, two-lined text LCD to a
user-friendlier device. Unfortunately,
graphic LCDs are resource-hungry
devices, both in terms of memory and
CPU power. So, you’re forced to
either create lovely minimalist
designs with an intelligent LCD (with
on-board LCD controller, processor,
and memory, as described by Jeff
Bachiochi in Circuit Cellar 150) or
swap the usual microcontroller for a
classic microprocessor, memory, dis-
play controller set.

Both options are expensive, and

there doesn’t seem to be another solu-
tion. For instance, the 240 × 320 pixel
display used in this project eats one 4-
bit nibble every 780 ns, and it needs a
minimum of 10 KB of RAM just to
store the displayed bitmap. Thus, it’s

The XY-Plotter

Robert spent nearly 100 hours building his high-performance, LCD-based XY-Plotter. Now
that he has written about the process, it should take you much less time to construct your
own. Follow along as he shows you how to maximize your time and money when driving
graphic LCD panels.

impossible to drive it directly with a
high-end PIC controller providing a
100-ns cycle when clocked at 40 MHz
and 1536 bytes of RAM, right?
Nothing useful can be done in less
than seven assembly instructions per
nibble, correct?

As you probably expect, this project

proves that the impossible is possible
with an optimized firmware design.
You’ll even learn that it’s possible to
use this minimalist concept for some-
thing useful!

PLOTTER BASICS

I got the idea for the XY-Plotter from

an old spectrum analyzer sleeping in
my garage. Despite the fact that the
heavy analyzer’s CRT display was dead,
the radio parts worked well. So, from
time to time, I used it with an oscillo-
scope as an output device. The arrange-
ment was cumbersome and uncomfort-
able to implement. Consequently, I
decided to repackage the analyzer in a
smaller, prettier enclosure and design
an LCD alternative to the CRT dis-
play. Because I wanted the ability to
reuse the design, I chose to develop a
generic display subsystem, the XY-
Plotter (see Photo 1).

The XY-Plotter is an autonomous

analog-like display with two main x
and y inputs. Continuously scanning
the two inputs, the plotter displays
them on a real-time x-y graph by way
of configurable modes (i.e., Sample,
Maximum, Peaks, or Average) with

FEATURE ARTICLE

by Robert Lacoste

CONTEST WINNER

Drive High-Resolution LCDs For Less

Photo 1—

The large 240 × 320 LCD is affixed to the

PCB. The three control push buttons and the screen
dump RS-232 connector are along the bottom edge.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

43

PIC or multiplexed with LCD data
lines (thanks to a firmware reconfigu-
ration on the fly).

Lastly, the ubiquitous MAX232 does

what it’s intended to do. It should be
noted that I included an in-circuit pro-
gramming header just in case; howev-
er, I haven’t had to use it thanks to
Microchip’s boot loader firmware. All
of the programming was accomplished
though the serial port.

POWER SUPPLIES

The power supply is a significant

part of the design (see Figure 5). First, I
needed a clean 5 V. I was already
using all of the PIC’s analog inputs,
so I couldn’t configure its ADC in
external-reference mode. I still need-
ed a stable reference for the analog-
to-digital conversions. After experi-
encing a few headaches, I decided to
use the PIC in its 0- to 5-V reference
mode and to provide a well-stabilized
5 V. I implemented a high-precision
MCP1541 voltage reference and built
a discrete power supply around a
low-drift LMC6462 op-amp. The sec-
ond part of the op-amp is used to get
the 0.6-V reference drawn on by the
offset circuitry.

The LCD was hard to deal with

because it needed both a –24-VDC
input (for the display itself) and a 100-
VAC power for the EL backlight. To
limit the number of power inputs, I
went with a small 5- to

±12-VDC con-

rail-to-rail op-amp. Two 20-turn trim-
mers per input give you the ability to
easily adjust the full-scale deviation as
well as the DC offset for each channel.
One of the channels, AUX2, even
includes two inputs summed by the
analog amplifier.

The values of the resistors used for

each amplifier stage can be adjusted
for each specific application to accom-
modate different input ranges and
adjustment precision. It is not obvious
how to design an amplifier stage with
positive and negative offset adjust-
ment without a negative
power supply. Here’s my
trick: A fixed positive volt-
age, which is derived from a
0.6-V reference, is first sub-
tracted from the input signal,
and then a variable positive
voltage is added to it, provid-
ing an offset that’s either pos-
itive or negative. I used Excel
to calculate the resistors.

The PIC is clocked by a 10-

MHz crystal up-converted to
40 MHz thanks to the on-
board PLL. The LCD is
directly connected to the PIC
I/O lines, whereas the auxil-
iary digital inputs, which are
used to dynamically select
the text for the screen, are
either direct inputs of the

(320 pixels high, 240 wide), so the
scan lines are vertical.

MICRO OF CHOICE

I chose the PIC18F252 microcon-

troller on the basis of certain project-
specific criteria. First, I needed speed.
The more instructions in these bloody
780-ns nibbles the better. I also want-
ed a significant amount of RAM. I did-
n’t store the full bitmap but chose
instead to store minimum, maximum,
and sample values for each column
already requiring 768 bytes. In addi-
tion, I needed a precision A/D con-
verter and a large program memory for
amassing the huge tables used in the
design (including character bitmaps).
Lastly, flash memory was necessary
for configuring the display for each
application.

One or two years ago, these require-

ments probably would have been
impossible to fulfill, but, thanks to sup-
pliers like Microchip, they are now eas-
ily satisfied, with the PIC18Fxx2 prod-
uct line in particular. The PIC18F252,
for instance, has 1.5 KB of RAM and
plenty of flash memory (32 KB).

GRASPING THE SCHEMATICS

Figures 4 and 5 are schematics of

the XY-Plotter. Each analog input (X,
Y, AUX1, and AUX2) is conditioned
thanks to half of an MCP6022 dual

X

Y

AUX1

AUX2

2×MCP6022

DA1
DA2
DA3

DA4

PIC18F252

MAX232

240 × 320

LCD

Display mode

Accumulate

Hold

Figure 2—

The XY-Plotter’s hardware design is simple. The

PIC18F252 manages everything including LCD pixel generation in
real time. A couple of Microchip MCP6022 rail-to-rail op-amps were
used to scale the analog inputs.

F R E Q = 1 2 3 4

M H Z

R E F

=

– 9 6

D B M

S C A N

2 0 0

K / D

V E R

=

1 0

D B /

R E S L =

1

K H Z

P E A

C C

L T

T

D

K

A

F

H D

One of 16

fixed text strings,

depending

on digital inputs

DA1[0..3]

One of eight

fixed text strings,

depending

on digital inputs

DA2[0..2]

Current display

mode indicator

(Sample, Maximum,

Peaks, or Mean)

Immediate value of

analog input AUX1

Immediate value of

analog input AUX2

One of two fixed text strings,

depending on digital input DA3

One of

two fixed text

strings,

depending on

digital input DA4

Accumulate

mode indicator

Hold mode

indicator

Figure 1—

The XY-Plotter screen displays a real-time x-y graph as well as three lines of configurable textual status

information and real-time measurements.

background image

44

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

the overall architecture. In order to
comply with the requirement of seven
instructions per nibble, I didn’t use an

verter to generate the –24 V switched
by two transistors under PIC control. I
couldn’t find a ready-made DC/AC
converter for the backlight in time,
but it wasn’t an issue. I built a pretty
one with a small 220/12-V transformer
driven by a NE555 timer. Done.

PROTOTYPE ASSEMBLY

I built a simple PCB for this project

(see Photo 2). All the components fit
easily because I wanted the size of the
PCB to be identical to the LCD. Note
that the front panel components,
including the push buttons and RS-
232 connector, are soldered on the bot-
tom. All of the trimmers are easily
accessible with a screwdriver, because
they are laterally shifted from one to
the other.

FIRMWARE DESIGN

The hardware side of this project

was straightforward, so if you’re imag-
ing that the firmware was more diffi-
cult, you’re right. Figure 6 illustrates

interrupt. I built a fully sequential
program flow.

A main loop is executed every

Figure 4—

The XY-Plotter’s power supply isn’t included in this schematic. An MCP6022 analog amplifier, with scale and offset controls, scales each analog input. Some of the

microcontroller’s I/O lines are multiplexed to limit the I/O count requirement.

Y Dr

number 1

Di

Do

80

Y Dr

number 2

Di

Do

80

Y Dr

number 3

Di

Do

80

LCD pannel

240 × 320

AC pulse

generator

X

Dr

EI

EO

Number 1

X

Dr

EI

EO

Number 2

X

Dr

EI

EO

Number 3

X

Dr

EI

EO

Number 4

Contrast circuit

(FR)

80

80

80

80

VLCD

(V0)

LP XSCL D0~D3

*DISP OFF

DIN

VDD

VSS VEE

Figure 3—

The EPSON ECM-A0635-2 display doesn’t include anything more than lines, columns, registers, and

drivers. The host controller must send pixels with strict timing requirements and supply frame, as well as line and
pixel clock signals.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

45

15.8 ms. It starts with a
frame-batch routine that
manages the push buttons,
and more importantly reads
the auxiliary inputs (analog
and digital) and generates the
text that will be displayed in
the first lines. The text is
stored as ASCII characters in
RAM using 90 bytes (3 × 30).

If you want to study the

binary-to-decimal conversion
routine, which I found on
the ’Net, refer to the
Resources section at the end
of this article. The frame-
batch routine also manages
the UART by way of a sim-
ple protocol. Then a loop is
executed for each of the 240
columns in the display. At
each iteration, a line-batch
routine is first executed.
This routine reads and man-
ages the x and y analog values (storing
y

minimum, maximum, and sample

values for each x value in three 256-
byte RAM areas). The display blank-
ing (i.e., y is not stored when x is
reducing) is also managed.

The last step is tricky. For each line,

the firmware must generate the nibbles
to send the LCD on the fly. It must
first send the nibbles corresponding to
the graphic area (the back of the screen
depicted in Figure 1) and then the
ones for the three text lines at the top.
Now let’s discuss the details.

GRAPHIC DISPLAY

How can you generate the graphic

display on the fly? The fixed parts
(e.g., borders and scales) are easily sent
to the LCD with the proper timing.
The graph is built in real time from
the minimum, maximum, and sample
values. It also depends on the display
mode (see Figure 7).

The LCD is used in Vertical mode

(320 pixels high), so the scan is verti-
cal, too. Thus, the successive nibbles
sent to the LCD correspond to succes-
sive vertical blocks of four pixels. In

order to generate them, an
optimized algorithm is
implemented based on
another trick: For each col-
umn, there is only one
black line surrounded by
whites. First, the black
line’s two extremities
(ystart and ystop) are cal-
culated based on the oper-
ating mode. Then, a loop
sends an optimal number
of fully blank nibbles fol-
lowed by (depending on
the ystart and ystop val-
ues) precalculated bitmaps
that correspond to the dif-
ferent situation and are

stored in a precalculated
table as well as full black

or full white nibbles in good quantity.
For reasons of efficiency, the flash
memory-based table is cached at start-
up in a RAM page. Figure 8 provides
visual description of the algorithm.

TEXT DISPLAY

The three text lines are also gener-

ated on the fly based on the ASCII
characters that are stored in RAM. For
this purpose, a specific character
bitmap was precalculated and stored
in flash memory. The table gives the
successive nibbles to send to the dis-

Figure 5—

The power supply includes four independent subsystems, one of which is the main 5-V regulator, which I built using a

high-precision Microchip MCP1541 reference. I used a 5- to –24-V converter for the LCD. A homemade converter supplies the
backlight voltage (100-V AC). Lastly, note that a 0.6-V reference is provided for offset control.

YMAX

YSAMP

YMIN

Input

y

signal

for the same

value of

x

Sample Maximum Mean Peak

Display mode

Figure 7—

Four display modes are supported by the

XY-Plotter. Sample mode simply plots the first y value
acquired for each x value. The Maximum mode plots
the highest y for a given x. The Mean mode isn’t in fact
a true mean; it simply displays the midpoint of the mini-
mum and maximum values. Last but not least is Peak
mode, which displays a line showing all of the y values
measured for a given x.

Initializations

Main loop

Execute frame batch

(one time each 10 frames)

Read push buttons, manage Display mode
Read auxiliary inputs, update textual display in RAM
Manage UART

Lines loop

(executed 240 times)

Execute line batch

Sequentially read

x

and

y

through ADC

Store measurements, calculate min/max, manage
blanking

Display graphic area

(284 pixels, 71 nibbles to send)

Generate drawing on the fly based on Display
mode (peak, etc.)

Display text area

(3 × 12 pixels, nine nibbles to send)

Generate bitmap on the fly based on ASCII
characters in RAM

Ov

er

all refresh per

iod 15.8 ms

3 to 8 µs

25 to 30 µs

12 to 28 µs

240

×

65 µs

200 µs

Figure 6—

The most critical section of this chart, which shows the archi-

tecture and timing of the firmware, is the graphic display routine.
Basically, 71 nibbles must be sent in 30 µs, giving 422 ns per nibble or
four PIC instructions per nibble (even at 40 MHz).

background image

46

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

play for each character (from back to
top and from left to right). Each char-
acter is encoded in an 8 × 12 pixel
bitmap, giving 30 (240/8) characters
per line.

A significant overhead is needed at

the start of each character (first scan
line out of the eight) in order to pre-
calculate the different pointers. I built
this unusual character bitmap table in
Excel, starting with a standard 8 × 12
bitmap I found on the Internet.

LINE-BATCH ROUTINE

The line-batch routine manages

the acquisition of the x and y analog
values as well as the storage of the
minimum, maximum, and sample
values in RAM. I built the routine as
a five-stage step machine (see Figure
9). Each step corresponds to a differ-
ent acquisition sequence.

You can’t lose time with this

architecture. A full pair of x and y
values is acquired every 260 µs (4 ×
65µs), which produces a satisfactory
3.8-kHz update rate. Depending on
the scan rate you apply (i.e., the fre-
quency of the saw-tooth applied on
the x input), two modes are auto-

matically executed. If the scan rate
is lower than 15 Hz (3.8 kHz/256) or
the scan time is higher than 7 ms
per division (1/15 × 10) using the
usual scope vocabulary, then more
than one y value is acquired for each
x

value per scan, enabling function-

ality such as minimum, maximum,
and peaks.

If the scan speed is higher (up to

500 Hz), an equivalent time-sampled
display is generated, and minimum,
maximum, and peak measurements
are only available in Accumulate
mode (i.e., no resetting of the mini-
mum and maximum between scans).

OPTIMIZATION TIPS

Optimizing the firmware’s cycle

count requires a huge effort. For
instance, one of its basic tasks is to
send N pulses to the LCD’s nibble
clock input. A loop already needs
five cycles to do this, but remember
that you have time for less than
seven instructions per nibble, and
the firmware has more to do than
simply send clock pulses! So, you’ll
need additional optimization tech-
niques like code expansion and the
calculated

goto procedure (see

Listing 1).

I used the calculated

goto tech-

nique extensively. Basically, I was
manually unrolling the code like an
optimized compiler does (or tries to
do). For instance, I used a long calcu-
lated

goto table to select the specific

line-generation algorithm for each col-
umn in the display (e.g., graduations,
plain line, ordinary curve column,
etc.). The result is a strange assembly
listing to read but an interesting one
to write!

Another tip is to copy, at startup,

the combined pixel table from flash
memory and paste it in RAM. An indi-
rect access to RAM is quicker than a

table read from flash memory.

MEMORY REQUIREMENTS

The aforementioned firmware

optimizations are memory hungry.
Fortunately, with 32 KB of flash
memory it’s not an issue. My
firmware currently uses only 10 KB.

I used the PIC18F252’s entire

RAM. Three pages at 256 bytes each
were used to store the respective
minimum, maximum, and sampled
y

value for each x value. One page

was devoted to the storage of the
ASCII text, although only 90 bytes
were actually needed. One last 256-
byte page was used to store the

bitmap patterns. That left 256 bytes
for general-purpose variables. All in
all, that’s 1536 bytes.

Start = 10/Stop = 22

Finish the screen with full whites

Send one combined three black/one white nibble

Send two full black nibbles

Send one combined two white/two black nibble

Send two full white nibbles

Finish the screen with full whites

Send one double-combined
one white/two black/one white

Send three full white nibbles

Send one combined two
white/two black nibble

Start = 13/Stop = 14

Scan direction

Scan direction

Figure 8—

The 4-bit nibbles are generated in real time for each of the LCD’s scan lines based on the position of the

first and last black pixel on that column. The firmware first calculates how many 0000s must be sent, and then two
things can happen: If all the black pixels to draw are in the same nibble, then a combined white/black/white nibble
is extracted from a table and sent to the display (on the right). Otherwise, one white/black transition nibble is sent,
followed by the required number of full black nibbles, and followed by one black/white transition nibble (on the left).

Initial

0

1

2

3

4

Configure ADC for channel

x

Read

y

from ADC

Store

y

in array, indexed by last

x

read

Configure ADC for channel

x

Launch A/D conversion for channel

x

Read

x

from ADC

If > than previous

x

, reset Min/Max (

x

)

If < than previous

x,

then blanking mode

If not blanking mode, configure ADC for
channel

y

Launch A/D conversion for channel

y

Blanking

Not b

lanking

Figure 9—

The acquisition of the x and y analog values is

managed thanks to a five-state machine executed each

time

the line-batch routine is called (each 65 µs). This allows you
to comply with the PIC ADC timing (precharge,

conversion,

and then read) without losing any time.

background image
background image

48

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

DEVELOPMENT PROCESS

The project was developed with the

MPLAB environment and simulator. I
also used Microchip’s boot loader
firmware (AN851) to burn flash mem-
ory, which is an interesting feature
even if firmware improvements are
welcome. In particular, no on-chip
debug facility is currently provided
(e.g., breakpoints), but I’m sure they’ll
be in the next version.

Also note that the AN851 boot

loader doesn’t provide an automatic
reentry facility. As soon as an applica-
tion firmware is downloaded and acti-
vated, there’s no way to reactivate the
bootloader without specific user-sup-
plied application code (like simultane-
ously pressing the three keys at
power-up). This is well documented in
the literature but more secure solu-
tions exist (e.g., timeout).

I wasn’t lucky enough to have a

full-featured ICE for the processor, so I
wanted to avoid hundreds of burn and
test cycles. I started by developing the
critical code (e.g., the pixel generation
algorithm) on a PC in C—just to vali-

date the algorithm itself. Then, I
developed the full firmware with
MPLAB, keeping a structured
approach to facilitate the validation.

Later, I implemented a bottom-up

approach. I simulated 100% of the
software with small stub routines in
an effort to execute each routine indi-
vidually. Note that I was still using

MPLAB and didn’t have a target sys-
tem at that point. I even kept a source
listing and ticked all of the assembly
lines to be sure to go across each of
them.

I used the MPLAB stopwatch to ver-

ify the timings. When everything
seemed fine under the simulation
framework, I went to the target
processor. That approach proved suc-
cessful. My first burned firmware was
not free from bugs, but I got a work-
ing display with the first burned file!

The RS-232 helped a great deal dur-

ing the final debugging steps. In fact,
rather than having to develop a specif-
ic protocol for each project, I used an
easy and powerful method.

First, the UART firmware dumps

the RAM’s content on the RS-232 port
per the host’s request. Following this,
software on the PC side is able to grab
interesting information based on the
RAM content (e.g., rebuilding some-
thing like a screen hard copy). But the
most interesting point is that the
same feature is invaluable during the
debugging steps!

Photo 2—

The analog front end is on the upper left with

its nine trimmers, the power supplies are on the top
right, and the PIC is in the middle. The PCB has plenty
of empty space because the LCD’s dimensions dictat-
ed its size.

background image
background image

PROBLEMS SOLVED

Strangely, my firmware generated a

serious problem: some of the LCD’s
columns were darker than others, and
it was dependent on the operating
mode and input signals. It took me
several nights of thinking before I
realized that this was because of the
slightly different CPU time spent
between columns. Because the LCD is
dumb, its buffers had stayed open
longer on the columns, and they gave
a darker display.

As always, when you can clearly

define a problem, the solution tends
to be straightforward. For this particu-
lar problem, I simply configured one
of the on-board timers and waited
until precisely 65 µs had been spent
on each column. Problem solved.

IMPROVEMENTS TO COME

The fully operational XY-Plotter

prototype demonstrates that the con-
cept actually works. The screen is
refreshed 70 times per second and
doesn’t flicker. The A/D management,
graph generation, and textual display

50

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Listing 1—

I used this coding technique to meet the strict timing requirements of the project. The routine

sends a configurable number of pulses to the LCD clock input with less than three PIC instructions per pulse
on average! Try to do it with a classic loop.

;Send W pulses to the XSCK line (W = 0 to 60). Execution duration: 100

;ns × (2xW + 20) for W < 60. Average with W = 20 (worst case) giving

;three instructions/pulse (300 ns).

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

send_upto60_pulses

;Limited to 60 because of page boundary

input in tmp_send_w_pulses

movf

tmp_send_w_pulses,W

sublw

.60

;Calculate 2 × (60 – w)

rlncf

WREG

rlncf

WREG

movwf

tmp_send_w_pulses

goto

pulsesaligned

pulsesnotaligned

org

(1 + high pulsesnotaligned)*.256

;Must start on a page boundary

pulsesaligned

movlw

high pulsesaligned

movwf

PCLATH ;High byte of new PC should be defined

movf

tmp_send_w_pulses,W

addwf

PCL,F

;Jump to next instruction if W = 0 (60 pulses)

bsf

PORTB,RB_LCDXSCL_BIT

;pulse 60

bcf

PORTB,RB_LCDXSCL_BIT

bsf

PORTB,RB_LCDXSCL_BIT

;pulse 59

bcf

PORTB,RB_LCDXSCL_BIT

bsf

PORTB,RB_LCDXSCL_BIT

;pulse 58

bcf

PORTB,RB_LCDXSCL_BIT

;etc…

bsf

PORTB,RB_LCDXSCL_BIT

;pulse 02

bcf

PORTB,RB_LCDXSCL_BIT

bsf

PORTB,RB_LCDXSCL_BIT

;pulse 01

bcf

PORTB,RB_LCDXSCL_BIT

retlw

0

;Must be in the same page as the first one

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

51

SOURCES

ECM-A0635-2 LCD
Epson Europe Electronics

are perfect in every mode.

It took me roughly 100 h to com-

plete this project. I still have a couple
of bugs to correct but nothing too
critical. A few more nights of work,
and the plotter will be embedded in
my new spectrum analyzer.

This project clearly demonstrated

the power of low-cost microcon-
trollers. In addition, it proved that
efficient debugging requires a good
simulator. I also learned that LCD
backlight high-voltage generators are
harmful, but that’s another story.

I have a long list of future improve-

ments, one of which is PC-based con-
figuration software to customize the
display for new applications (e.g.,
modification of the textual informa-
tion). That will be easy thanks to the
flash memory-based PIC I used.

Developing this useful project was

extremely fun. I hope reading about it
was fun too!

I

Robert Lacoste lives near Paris,
France. He has 15 years of experience
working on innovative real-time soft-
ware and embedded systems.
Specialized in cost-optimized mixed-
signal designs, he has won over a
dozen international design contests.
Robert currently manages his own
design and consulting company. You
can reach him at rlacoste@alciom.com
or www.alciom.com.

PROJECT FILES

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

RESOURCES

8 × 12 Character set, www.sxlist.com/
techref/datafile/charset/8x12.htm.

Epsom A0635-2 LCD Preliminary
specification, www.supelec-rennes.fr
/ren/fi/elec/ftp/lcd/a0635.pdf.

R. Fosler and R. Richey, A FLASH
Bootloader for PIC16 and PIC18
Devices

, AN851, Microchip

Technology, Inc., 2002.

D. Jones, “Binary to Decimal Conver-

sion in Limited Precision,” The
University of Iowa, www.cs.uiowa.
edu/~jones/bcd/decimal.html, 1999.

Microchip Technology, Inc.,
PIC18FXX2 Data Sheet: High
Performance, Enhanced FLASH
Microcontrollers with 10-Bit A/D

,

DS39564B, 2002.

+49 89 14005-0
www.epson-electronics.de

MCP1541 Voltage reference,
MCP6022 analog amplifier,
PIC18F252 microcontroller
Microchip Technology, Inc.
(480) 786-7200
www.microchip.com

LMC6462 Op-amp
National Semiconductor Corp.
(800) 272-9959
www.national.com

background image

After you decide to implement logic

within a PLD, you’ll need a design
methodology to move ahead and solve
the problem at hand. It is possible to
use the same design techniques as
those used for discrete 7400 logic

52

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

A

typical digital system includes a

microprocessor complemented by
peripherals and miscellaneous glue
logic that ties the components together.
Many of the peripheral and logic func-
tions are available in off-the-shelf ICs.
A variety of UART ICs and DMA con-
trollers are available, too. Simple
address decoding is accomplished with
7400 devices such as the 74LS138. But,
as digital systems become more com-
plex, the chances increase that suitable
off-the-shelf logic will become either
unavailable or impractical. The answer
is to design and implement custom
logic rather than rely solely on a third
party to deliver the perfect solution.

Logic design techniques differ

according to the scale of logic that’s
implemented. If only a few gates are
needed to implement a custom address
decoder or timer, the most practical
solution may be to write down truth
tables, extract Boolean equations,
select appropriate 7400 devices, and
draw a schematic diagram. This used to
be the predominant means to design
logic for many applications. The origi-
nal Apple and IBM desktop computers
were designed in this way, as wit-
nessed by their rows of 7400 ICs.

When functions grow more com-

plex, it becomes awkward and often
impossible to implement the neces-
sary logic using discrete 7400 devices.
Reasons vary from simple density con-
straints (How much physical area would
be consumed by dozens of 7400 ICs?) to

Microprocessor Glue Logic with Verilog HDL

For reasons of availability and practicality, you may soon find it necessary to design custom
logic for your digital projects. There are various design techniques to choose from, but you’ll
want one that suits your specific needs. Mark explains how Verilog HDL may prove to be the
perfect solution for your more complex digital designs.

propagation-delay constraints (How fast
can a signal pass through multiple dis-
crete logic gates?). A common solution
to these problems requires the imple-
mentation of application-specific logic in
a programmable logic device, or PLD.

FEATURE ARTICLE

by Mark Balch

Listing 1—

Verilog gate, or instance, level design entails the manual connection of logical entities in a

netlist-like form. A typical design uses this style for interconnecting hierarchal blocks rather than actually
creating Boolean equations.

module my_logic (

A, B, C, Y

);

input A, B, C;

output Y;

wire and1_out, and2_out, notA;

and_gate u_and1 (

.in1 (A),

.in2 (B),

.out (and1_out)

);

not_gate u_not (

.in (A),

.out (notA)

);

and_gate u_and2 (

.in1 (notA),

.in2 (C),

.out (and2_out)

);

or_gate u_or (

.in1 (and1_out),

.in2 (and2_out),

.out (Y)

);

endmodule

Editor’s note: This article is an excerpt from Mark Balch’s recently published book,

Complete Digital Design: A Comprehensive Guide to Digital

Electronics and Computer System Architecture, McGraw-Hill, 2003.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

53

contextual requirements, logic can be
represented at the gate/instance level,
register transfer level (RTL), or behav-
ioral level.

Gate/instance-level representations

involve the manual instantiation of
each physical design element. An ele-
ment can be an AND gate, flip-flop,
multiplexer, or an entire microproces-
sor. These decisions are left up to you.
In a purely gate/instance-level HDL
design, the HDL source code is noth-
ing more than a glorified list of
instances and connections between
the I/O ports of each instance. The
Verilog instance representation of Y =
A & B + A & C is shown in Listing 1.
It is somewhat cumbersome but pro-
vides full control over the final
implementation.

Listing 1 incorporates many of the

basic pieces of a generic Verilog module.
First, the module is named and declared
with its list of ports. Following the port
list, the ports are defined as either
inputs or outputs. In this case, the ports
are all single net vectors, so no indices
are supplied. Next is the main body that
defines the function of the module.
Verilog recognizes two major variable
types:

wire and reg. A wire simply

connects two or more entities together.
A

reg can be assigned values at discrete

events. When ports are defined, they are
assumed to be

wire unless declared

otherwise. An output port can be
declared as a type other than

wire.

This example is a gate/instance-level

design, so all logic is represented by
instantiating other modules that have
been defined elsewhere. A module is
instantiated by invoking its name and
following it with an instance name.
Here, the common convention of pre-
ceding the name with

u_ is used.

Following the name with a number dif-
ferentiates multiple instances of the
same module type. Individual ports for
each module instance are explicitly
connected by referencing the port name
prefixed with a period and placing the
connecting variable in parentheses.

Listing only the connecting vari-

ables in the order in which a module’s
ports are defined can implicitly con-
nect ports. This is generally consid-
ered poor practice because it is prone
to mistakes and difficult to read.

implementations. The trouble with
graphical logic representations is that
they are bulky and prone to human
error. Hardware description languages
(HDL) were developed to ease the
implementation of more complex digi-
tal designs by representing logic with
high-level semantic constructs found
in mainstream computer programming

languages. One of the major HDLs in
use today is Verilog, which began as a
proprietary product and was eventually
transformed into an open standard.

GATE-LEVEL DESIGN

HDLs enable logical representations

that are abstracted to varying degrees.
According to either your preference or

Listing 2—

RTL level design is the principal method of inferring logic (e.g., Boolean equations and flip-

flops). The same logic function (here a 2:1 multiplexer) may be implemented in multiple ways. Note the dis-
tinction between

wire

and

reg

types:

wires

are continuously assigned, and

regs

are assigned

when discrete events (signal transitions) occur. Events are triggered through an

always

block’s sensitivi-

ty list, which contains a list of the block’s casual signals.

module my_logic (

A, B, C, Y

);

input A, B, C;

output Y;

//Style 1: Continuous assignment

assign Y = (A && B) || (!A && C);

//Style 2: Behavioral assignment

reg Y;

always @(A or B or C)

begin

Y = (A && B) || (!A && C);

end

//Style 3: If-then construct

reg Y;

always @(A or B or C)

begin

if (A)

Y = B;

else

Y = C;

end

endmodule

Listing 3—

Flip-flops are inferred using an edge-sensitive clock event in the sensitivity list.

posedge

and

negedge

are provided by Verilog to indicate a rising- or falling-edge sensitive flip-flop. When a reset sig-

nal is included in the sensitivity list, an asynchronous reset is inferred.

//Synchronous reset

always @(posedge CLK)

begin

if (RESET)

//RESET evaluated only at CLK rising edge

Q <= 1’b0;

else

Q <= D;

end

//Asynchronous reset

always @(posedge CLK or posedge RESET)

begin

if (RESET)

//RESET evaluated whenever it goes active

Q <= 1’b0;

else

Q <= D;

end

background image

54

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

effective test benches. It is important
to realize that these constructs are
usually nonsynthesizable (e.g., a ran-

SYNTHESIS AND SIMULATION

HDL’s textual representation of logic

is converted into actual gates through
a process called logic synthesis. A syn-
thesis program parses the HDL code
and generates a netlist that contains a
detailed list of low-level logic gates
and their interconnecting nets, or
wires. Synthesis is usually achieved
with a specific implementation target
in mind because each implementation
technology differs in the logic primi-
tives it provides as basic building
blocks. After synthesis is performed,
the netlist can be mapped into a PLD.

A key benefit of HDL design method-

ology is the ability to thoroughly sim-
ulate logic before having to debug the
circuit in the lab. Because HDL is a
programming methodology, it can be
arbitrarily manipulated in a software
simulation environment. The simula-
tor allows a test bench to be written
in either the HDL or another language
(e.g., C/C++) that is responsible for
creating a stimulus to be applied to
the logic modules.

A distinction is made between syn-

thesizable and nonsynthesizable code
when writing RTL and test benches.
Synthesizable code represents the logic
to be implemented in some type of chip.
Nonsynthesizable code is used to imple-
ment the test bench and usually con-
tains constructs specifically designed for
simulation that cannot be converted
into real logic through synthesis.

An example of a test bench for the

preceding Verilog module may consist
of three number generators that apply a
pseudorandom test stimulus to the three
input ports. Automatic verification of
the logic would be possible by having
the test bench independently compute
the function Y = A & B + A & C and
then check the result against the mod-
ule’s output. You can use such simula-
tion, or verification, techniques to
root out the majority of bugs in a com-
plex design. This is a tremendous fea-
ture because it is usually faster to iso-
late and fix a bug in simulation than in
the laboratory. In simulation, you have
immediate access to all of the design’s
internal nodes. In the lab, such access
may prove difficult to achieve.

Verilog supports simulation con-

structs that facilitate the writing of

dom number generator), and they
should be used for writing test code
rather than actual logic.

Listing 4—

Blocking and nonblocking assignments can result in different logic inferences. Nonblocking

assignments are preferred for sequential logic (flip-flops), whereas blocking assignments are preferred for
describing combinatorial logic paths.

//Non-blocking assignments: two flops inferred

always @(posedge CLK)

begin

Q1 <= D;

Q2 <= Q1;

end

//Blocking assignments: one flop inferred

always @(posedge CLK)

begin

Q1 = D;

Q2 = Q1;

end

Listing 5—

This example of basic asynchronous address decoding uses the case construct to activate indi-

vidual chip-selects when specific address ranges are active on the address bus. All driven signals are
assigned default values so that each enumerated address range does not have to explicitly assign each
signal. Undesirable latches are formed in a combinatorial

always

block when there exists at least one

combination of inputs that does not result in a signal being assigned a value.

module GlueLogic (

Addr,

RomSel,

CS0_,

CS1_,

CS2_,

CS3_

);

input [23:20] Addr;

input RomSel;

output CS0_, CS1_, CS2_, CS3_;

reg CS0_, CS1_, CS2_, CS3_;

reg IntSel;

always @(Addr or RomSel)

begin

CS0_ = 1’b1; //Establish default values to simplify case

CS1_ = 1’b1; //Statement and prevent formation of latches

CS2_ = 1’b1;

CS3_ = 1’b1;

IntSel = 1’b0;

case (Addr[23:20])

4’b0000 : begin

CS0_ = RomSel;

CS1_ = !RomSel;

end

4’b0001 : begin

CS0_ = !RomSel;

CS1_ = RomSel;

end

4’b0010 : CS2_ = 1’b0;

4’b0011 : CS3_ = 1’b0;

4’b0100 : IntSel = 1’b1;

endcase

end

endmodule

background image
background image

56

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

REGISTER TRANSFER LEVEL

Gate/instance-level coding is used

to varying degrees in almost every
design, but the real power of HDL lies
at the RTL and behavioral levels.
Except in rare circumstances when
absolute control over gates is required,
instance-level coding is mainly used
to connect different modules together.
Most logic is written in RTL and behav-
ioral constructs, and they are often treat-
ed together, hence the reason that syn-
thesizable HDL code is often called RTL.

Expressing logic in RTL frees you from

having to break everything down into
individual gates, and it transfers this
responsibility to the synthesis software.
The result is a dramatic increase in pro-
ductivity and maintainability because
logical representations become concise.
You can rewrite Listing 1 in Verilog RTL
in multiple styles, as shown in Listing 2.

Each of the three styles has its

advantages, and each is substantially
more concise and readable than the
gate/instance-level version. You can
freely mix the styles within the same
module according to your preference.

The first style is a continuous assign-
ment; it makes use of the default wire
data type for the output port. A wire
is applicable here because it implicitly
connects two entities: the logic function
and the output port. Continuous assign-
ments are useful in certain cases because
they are concise, but they cannot get too
complex without becoming unwieldy.

The second style uses the

always

block, which is a keyword that tells the
synthesis and simulation tools to per-
form the specified operations whenever
a variable in its sensitivity list changes.

The sensitivity list defines the variables
that are relevant to the

always block. If

all the relevant variables are not included
in the list, incorrect results may occur.

Note that

always blocks are one of

Verilog’s fundamental constructs. A
design may contain numerous

always

blocks, each of which contains logic
functions that are activated when a
variable in the sensitivity list changes
state. A combinatorial

always block

should normally include all of its input
variables in the sensitivity list. Failure to
do so can lead to unexpected simulation

Address range

Qualifier

Chip select

Function

0x000000-0x0FFFFF

RomSel=0

CS0_

1-MB default boot ROM

0x100000-0x1FFFFF

RomSel=1

0x100000-0x1FFFFF

RomSel=0

CS1_

1-MB ROM module

0x000000-0x0FFFFF

RomSel=1

0x200000-0x21FFFF

N/A

CS2_

128-KB SRAM

0x220000-0x2FFFFF

N/A

None

Unused

0x300000-0x30000F

N/A

CS3_

UART

0x300010-0x3FFFFF

N/A

None

Unused

0x400000-0x4FFFFF

N/A

Internal

Control/status registers

0x500000-0xFFFFFF

N/A

None

Unused

Table 1—

An example 16-MB memory map illustrates how address decoding can be performed. Two swappable

ROM banks are present along with sparsely located peripherals for easier decoding.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

57

results because the

always block will

not be activated if a variable changes
state and is not in the sensitivity list.

The third style also uses the

always

block, but it uses a logical

if-else con-

struct in place of a Boolean expression.
Such logical representations are often
preferable so you can concentrate on the
functionality of the logic rather than
deriving and simplifying Boolean algebra.

FLIP-FLOPS

The two examples I’ve shown you

illustrate basic Verilog HDL syntax
with combinatorial logic. Clearly, syn-
chronous logic is critical to digital
systems, and it is fully supported by
HDLs. D-type flip-flops are most com-
monly used in digital logic design, and
they are directly inferred by using the
correct RTL syntax. As always, gate-
level instances of flops can be invoked,
but this is discouraged for the reasons
already discussed. Listing 3 shows the
Verilog RTL representation of two flops,
one with a synchronous reset and the
other with an asynchronous reset.

The first syntactical difference to

notice is the Verilog keyword

posedge.

Note that

posedge and its complement,

negedge, modify a sensitivity list vari-
able to activate the

always block only

when it transitions. Synthesis tools are
smart enough to recognize these key-
words and infer a clocked flop. Clocked
always blocks should not include nor-
mal

reg or wire variable types in the

sensitivity list, because it is only
desirable to activate the block on the
active clock edge or when an optional
asynchronous reset transitions.

At reset, a default zero value is

assigned to

Q. Constants in Verilog can

be explicitly sized and referenced to a
particular radix. Preceding a constant
with

|

b denotes it as binary. (

|

h is hex,

and

|

d is decimal.) Preceding the radix

identifier with a number indicates the
number of bits the constant occupies.

Another syntactical difference to

note is the use of a different type of
assignment operator,

<= instead of =.

This is known as a nonblocking (

<=)

assignment as compared to a blocking
(

=) assignment. It is considered good

practice to use nonblocking assign-
ments when inferring flops because
the nonblocking assignment doesn’t

take effect until after the current sim-
ulation time unit. This is analogous to
the behavior of a real flop, where the
output does not transition until a finite
period of time has elapsed after its trig-
gering event. Under certain circum-
stances, either type of assignment will
yield the same result in both simulation
and synthesis. In other situations, the
results will differ, as shown in Listing 4.

In the first case,

reg variable types

Q1 and Q2 are tracked at two different
instants in time. First, their current

states are maintained as they were just
prior to the clock edge for the purpose
of using their values in subsequent
assignments. Second, their new states
are assigned as dictated by the RTL.
When

Q2 is assigned, it takes the previ-

ous value of

Q1, not the new value of

Q1, which is D. Two flops are inferred.

In the second case, variables

Q1 and

Q2 are tracked at a single instant in
time.

Q1 is assigned the value of vari-

able

D, and then Q2 is assigned the new

value of variable

Q1. Q1 has become a

background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

59

temporary placeholder and has no
real effect on its own; therefore,
only a single flop,

Q2, is inferred.

ADDRESS DECODING

Most digital systems require a

quantity of miscellaneous glue
logic to help tie a CPU to its mem-
ory and I/O peripherals. Some
common support functions are
address decoding, basic I/O sig-
nals, interrupt control, and timers.

Address decoding is usually a

combinatorial implementation
because many CPU interfaces are
non-pipelined. When performing address
decoding and other bus-control functions
for a pipelined CPU bus, a more complex
synchronous circuit is called for that can
track the various pipeline stages and take
the necessary actions during each stage.
Basic combinatorial address decoding
consists of mapping ranges of addresses
to chip selects. Chip select signals are
usually active low by convention and
are numbered upwards from zero. For
the sake of discussion, consider the
24-bit memory map in Table 1 to
design an address decoder.

Four external chip selects are called

out. Instead of using the asterisk to
denote active-low signals, the underscore
is used because an asterisk is not a valid
character for use in a Verilog identifier.
The first two chip selects are used for
ROM (e.g., flash memory or EPROM),
and their memory ranges are swappable
according to the

RomSel signal.

Sometimes it’s useful to provide an

alternate boot ROM that can be
installed at a later date for various pur-
poses such as a software upgrade. When
boot ROM is implemented in flash
memory, the CPU is able to load new
data into its ROM. If there is no other
way to send a new software image to
the system, the image can be loaded
onto a ROM module that is temporari-
ly installed into the

CS1_ slot. Then a

jumper can be installed that causes
RomSel to be asserted. When the sys-
tem is turned on,

RomSel=1 causes

the ROM module to become the boot
ROM, and new software can be loaded
into

CS0_ ROM.

The remainder of the address space

is sparsely populated. Occupied mem-
ory regions are spread out to reduce

the complexity of the decoding logic
by virtue of requiring fewer address
bits. If the UART was located imme-
diately after the SRAM, the logic
would have to consider the state of
A[23:16] rather than just A[23:20]. The
fifth and final used memory region is
reserved for internal control and sta-
tus registers. This decoding logic can
be written in Verilog (see Listing 5).

The address decoding logic was writ-

ten in behavioral form with a case con-
struct. Case statements enable actions
to be associated with individual states
of a causal variable. Note that the chip
select outputs are declared as

regs even

though they are not flops because they
are assigned in an

always block

instead of in a continuous assignment.

Prior to the case statement, all of the

always block’s outputs are assigned to
default inactive states. This prevents
the synthesis software from inferring an
unwanted latch instead of simple combi-
natorial logic. If a combinatorial

always

block does not assign a

reg value for all

input combinations, the synthesis tool
determines that the

reg should hold its

previous state, thereby creating a latch.
Latches are prevented by either exhaus-
tively listing all combinations of inputs
or assigning a default value to all vari-
ables somewhere in the

always block.

Unintended latches are the bane of

HDL design. There are valid instances
when a latch is desired, but latches
are often mistakenly inferred because
the RTL code does not properly han-
dle default cases where the variable is
not assigned. Combinatorial logic
must always assign values to variables
regardless of the logic path. Otherwise,
statefullness is implied. Verilog’s

blocking assignments enable
multiple values to be assigned
to a single variable in an
always block, and the last
assigned variable is the one that
takes effect. Therefore, latches
are avoided by assigning default
values up front. An active-high
signal,

IntSel, is decoded but

not used (yet) for selecting inter-
nal control and status registers.

BUS EXPANSION

When expanding a CPU bus,

make sure that too many devices

aren’t on the bus, because output pins
are only rated for certain drive strengths.
As the interconnecting wires lengthen
and the number of loads increases, it
may become necessary to extend the
CPU bus using bidirectional buffers.

Figure 1 shows how my hypotheti-

cal system might use such buffers to
isolate the plug-in ROM module so
that the electrical impact of connec-
tors and a separate module are mini-
mized. Control signals are not shown
for clarity. A unidirectional buffer iso-
lates the address bus, and a bidirec-
tional buffer isolates the data bus. No
control is necessary for the address
buffer because it can be configured to
always pass the address bus to the
ROM module socket. However, the
data buffers require control because they
must direct data out to the module for
writes and in from the module for reads.
Therefore, the tristate control of the data
buffer must be operated according to the
address decode and read/write status.

The existing address decoding logic

can be augmented to provide the neces-
sary functionality. One additional input
is required—the CPU’s active-low read
enable signal. An additional output is
required to operate the data buffer’s
direction select signal. When high, the
buffers pass data from the CPU side to
the ROM; when low, the buffers drive
the CPU data bus with data presented by
the ROM. A second

always block can

be added (see Listing 6). New port and
variable declarations are assumed.

READ/WRITE REGISTERS

Another common function of sup-

port logic is to provide general I/O sig-
nals that the CPU can use to interact

CPU

Address

decode

logic

Local

memory and

peripherals

ROM

Module

Data bus

Address bus

74LS244

or similar

74LS245

or similar

Figure 1—

A CPU bus may need extension buffers if it is too long or there

are more loads than the I/O drivers can handle. Data bus buffers must be
bidirectional/tristate-capable to drive write data to the expansion module
and drive read data to the CPU.

background image

60

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Listing 6—

A bidirectional data bus buffer can be controlled based on the chip select and read enable sig-

nals. When a read is performed, the buffer is turned to drive data towards the CPU. In all other circum-
stances, the buffer drives data from the CPU.

always @(CS1_ or Rd_)

begin

if (!CS1_ && !Rd_)

DataBufDir = 1’b0;

//Drive CPU bus when ROM selected for read,

else

DataBufDir = 1’b1; //Otherwise always drive data to ROM

end

Listing 7—

Register read/write logic can be implemented in asynchronous or synchronous fashion accord-

ing to the application’s needs. In both cases, a read multiplexer selects a single register. The asynchronous
circuit does not register the outgoing data bus and forms latches for the writeable register. The synchro-
nous circuit registers outputs and uses flip-flops for the writeable register.

always @(Addr[3:0] or StatusInput[7:0] or ControlReg[7:0] or IntSel)

begin

case (Addr[3:0])

//Read multiplexer

4’h0 : ReadData[7:0] = StatusInput[7:0];

//External input pins

4’h1 : ReadData[7:0] = ControlReg[7:0];

default : ReadData[7:0] = 8’h0;

//Alternate means to prevent latch

endcase

ControlRegSel = 1’b0;

//Default inactive value

case (Addr[3:0])

//Select signal only needed for writeable registers

4’h1 : ControlRegSel = IntSel;

endcase

end

//Option 1A: asynchronous read logic

assign CpuData[7:0] = (IntSel && !Rd_) ? ReadData[7:0] : 8’bz;

//Option 1B: synchronous read logic

always @(posedge CpuClk)

begin

if (!Reset_)

//Synchronous reset

CpuDataOE <= 1’b0;

//No need to reset ReadDataReg and possibly save some logic

else begin

CpuDataOE <= IntSel && !Rd_;

//All outputs are registered

ReadDataReg[7:0] <= ReadData[7:0];

end

end

assign CpuData[7:0] = CpuDataOE ? ReadDataReg[7:0] : 8’bz;

//Option 2A: asynchronous write logic

always @(ControlRegSel or CpuData[7:0] or Wr_ or Reset_)

begin

if (!Reset_)

ControlReg[7:0] = 8’h0; //Reset state is cleared

else if (ControlRegSel && !Wr_)

ControlReg[7:0] = CpuData[7:0];

//Missing else forces memory element: intentional latch!

end

//Option 2B: synchronous write logic

always @(posedge CpuClk)

begin

if (!Reset_)

//Synchronous reset

ControlReg[7:0] <= 8’h0;

else if (ControlRegSel && !Wr_)

ControlReg[7:0] <= CpuData[7:0];

end

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

61

start operating before the CPU finish-
es booting and can disable them.

The read logic consists of two sec-

tions: the output multiplexer and the
output buffer control. The former sim-
ply selects one of the available regis-
ters for reading. It is not necessary to
qualify the multiplexer with any other
logic, because a read will not actually
take place unless the output buffer
control logic sends the data to the
CPU. Rather than preventing a latch in
ReadData by assigning it a default
value before the case construct, the
Verilog keyword

default is used as the

final case enumeration to specify default
operation. Either solution will work; it
is a matter of preference and style over
which to use in a given situation.

Both read-only and writeable registers

are included in the read multiplexer
logic. Strictly speaking, it is not manda-
tory to have writeable register contents
readable by the CPU, but it is a good
practice. Years ago, when logic was
extremely expensive, it was not
uncommon to find write-only registers.
However, there is a substantial draw-
back to this approach: you can never be
sure what the contents of the register
are if you fail to keep track of the exact
data that has already been written!

BIDIRECTIONAL PINS

Implementing bidirectional signals

in Verilog can be achieved with a con-
tinuous assignment that selects
between driving an active variable or a
high-impedance value, Z. The asyn-
chronous read logic is simple: whenever
the internal registers are selected and
read enable is active, the tristate buffer
is enabled and the output of the mul-
tiplexer is driven to the CPU data bus.
At all other times, the data bus is held
in a high-impedance state. This works
as expected because the value Z can be
overridden by another assignment. In
simulation, the other assignment may
come from a test bench that emulates
the CPU’s operation. In synthesis, the
software properly recognizes this
arrangement as inferring a tristate bus.

The continuous assignment takes

advantage of Verilog’s conditional oper-
ator,

? : , which serves an if-else

function. When the logical expression
before the question mark is true, the

value before the colon is used; other-
wise, the value after the colon is used.
A bidirectional port is declared using
the Verilog

inout keyword in place of

input or output. The synchronous ver-
sion of the read logic is similar to the
asynchronous version, except that the
outputs are first registered before being
used in the tristate assignment.

TIP OF THE ICEBERG

Basic microprocessor support func-

tions including interrupt control and
timers are the next step beyond what
has been presented. Going further,
multiphase bus protocols and data-
processing algorithms are often imple-
mented with finite state machines
written and simulated in an HDL
design environment. Choosing to
develop logic with an HDL does not
force a one-size-fits-all approach.
Rather, it enables you to take advan-
tage of specific HDL features that are
appropriate for each situation. Small
address decoders in a PAL-type device
may not require the development
overhead of a simulation test bench.
Moderately complex glue logic and bus
interfaces can be simulated to whatever
detail is considered practical.

HDL simulation and synthesis tools

are available in a wide range of prices
and capabilities. Top-of-the-line tools
run into the tens of thousands of dol-
lars per seat. For those on a tight
budget, these tools are commonly
bundled into relatively low-cost devel-
opment packages by PLD vendors to
encourage the use of their chips. Such
vendors include Actel, Altera, Cypress,
Lattice, QuickLogic, and Xilinx. Once
solely the domain of high-budget chip
development, the HDL design method-
ology has become practical across the
full spectrum of logic design.

I

with its environment. Such interac-
tion can include detecting an opening
door and turning on an alarm. The
opening door can be detected using a
switch connected to an input signal.
When the CPU reads the status of this
signal, it can determine whether the
switch is open or closed. An alarm can
be turned on when the CPU sets an
output signal that enables an alarm
circuit. Control and status registers
must be implemented to enable the
CPU to read and write I/O signals.

In my example, I assume an 8-bit data

bus coming from the CPU, as well as the
need for eight input signals and eight
output signals. Implementing registers
varies according to whether the CPU bus
is synchronous or asynchronous. Some
older microprocessors use asynchronous
buses requiring latches to be formed
within the support logic. Listing 7 shows
the implementation of two registers
using the previously decoded

IntSel sig-

nal in both synchronous and asynchro-
nous styles. Again, the proper declara-
tions for ports and variables are assumed.

An added level of address decoding is

required in this to ensure that the two
registers are not accessed simultaneously.
The register logic consists of two basic
sections: the write logic and read logic.

The write logic, which is only required

for the control register that drives output
signals, transfers the contents of the CPU
data bus to the internal register when the
register is addressed and the write enable
is active. The

ControlRegSel signal is

implemented in a case statement, but it
can be implemented in a variety of ways.
The asynchronous write logic infers a
latch because not all permutations of
input qualifiers are represented by assign-
ments. If Reset_ is high and the control
register is not being selected for a write,
there is no specified action. Therefore,
memory is implied, and, in the absence
of a causal clock, a latch is inferred.

The synchronous write logic is

almost identical, but it references a
clock that causes a flop inference.
Reset is implemented to provide a
known initial state. This is a good idea
so that external logic driven by the
control register can be designed safely,
assuming the operations begin at a
known state. The known state is usu-
ally inactive so that peripherals do not

Mark Balch is a Silicon Valley-based
author and electrical engineer. He
holds a B.S.E.E. from The Cooper
Union in New York City. In addition
to PCB, FPGA, and ASIC design, he
has developed products for the HDTV,
consumer electronics, and industrial
computers industries. Currently, Mark
designs high-performance computer-
networking hardware. You may reach
him at mark_balch@hotmail.com.

background image

62

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Y

ou’re a Circuit Cellar reader,

which means it’s entirely possible that
you fall into the category of “neighbor-
hood guru.” You’re the guy who repairs
all of your friends’ (and their friends’)
electronic gadgets. You are also proba-
bly the neighborhood’s certified
Microsoft Windows expert and regu-
larly answer questions like, What does
“missing operating system” mean? If
you cannot offer a credible excuse, you
become the neighborhood A+ certified
technician, and find yourself replacing
and reloading a crashed hard drive. Why
do professional basketball coaches wear
$1500 suits? Because they can. Why do
you help your friends and neighbors?
Because you can.

I’m sure that most of you have used

your engineering skills to solve tech-
nical problems presented to you by
friends who “don’t do what you do.” I
don’t know if I qualify as the neighbor-
hood guru, but for the past couple of
years I’ve had the opportunity to help a
worthy cause and have some fun doing
“what I do” to provide that assistance.

It all started when my friend

Wayne’s homebrew Pinewood Derby
setup failed. Of course, the original
designer was no longer part of the
organization and, naturally, he was
nowhere to be found. The electronics
consisted of a makeshift PC card
loaded with analog circuitry that sens-
es the breaking of an infrared beam
shot from a overhanging set of IR
emitters to the IR receivers embedded
in the track.

and powerful Atmega128 do every-
thing: multiplex and drive the eight
super-sized seven-segment LEDs; pro-
vide a PWM signal for the eight IR
emitters; sense the IR beam interrup-
tions via eight IR sensors; and update
the RS-232 console and the eight seven-
segment lane finish order LED displays.

There were also plans for displaying

the elapsed times and calculating the
pine block cars’ simulated speeds on
the PC console, but the race day dead-
line was approaching, and I didn’t
have time to finish the frills firmware
package. So, the initial release of the
Pinewood Derby computer simply dis-
played the order of the finish by lane
with a corresponding number fed to
each lane LED display.

After Wayne’s organization had fin-

ished their annual race, the Pinewood
Derby computer and track were loaned
to another group to add some excite-
ment (and fairness) to their event.
Unfortunately, the unit was somehow
damaged, and one of the borrowing
organization’s neighborhood gurus
attempted a fix sans a schematic or
knowledge of how the Pinewood
Derby computer’s systems work.
Needless to say, Wayne once again
paid a visit to the Florida Room, but
this time with a totally trashed piece
of custom-made equipment.

I had hand-wired Wayne’s terminally

ill pinewood timer by using IC ship-
ping rails as support for four pieces of
interconnected perf board that was
stuffed inside a special cabinet, which

Speed Racer

APPLIED PCs

by Fred Eady

I was impressed by the original

designer’s ingenuity. He had built his
infrared beam-sensing circuitry on a
piece of standard perf board using
point-to-point wiring. Then, he screw-
mounted the perf board assembly to
a dead ISA modem card. The dead
modem’s ISA pins were disconnected
from the original modem electronics
and patched into the perf board’s ana-
log circuitry. This piggyback assembly
allowed the op-amp-laden perf board/
dead-modem card set to be easily
plugged into one of the host PC’s ISA
slots. The host PC was a junker 486. A
DOS-based Basic program performed the
I/O, finish timing, and display function-
ality. Did I mention that there isn’t a
schematic for this contraption?

Wayne wanted to chuck the PC

because the cables running out of the
homemade ISA race-timing card tend-
ed to pull the card set out of the ISA
slot. And, to race, he had to depend on
the old 486 and an undocumented
QuickBasic program. The track sensors
and companion electronics had finally
parted ways because of one too many
connect/disconnect cycles when Wayne
appeared at the Florida Room’s screen
door. It was time to design and build a
stand-alone, track-timing computer.

A LOT OF PRACTICE

The first spin of Wayne’s Pinewood

Derby computer was performed with
an Atmel ATmega128 and a bunch of
74HCT5xx buffers and latches. The
design concept was to have the fast

Fred’s the guy many of his neighbors turn to with their electronics and computing problems.
Recently, one of his neighbors approached him regarding the trouble he was having with his
Pinewood Derby racing setup. This month, Fred explains how he came through with a PIC-
based track-timing Pinewood Derby computer.

Stand-Alone, Track-Timing Pinewood Derby Computer

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

63

had been tooled by my machine-shop
buddy, Mark. To add insult to injury,
the offending neighborhood guru had
drilled out a precision hole in the cab-
inet to replace a switch he had
destroyed in the process of attempting a
repair. The repair confidence must have
been extremely high because a couple
of screws that held the back panel of
the timer cabinet were severely cross-
threaded. After a week or so of debating
whether I should fix it or trash it and
start over, I decided to trash it.

FROM THE ASHES

The second time through I wanted

to design the new Pinewood Derby
computer around a distributed system
of microcontrollers. If you don’t plan
carefully, the advantages of task distri-
bution can be offset by the cost of
task distribution. So, I decided to use
the least inexpensive microcontroller
on hand in the Florida Room that
would have all the attributes I would
need to complete the design. My
microcontroller selection checklist
included lots of available digital I/O
lines to accommodate the following:
LED displays; status, control, and IR
sensor lines; PWM capability for the
IR emitters; RS-232 connectivity for
the PC console; and some form of
inexpensive networking to connect
the distributed microcontrollers.

I sifted through some preliminary

design ideas and determined that I
needed a fast microcontroller to
accommodate the following: one 8-bit
port for the LED segments (no muxing
this time); at least one external inter-
rupt line for the IR receiver; an addi-
tional 4 bits of port I/O for status and
control; a dedicated USART for the
master microcontroller; and a cheap
and easy way to glue the microcon-
trollers together with a minimum of
extra hardware and supporting silicon.

All of my problems, with the excep-

tion of the internal network issue,
could have been easily solved with
any of a number of different micro-
controllers. My first thought had been
to invent yet another bit-bang proto-
col that would employ the services of
a few I/O pins from each microcon-
troller in the network, but I quickly
shot down the idea because I wasn’t up

to putting together the firmware and
thinking through the logic for multi-
byte bit banging across nine micro-
controllers. Besides, I’d forget why I
had done this or that if I had to go
back into the code or hardware to fix
something a year later. I needed some-
thing that was standardized and
preferably already included inside the
microcontroller.

The idea of standardization led me

to think about using the built-in
USART on each microcontroller to
form the bidirectional microcontroller
network I desired. I considered using a
9-bit asynchronous protocol, and even
thought about trying to get a synchro-
nous thing going. After considering
the cost, however, I dropped the asyn-
chronous communications idea,
because I would have to keep up with
the status of each microcontroller’s
transmitter and receiver to avoid colli-
sions on the network. That seemed
like too much unnecessary work.

I had worked my way around the

pins of my preliminary microcon-
troller, the PIC16F873, so all that was
left was SPI and I

2

C. I quickly discount-

ed SPI because I would need an off-IC
multiplexer or a larger collection of I/O
pins to pull off master-to-slave commu-
nication using the SPI protocol. Besides,
I have a tube of PIC16F873s that I’m
going to use one way or another.

OK. I was down to I

2

C. I didn’t want

to resort to any of my previous solu-
tions, so I was hoping it would be
what I needed to complete my new
car timer design. As I pondered
whether or not to use I

2

C, the inher-

ent goodness of the protocol started to
bubble to the top. I

2

C doesn’t need

any special connectors, magnetic mod-
ules, or auxiliary voltage conversion
hardware. All I needed were a couple
of resistors and a small amount of
firmware to get an I

2

C network online.

I also realized that going with the

I

2

C method would allow me to use a

smaller microcontroller. Unlike SPI,
I

2

C uses a packet-based slave-address-

ing scheme instead of slave select
lines to single out a device on the net-
work. Another quick look at the
PIC16F873 datasheet and pinout con-
firmed that I could run both the PIC’s
USART and the I

2

C module (master syn-

chronous serial port, or MSSP) concur-
rently, which meant I could service the
PC console and slave microcontrollers
without having to bother myself with
internal microcontroller peripheral
switching and status housekeeping.

I had made my hardware decision:

PIC16F873s for all nine microcon-
trollers. And this time I planned to
use professional PCBs instead of perf
board for the main computing module
and LED display assembly. I decided to
use UDN2595A eight-channel saturated
sink drivers to interface the PICs’ I/O
lines to the segments of the LED dis-
plays. Additional current-sinking duties
would be handled by a ULN2003A.

I assembled a prototype of the lane

and master microcontroller hardware
on a perf board to verify my design

Photo 1—

With a little help from my MPLAB ICE 2000,

I was able to verify that the master and lane microcon-
trollers would play together in the new design.

Photo 2—

Just like any good race team, the drivers

trash ’em and we rebuild ’em. The IR emitters, which
are located on the underside of the tower, are mounted
in precision-machined positions relative to the track
sensors. When the electronics are mounted inside the
enclosure, a single 25-pin D-shell connector mates the
track sensors and tower electronics.

background image

64

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

(see Photo 1). Then, I sent the enclo-
sure back to Mark’s shop for some
bodywork. The production electronics
and the reincarnated enclosure are
shown in Photo 2.

HARDWARE DESIGN

I

2

C is the backbone that supports

the entire Pinewood Derby computer
design. As you’ve already figured out,
Wayne’s track is eight lanes wide, so I

dedicated a microcontroller to each
lane. Each lane’s microcontroller is
responsible for responding to com-
mands from the I

2

C master microcon-

troller. The microcontrollers sense the

Figure 1—

The idea is to have as many standard plug-in devices as possible. This makes the electronics easy to troubleshoot and repair. Each lane’s circuitry is identical

except for the distinguishing address byte in each lane microcontroller’s firmware.

JK

microsystems, Inc.

Visit us on the web www.jkmicro.com

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

Tools

to

Move

Data

µFlashTCP-EP

*

10Base-T Ethernet

2 Serial Ports

7-34 VDC

Optional I/O Interface

Rugged Enclosure w/

Industry Standard

Connectors

Starts at

$229

LogicFlex

*

10Base-T Ethernet

2 Serial Ports

46 Digital I/O’s

Programmable Xilinx CPLD

Hardware Clock/Calendar

Expansion Bus for

Peripheral Boards

Starts at

$189

Dual-E

*

2 Ethernet Ports

2 Serial Ports

3 Counter / Timers

5 Digital I/O’s

Onboard Connectors

USNET TCP/IP

Software in Kits

Starts at

$199

TCP/
IP

Solutions

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

&

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

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

1403 Fifth St., Suite D

Davis, CA 95616 USA

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

*

LogicFlex-EPX

*

10Base-T Ethernet

2 Serial Ports

16 Opto-Isolated inputs

16 Relay Outputs

@

500mA ea.

Quick-Disconnect Connectors

Rack Mount Enclosure

LCD

&

6 Pushbuttons

Starts at

$499

NEW

Products

background image
background image

66

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

cars in their lanes via their IR detec-
tors, and they provide an elapsed time
for them to the master microcontroller.

In addition to monitoring each

lane’s microcontroller for an elapsed
time available signal, the master
microcontroller provides a 38-kHz
PWM signal for the IR emitters and a
common reset signal for all of the
slave lane microcontrollers. It also
monitors the race start switch, and
computes the order of finish by using
each lane’s reported elapsed time.

Each time a lane microcontroller

signals that the car in its lane has
passed through the IR trap, the master
microcontroller retrieves the elapsed
time from the lane microcontroller
via the I

2

C link and computes the

lane’s relative finish at that point in
time. The finish order (1, 2, 3, etc.) is
sent back to the lane microcontroller
and displayed on the LED display that
represents that lane. An ASCII mes-
sage is also sent out of the master
microcontroller’s RS-232 port that
details the finish order and elapsed
time in readable form.

Wayne’s initial PC-dependent design

suffered from component overload. A
minimum of 20 components per lane
was used in the original analog design
to sense a car passing through the
timing trap. Using the Panasonic
PNA4602M and a companion LN68, I
reduced the lane IR emitter/sensor part
count to three items including the
current-limiting resistor for the LN68.

The PNA4602M is billed as a bipo-

lar integrated circuit with photo-detec-
tion functionality. It does not require
any external parts and is enclosed in a
special resin that absorbs visible light.
The PIC’s PWM is set to provide a
38-kHz square wave to one of the
ULN2003A buffers that provides a
ground path for all of the LN68 lane
IR emitters. The modulated IR light is
sensed by the PNA4602M, amplified,
filtered, and demodulated before being
passed through an internal integrator
and comparator.

The comparator feeds an internal

NPN transistor that has its collector
tied to V

CC

through a resistor. As

long as the PNA4602M is exposed to
38-kHz modulated IR light, the NPN
transistor is on, and the PNA4602M

outputs a low to the PIC’s external
interrupt pin RB0. The lane ’16F873’s
RB0 external interrupt mechanism is
instructed to trigger on a low-to-high
transition, which occurs when a car
passes through the IR timing trap and
interrupts the IR beam.

A microswitch integrated in the

track’s starting gate signals the master
microcontroller that the starting gate
is closed and a race can begin. After
sensing the closure of the start gate,
the master microcontroller resets the
lane microcontrollers by dropping the
master microcontroller’s MCLR line
to ground through another ULN2003A
buffer. The lane microcontrollers per-
form a reset sequence, which includes
an LED display segment test and the
initialization of their internal timers
and TRIP_X status lines.

Each set of lane electronics is

labeled (A through H) on the PCB. I
used letters so that lane numbers
could be assigned in any manner with-
out any of the lane electronics being
tied to a specific lane of the track.
TRIP_A corresponds to lane A, TRIP_B
to lane B, and so on. When the starting
gate is closed and all of the TRIP_X
status lines (A through H) are account-
ed for by the master microcontroller,
the master microcontroller waits for

the starting gate to open, which indi-
cates that the race has begun.

When the starter trips the start gate,

the master microcontroller senses the
event and activates the GO status line
to all of the lane microcontrollers
through another ULN2003A buffer. At
that point, the lane microcontroller
timers click off elapsed time, and the
master microcontroller polls each of
their TRIP_X status lines.

After a car passes through the tim-

ing trap, the lane microcontroller cap-
tures the elapsed time and activates
its TRIP_X line. The master sees the
lane microcontroller’s TRIP_X signal
and reads the raw elapsed time from
the lane microcontroller using the I

2

C

link. After the time and finish-order
calculations are done, the master micro-
controller sends a finish-order number
to the lane microcontroller, which pass-
es the number on to its LED display.

The Pinewood Derby computer can

be powered by any clean 5 VDC at 1 A.
I designed in a standard PC power sup-
ply connector to simplify the power
interface. The Pinewood Derby comput-
er circuitry is shown in Figure 1.

ESSENTIAL FIRMWARE

Each lane controller is a clone of its

neighbor in terms of hardware and

Listing 1—

The end of an I

2

C master-receiver read operation is signaled by a NAK from the master micro-

controller against the last byte that was clocked out of the receiver. A NAK in this case is the absence of an
acknowledge. The

0

in the last read instruction of the

read_slave_i2c(int8 addr)

function

et[milli_l] = i2c_read(0);

instructs the

i2c_read

function to issue a NAK.

//Set slave LED via I

2

C

void set_led_i2c(int8 addr,int8 value)

{

i2c_start();

i2c_write(addr);

i2c_write(value);

i2c_stop();

}

//Read slave via I

2

C

void read_slave_i2c(int8 addr)

{

int8 lane;

i2c_start();

i2c_write(addr+1);

et[lane_id] = i2c_read();

et[sec_h] = i2c_read();

et[sec_l] = i2c_read();

et[milli_h] = i2c_read();

et[milli_l] = i2c_read(0);

i2c_stop();

lane = swap(et[lane_id] & 0xF0);

lane_et[lane] =

make32(et[lane_id],et[sec_l],et[milli_h],et[milli_l]);

}

background image

www.circuitcellar.com

Issue 158 September 2003

67

CIRCUIT CELLAR

®

firmware. Although the master micro-
controller can distinguish between
them by their TRIP_X status lines, that
doesn’t help when it comes to commu-
nicating with them using the I

2

C link.

A master-to-slave I

2

C write transaction

begins with a start condition, which
is followed by 8 bits of address infor-
mation and ends after the last data byte
is transferred with a stop condition.

A start condition is defined as a high-

to-low transition on the SDA line
while the SCL line is high. A stop bit
is generated when a low-to-high tran-
sition on the SDA line occurs while the
SCL line is high. The master always
generates a start or stop condition.

I used the I

2

C 7-bit addressing

scheme in which 7 bits of address
information (the most significant bit
first) are clocked out from the master
microcontroller following the start
bit. The eighth bit of the I

2

C address

packet determines whether the opera-
tion performed against the I

2

C slave is

to be a

read(1) or write(0).

I wanted to keep up with lane num-

bers as well as their corresponding I

2

C

addresses, so my addressing scheme
assigns the microcontroller in lane 1
address 0x18. Lane 2 gets a 0x28
address and so on. Thus, a read of lane
1’s elapsed time would begin with an
I

2

C address of 0x19. A write to the

lane 1 microcontroller would be sig-
naled by 0x18 following the start bit
in the I

2

C address field. Because the

lane microcontroller’s address can be
set via firmware, you can set up any
lane microcontroller to coincide with
any lane on the track.

My Custom Computer Services PIC

compiler handles the I

2

C master chores

handily. The company’s C for PICs sup-
ports standard I

2

C functions such as

i2c_start, i2c_read, i2c_write,
and

i2c_stop. As you can see in

Listing 1, reading and writing in I

2

C

Master mode was straightforward. The
real work had begun when coding the
slave side of the common I

2

C functions.

Fortunately, I had Microchip’s I

2

C

application note (AN734) and the
Philips I

2

C bus specification to draw

from. I used the two documents to port
the AN734 assembler to the C code in
Listing 2. As you can see, there are
only three PIC registers to be con-

Listing 2—

Each lane microcontroller returns 5 bytes of address and timing information after a car passes through

its timing trap. Time passes as two 16-bit words (seconds and milliseconds). The lane address passes as the first
byte. By passing the I

2

C address with the timing data, it’s easy to keep up with which time belongs to which lane.

//Initialize common variables

SSPSTAT = 0x80; //Slew rate disabled for standard speed mode

SSPCON2 = 0x00;

//The code is actually located inside the main() function

//I

2

C Slave receive

#INT_SSP

ssp_interrupt ()

{

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

#bit SMP = SSPSTAT.7 set for standard 100KHz mode

#bit CKE = SSPSTAT.6 set for I

2

C mode

#bit D_A = SSPSTAT.5 data(1) or address(0)

#bit P =

SSPSTAT.4 stop bit detected if set

#bit S =

SSPSTAT.3 start bit detected if set

#bit R_W = SSPSTAT.2 read or write bit

#bit UA =

SSPSTAT.1 update address if set

#bit BF =

SSPSTAT.0 SSPBUF full if set

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

int8 dummy;

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

The I

2

C code below checks for 5 states:

State 1: I

2

C write operation, last byte was an address byte

SSPSTAT bits: S = 1, D_A = 0, R_W = 0, BF = 1

State 2: I

2

C write operation, last byte was a data byte

SSPSTAT bits: S = 1, D_A = 1, R_W = 0, BF = 1

State 3: I

2

C read operation, last byte was an address byte

SSPSTAT bits: S = 1, D_A = 0, R_W = 1, BF = 0

State 4: I

2

C read operation, last byte was a data byte

SSPSTAT bits: S = 1, D_A = 1, R_W = 1, BF = 0

State 5: Slave I

2

C logic reset by NACK from master

SSPSTAT bits: S = 1, D_A = 1, R_W = 0, BF = 0

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

//State 1

if(S && !D_A && !R_W && BF )

dummy = SSPBUF;

//State 2

else if(S && D_A && !R_W && BF )

{

digit = SSPBUF;

update_led = TRUE;

}

//State 3

else if(S && !D_A && R_W && !BF )

{

index = 0x00;

while(BF);

do{

WCOL = 0;

SSPBUF = et[index];

}while(WCOL);

++index;

CKP = 1;

}

//State 4

else if(S && D_A && R_W && !BF )

{

while(BF);

do{

WCOL = 0;

SSPBUF = et[index];

}while(WCOL);

if(++index > 0x04)

index = 0x00;

CKP = 1;

}

//State 5

else if(S && D_A && !R_W && !BF )

index = 0;

}

background image

68

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

cerned with: SSPCON, SSPSTAT, and
SSPBUF. SSPCON determines whether
or not a collision has occurred (

WCOL) and

ensures that you are not stretching the
clock when you shouldn’t be (

CKP = 1).

SSPSTAT provides the status of the
data transfer. SSPBUF is the register
that actually transfers the data.

The PIC’s MSSP does several other

things, including double-buffering I

2

C

data using the SSPSR/SSPBUF register
combination, providing a holding reg-
ister for the slave address, and generat-
ing I

2

C interrupts on start and stop

bits. I’ve used interrupts freely in the
Pinewood Derby computer code to help
keep things simple and organized. Let’s
walk through the I

2

C interrupt routine.

The AN734 assembler breaks the

I

2

C transmission and reception process

down into five states. The only com-
mon factor is that for all the states, the
start condition must be detected (S = 1).
After you have a start bit, you can use
the other bits inside the SSPSTAT reg-
ister to determine which state the I

2

C

transaction is currently in.

Take a look at Listing 1 again.

Putting a number in the lane LED dis-
play (

set_led_i2c function) requires

only four lines of I

2

C C constructs. The

i2c_start function initiates the start
condition and satisfies the S = 1 condi-
tion. Now let’s assume you’re writing
a one to the lane 1 LED display.

After initiating a start condition, the

master microcontroller clocks out the
lane 1 address for an I

2

C master-to-

slave write operation, i2c_write(0x18).
At that point, all of the lane micro-
controllers are listening on the I

2

C

link. The lane 1 microcontroller com-
pares the incoming address with the
address stored in its SSPADD register
and detects a match. The slave’s BF bit
is set, an acknowledge (ACK) pulse is
generated by the lane microcon-
troller’s MSSP hardware, and an SSP
interrupt is generated. The lane 1
microcontroller then enters its SSP
interrupt routine and, using the SSP-
STAT bits, determines that the I

2

C

transaction is in state 1.

The I

2

C state table in Listing 2 tells

you that state 1 is defined as the
reception of an I

2

C address byte. The

BF bit is set, which means the con-
tents of the SSPSR register have been

transferred to the SSPBUF register. To
avoid an overflow condition, the SSPBUF
register must be read even though you
don’t have any use for the address data.

I have already defined an LED seg-

ment map for the Lumex LDS-AA14RI.
A binary 1 will be translated into an
LED display 1 by the lane microcon-
troller. The

i2c_write(0x01) instruc-

tion clocks the binary 1 data to the I

2

C

link. Another SSP interrupt is generat-
ed within the lane 1 microcontroller,
which is then in Slave Receiver mode.
This time the D_A and BF bits are set
indicating that state 2 (a data byte has
been received) has been entered. Again,
SSPBUF is read, but the data (a binary 1)
is read and the LED display update flag is
set. The lane 1 microcontroller processes
the binary 1 after it finishes servicing the
SSP interrupt. The data transfer termi-
nates with an

i2c_stop, which perpet-

uates an I

2

C stop condition.

A similar process is followed when

a lane microcontroller is in Slave
Transmitter mode. The master micro-
controller initiates a start condition
and follows it with a read address
byte, which is the write address incre-
mented by one (0x19 for lane 1). By
incrementing the address byte, the
R_W bit inside the I

2

C address byte is

set. In this mode, the master generates
the I

2

C ACKs and NAKs. Slave

Transmitter (slave read) mode I

2

C

transactions begin at state 3 in the
SSP interrupt service routine.

Note in Listing 2 that the lane micro-

controller must be ready to send the first
byte of data after the ACK following the
address byte. Subsequent bytes of data
are clocked out of the slave-transmitter
microcontroller in state 4 until the mas-
ter clears the R_W byte and generates
a NAK, which is defined as state 5.

CHECKERED FLAG

The beauty of using I

2

C in this proj-

ect is that after the code has been writ-
ten for one lane, you can copy the lane
timer hardware layout and change the
I

2

C address in the source code for each

additional lane. If you have a need for
speed, you may download the Pinewood
Derby computer source code and PCB
layout from the Circuit Cellar ftp site.
The PCB layout is in ExpressPCB format,
and you can simply submit the original

or your customized layout file via the
Internet to get your set of Pinewood
Derby computer PCBs.

I used a PIC in this I

2

C implemen-

tation, but there’s no reason why you
can’t take this idea and use it with any
microcontroller that supports I

2

C in its

hardware. In fact, I

2

C is simple enough

to deploy using only firmware in
microcontrollers that don’t have built-
in MSSP-like hardware. Thanks to the
engineers at Philips Semiconductor,
there’s nothing complicated about
embedding I

2

C.

I

PROJECT FILES

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

SOURCES

UDN2595A and ULN2003A Sink
drivers
Allegro MicroSystems
www.allegromicro.com

Pinewood Derby computer PCB
ExpressPCB
www.expresspcb.com

LDS-AA14RI LED Display
Lumex
www.lumex.com

MPLAB ICE 2000, PIC16F873
Microchip Technology, Inc.
www.microchip.com

PNA 46 02 M Optical detector
Panasonic
www.panasonic.com

RESOURCES

S. Bowling, “AN734: Using the
PICmicro SSP for Slave I

2

C

Communication,” Microchip
Technology, DS00734A, 2000.

Philips Semiconductor, “The I

2

C Bus

Specification,” V. 2.1, January 2000.

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

CANbus

Starter Packs

available for almost

any board format: PCI, ISA, PCMCIA, PC104,
VME, cPCI, etc. with software for most OS’s
inc. all Windows, Linux, QNIX, etc.
CAN/Ethernet bridges, industrial
computing and automation solutions
Industry leaders worldwide trust and
specify Janz AG’s ISO9000 systems.
Janz AG - a leading CANbus supplier.

ALSO:

S C A L A B L E L E D D I S P L A Y P A N E L S , TEMP-HUMIDITY

MONITORS, T H E R M O C O U P L E P . C . A D A P T E R S , ENVIRONMENT

MONITORING SYSTEMS, EDUCATIONAL SCIENCE PROJECTS,

GRAPHICS SOFTARE, AutoCAD PROGRAMMING COURSE, USB-PIC

BOARDS, FLASH PROGRAMMERS - IF YOU DON’T SEE WHAT YOU

NEED MAYBE WE CAN FIND IT FOR YOU? - JUST ASK FOR ALAN!

by

Janz

for

all

computers

Saelig Co. brings to USA unique, easy-to-use control and
instrumentation products from overseas. Customers inc:
Intel, Philips, NEC, Kodak, Nokia, US Military, Microsoft,
Dell, Xerox, Universities, T.I., Harris, Sony, J&J,
Thomson, Sandisk, General Dynamics, H-P/Compaq, e t c .

Industrial PCs

Turn your PC into a high-
speed scope. Sampling
rates up to 100MS/s for sin-
gle shot signals (and up to
5GS/s for repetitive signals)
with 12-bit resolution. With
FREE software, your PC
becomes a powerful 2-chan-
nel scope and spectrum
analyzer.

ADC-212/100

$1090

US232 is a 6ft USB-RS232
self-powered converter
cable which instantly and
reliably solves the problem
of laptops with no serial
ports, or legacy RS232
devices that need to be
updated to USB

IN ONLY 5

MINUTES!

Buy in bulk to

update your products - $39!

"After looking at a number of packages
both large and small we have found

TRAKIT

TM

to be the most cost effective

solution for inventory management in the
manufacturing environment available for
the small to medium size company. It
contains most of the commonly used
features of the larger programs as well as
maintaining the user ease of the smaller
programs. Some of the more advanced
features of Trakit are more successfully
implemented than packages costing
many times more. Better and easier to
use than P&V" (S.P. Ltd)

TRAKIT

manufacturing

- Inventory Management

- Bills of Materials

- Build Schedule

- Sales Orders

- Instant Builds

- Purchase Ordering

- Request for Quote

- Reminders

- Reports

K2

9p-9p self-powered RS-422/485 converter

K3

9p-9p isolated RS-422/485 converter

K3-232

9p-9p isolated RS232 converter

K232-ISOL

25p -25p RS232

K422-ISOL

25p -25p RS422

K485-ISOL

25p -25p RS485

KD485-STD

DINrail-mount

RS-232/485/20mA isolators

KD485-PROG

DINrail-mount

RS-232/485/20mA isolators
C-programmable for protocol/MODbus
conversion. Program to convert custom needs.

USB-485i offers self-
powered USB to RS485
conversion with optical
isolation to 1kV. Baud
rates 184bps - 3Mbps.
Link-selectable half-duplex
mode enables the 485
transmit-buffer when data
ready. Three-point isolated
serial communciations.

200 kS/s 12-bit dual-channel USB scope adapter for
PC. Unique software looks like a “Digital Scope” right
on your PC screen! Built-in
squarewave generator.
Weighs less than 8oz so
you can take it anywhere.
Only $189!! For details:
www.usb-instruments.com

USB protocol analyzer displays USB packets sent,
decodes descriptors, detects errors in peripherals or
drivers and measures their performance.
Ideal for anyone developing
USB peripherals,
embedded soft-
ware or drivers.
Software is easy
to use - learn all
about USB. $799!

Make PCs talk I2C easily with this industry-standard
card, available in 2 - 6V bus version for low-volt I2C
systems. Optional WINI2C/PCI software gives you a
windows-interface to develop
and debug I2C bus systems.
Monitor software lets you
transparently monitor I2C bus
activity .

NEW - USB VERSION

UCA93LV: 400kHz monitoring!

Build a custom PCMCIA or CF
card datalogger or controller

- quickly!

Wizard high-level

software completes your
project in hours not weeks.
Store GPS or CANbus data.
TDS2020F is the low-power
controller of choice for sure
LONGEVITY - this one won’t
disappear like so many other
obsolete boards. Ask us why!

Join all the industry leaders who are using this easy-use
USB ic. Single chip USB-232 solution comes with all
Windows/Mac/Linux drivers. UART ASIC-based so no
software development is needed!

Euroquartz is one Europe’s largest manufacturers and
supplier of quartz crystals, oscillators, filters and
frequency-related products. They design & manufacture
a comprehensive range of frequency-related components
including custom-made filters, high
reliability oscillators for defence
applications and radiation tolerant
oscillators for high-altitude apps.
EQ-HM oscillators reduce EMI using
Spread Spectrum Technology
to slowly shift center frequency.

Easily construct small control systems communicating
through Intranet/Internet. BIT2000 is the ideal solution
for process control, building
monitoring, data logging,
alarm systems and other
industrial uses. BIT2000
can communicate with
many types of equipment
through the fast multidrop
RS485 based bus and a
standard RS232 serial port.

At last!

This tiny pocketable USB-based and USB-

powered device is the answer to your need for an eco-
nomical logic analyzer that you can take anywhere.
About the size of a small matchbox, ANT8 can sample
eight channels at up to 500 million samples-per-sec.
ANT8 offers simple or complex
triggering, upgradeable soft-
ware. View the captured eight
digital channel traces on your
PC. Save or print screens for
reference or labnotes! $199!

Manufacturing Software

RS485 factory control

Crystals & Oscillators

Easy USB in one IC!

Basic modules

No USB knowledge required! Byte-
wide ic version FT245BM too!
FT232BM is in the ready-made
US232 cable (USB-serial) - see top
right panel. Instantly update your
legacy serial RS232 products!

PC Scope Adapters

RS232<>422/485

I2C for PCs

Datalogger/Controller

CANbus Cards

Standalone Dataloggers

SM PCB Adapters

USB PC Scope

USB Bus Analyzer

Logic Analyzer

Isolated USB<>RS485

USB-Serial Adapters

BASIC Tigers

are tiny multitasking

modules for quick project development.
Powerful features and low prices make
Tigers a number one choice: super-fast
development cycle, high reliability prod-
ucts, >100,000 instructions/s, up to 38 I/O
lines, A/D, D/A, I2C, SPI, text/graphic LCD
interface.

NOW - SmartCard Interface!

iCOM200

ready-made controller with LCD

and keypad.

Touch240

controller - with

touchpad and LCD display.

Self-contained in 2” x 3” box, these
battery-powered standalone analog
and digital loggers store events,
voltages, currents or pressures for
days to weeks. Download detailed
time and data via serial port and
review results with graphic software
or upload to an Excel spreadsheet.
More details at - www.abidata.be

These SM miniboards have two foot-
prints on either side, allowing you to
use ultra fine pitch SMD components
with a more useful array of 0.1"
spaced holes. 1-to-1 pinout for circuit
probing during design and testing.
Each unique miniboard (pat-pending)
can fit several different devices.
More at www.omega-research.co.uk

Ruggedized Industrial ATX PC systems to suit almost
any budget or PC application.
Easy maintenance, economy
and reliability. $899 version
features AMD Athlon XP1700,
shock-mounted 40GB harddrive.
Lockable front doors prevent
tampering. Full Burn-in and
Test Report with every system.
LED system status indicators.
CE EMC certified. More info at www.amplicon.co.uk

S

A

E

L

I

G

B

R

I

N

G

S

Y

O

U

S

O

L

U

T

I

O

N

S

!

Saelig

Co. Inc.

585-425-3753 • fax: -3835

www.saelig.com • info@saelig.com

background image

70

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

T

ext-to-speech technology enables

the visually handicapped to communi-
cate via e-mail complete with spam.
For the handicapped with plenty to
say (e.g., Stephen Hawking), the tech-
nology provides a voice to be heard.

For many of you, the excitement of

having your computer talk to you has
waned. Could it be the lack of human
feeling these robotic regurgitation
devices bring to mind? For those of
you familiar with Star Trek, the com-
puter aboard the Starship Enterprise
has a woman’s voice. Majel Barrett—
wife of the show’s creator, Gene
Roddenberry—continues to play the
voice of the computer. There is some-
thing soothing about a woman’s voice
that makes me think of mom. What
could be more comforting than to
know mom is there?

My PC efficiently turns text into

speech. Keep in mind that it takes a
lot of horsepower to do so; conse-
quently, it won’t fit well in an embed-
ded environment, especially if your
plan is to share CPU time. You may
find your application grinding to a halt.

Phoneme synthesizers were the first

attempt to make speech output avail-
able as a peripheral device. Phonemes
are the small sounds you make when
interpreting the letters, or combina-
tion of letters, in a word. The air from
your lungs passing through your vocal
cords makes sounds, which, like let-
ters, can be divided into two groups,
consonants and vowels. The former

important is how certain combina-
tions of letters affect the sound. Thus,
a single phonetic symbol may reflect
one or more letters (e.g., the “t” in
“ten” versus the “t” in “thin”).
Consonants aren’t the only sounds
that can change with respect to their
neighbors. Vowel sounds are also affect-
ed, as in the “oo” sound in “book” ver-
sus “boot.” This is one reason English
is not an easy language to learn.

A phoneme synthesizer allows you

to string phonemes together by
inputting the phonetic symbols that
are used to pronounce a specific

Next-Generation Text to Speech

FROM THE BENCH by Jeff

Bachiochi

are created when your tongue or lips
interrupt the airflow (e.g., the “t” and
“p” in the word “tip”). Vowels are not
made in the same fashion. There are
26 letters in the English alphabet, six
vowels and 21 consonants. Note that
I’ve grouped the letter “y” with both
vowels and consonants.

Phonetics is the study of the sounds

of a spoken language. A phonetic
alphabet may have 17 vowels and 24
consonants. What’s with that? Because
phonetics is focused on sounds, it isn’t
necessarily concerned with how a par-
ticular letter sounds. Instead, what’s

Text-to-speech technology can be both useful and exciting to implement. Now you can bring
the technology to your next embedded project with the Winbond WTS701, and a little assis-
tance from Jeff, of course. In this column, he explains everything you need to know to begin
the translation process.

SPI Interface

*CS

*SS

MOSI

MISO

SCLK

*R/B

*INT

Clock

generation

High-voltage

generation

Reference

generation

XTAL1

XTAL2

AUX
amp

AUXIN

MLS Control

logic

MLS

Phoneme

memory

Analog signal

conditioning

Power conditioning

V

CCA

V

SSA

V

SSA

V

SSD

V

SSD

V

CCD

V

CCD

ATT CAP

Flash

codestore

memory

(ROM)

RAM

Processor

AUX

OUT

amp

Spkr.

amp

AUXOUT

SP+

SP–

13-bit CODEC

linear/2’s complement

VFS
VDX
VCLK

RESET

Figure 1—

The WTS701 processor is combined with flash memory and analog memory (MLS) to create a single-

chip text-to-speech converter.

Winbond Makes Strides with the WTS701

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

71

make high-quality speech from con-
catenated human speech samples.
Thus, the Winbond WTS701 single-
chip text-to-speech processor was born.

The WTS701 combines a text

processor with an SPI interface, analog
phoneme storage, and an audio ampli-
fier in a single chip (56-pin TSOP
package). Let’s see how the items in
Figure 1 work together to perform a
complete text-to-speech peripheral.

WTS701

The processor runs on a 24.576-MHz

clock from an external crystal source.
All communication occurs through an
SPI port with additional ready/busy
and interrupt outputs. Execution code
is stored in the flash memory. All com-
mands are 2-byte (or multiples of two)
transfers. The SPI interface is bidirec-
tional, so for each command received, a
2-byte status code is sent.

The application code has five states:

Reset, Power Down, Idle, Convert,
and Wait (see Figure 2). Each command
that’s interpreted either changes a
parameter or moves between states.
All speech text is handled in the
Convert state. Sound bits are stored
in the multilevel storage (MLS)
phoneme memory. The concatenated
phoneme audio passes through a con-
ditioning low-pass filter and digital
volume control before going to a
speaker amplifier, auxiliary output
amplifier, and a 13-bit CODEC. The
WTS701 also has an auxiliary audio
input that can be routed through the
signal conditioner.

Speech creation has three

basic processes (see Figure 3).
The first process, text normal-
ization, ensures the text is in
a pronounceable form. This
means expanding abbreviations
and translating numerical
strings. An editable exception
list allows you to define how
an abbreviation or special
character (or group of charac-
ters) is pronounced. The words-
to-phoneme phase translates
each word to its phoneme

equivalent using a rule/excep-
tion-based process. Finally, the
speech mapper chooses the
most appropriate phonetic

speech blocks by breaking the pho-
netic word into pieces. The inventory
is searched for available pieces. If large
blocks cannot be matched, the block is
broken down into smaller pieces. The
idea is that it’s best to use larger mul-
tiple phoneme blocks to reproduce the
highest-quality output.

WTS701 COMMANDS

You must communicate with the

WTS701 via the SPI interface. This
consists of a SCLK and master out
slave in (MOSI) and master in slave
out (MISO) datapaths. You are the
master and supply the SCLK and
MOSI outputs to the WTS701. The
slave (WTS701) supplies the MISO
datastream to the master.

word. Outputting speech may
be a simple look-up table of
prestored phonetic word sym-
bols that you can send to the
phonetic synthesizer (see
Table 1).

Building an extensive word

library is more than tedious; it
requires great gobs of memory.
Enter the rule-based phonetic
word builder that gives life to
the text-to-speech synthesizer.
Yet, it all boils down to the
phonemes you’re working
with. You can form them
through formant frequency,
bandwidth, and voicing, or by
imitating the vocal tract with
position and movement parameters.
You can also concatenate prerecord-
ed phonemes.

WINBOND

If you’ve been reading my columns,

you’re probably familiar with
Winbond and its line of ISD devices.
These are used as solid-state
recorders. The ability to record and
playback the analog from any point
gives Winbond the tool necessary to

Table 1—

Study this chart to learn how vowel and con-

sonant sounds are identified. Each phoneme corre-
sponds to a letter or combination of letters of the
alphabet, which is interpreted as a unique sound.

Vowels

Consonants

Phoneme Example Phoneme

Example

i

b

eat

p

pet

I

b

it

t

ten

e

b

ait

k

kit

E

b

et

b

bet

@

b

at

d

debt

u

b

oot

g

get

U

b

ook

h

hat

o

b

oat

f

fat

c

b

ought

T

thing

a

B

ob

D

that

A

b

ut

s

sat

R

b

urr

S

shut

O

b

oy

v

vat

Y

b

uy

z

zoo

W

d

own

Z

a

zure

x

about

y

you

X

ros

es

w

wit

r

rent

l

let

m

met

n

net

G

si

ng

C

church

J

judge

Reset

V

CC

Applied

Power Down

Wait

Idle

Convert

Convert

Convert

Hard reset

Idle

PWUP

PWDN, Soft reset

Soft reset, PWDN

Soft reset

PWDN

Hard reset

Stop
finish
finish word
conversion finished

Figure 2—

The WTS701 text-to-speech chip has various states of operation.

After resetting, the chip must receive initialization in Power Down state
before it enters the Idle state, where text-to-speech conversion takes place
(Convert state and Wait state).

Text normalization

Words to phoneme

Phoneme mapper

MLS

Memory

Digital
output

Analog

output

Serial text,

symbols, and

control

WTS701

Speech

Figure 3—

Text is converted in phonemes via a three-

step process. First, the text is analyzed, and substitu-
tions are made (i.e., abbreviations) where necessary.
Next, the text is broken down into the largest possible
phoneme blocks. Finally, the corresponding prerecord-
ed analog phoneme blocks output the concatenated
sounds producing the spoken text.

background image

72

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Additionally, the WTS701 has a slave
select (SSB) chip select and reset input,
as well as ready/*busy (R/*B) and
interrupt (*INT) outputs.

One advantage to using separate

datapaths is that data passes between
devices in both directions at the same
time via the SCLK. The WTS701 uses
a minimum of a 2-byte transaction for
each command. A 2-byte command is
used so a data value can be passed in
the same transaction, and 11 bits of
status can be returned for each com-
mand (see Figure 4).

A number of status bits begin with

“I”; these are interrupt flags that can
indicate the state of various enabled
interrupt activities. The
*INT output can be used by
the master as an external
interrupt, or the status bits
can be monitored by the
application. Similarly, the
R/*B output can be used or
the R/B bit monitored.

At power-up, the

WTS701 looks for some
information before it can
be used. Specifically, it
needs to know what speed
crystal is attached (com-
mand

SCLC). After the

command is sent, the
WTS701 is in Power Down
mode during which speech
is not available (while RDY
bit = 0). This is illustrated
in Figure 2. The power-up
command allows the
WTS701 to enter Idle mode
and prepare for speech
(command

PWUP).

Text can be transferred

using the convert com-
mand (

CONV). The FIFO

buffer holds 256 characters.
The BFUL bit is set when
this buffer is full. If more
text needs to be sent to the
WTS701, you must end the
command and wait until
the BFUL bit is cleared
(i.e., the buffer has emptied
to half full). After the BFUL
bit is cleared, another con-
vert command can be sent
with more text. Following
the transmission of the

mand and data byte. These bytes are
passed to the FIFO buffer. The status
must be monitored to prevent data
overflow. Class 3 commands have to do
with the WTS701 returning requested
data. Status must be monitored after
every two bytes of the transmission,
because the WTS701 may need addi-
tional time to access extra data.

Commands have four types of trans-

actions. Class 0 and 1 commands use
the type 1 format (2-byte commands)
and R/*B will never be active. Type 2
commands are 4 bytes in length. They
return 2 bytes of data and R/*B will
never be active.

Type 3 commands are used to send

data to the WTS701. Data
follows the first 2-byte
command/data transaction.
The status must be moni-
tored after each 2-byte
transaction to prevent data
overflow. Type 4 com-
mands are used to receive
data from the WTS701.
Again, data follows the
first 2-byte command/data
transaction. The status
must be monitored after
each 2-byte transaction to
allow the WTS701 to
access the requested data.
Table 2 lists the available
commands for communica-
tion with the WTS701.

SPI INTERFACE

If you want to add this

text-to-speech synthesizer
to your embedded project,
try the SPI interface in
Figure 5. On the other
hand, if you want to add
this as a peripheral to a fin-
ished product—or maybe
through a printer port,
RS-232 serial, I

2

C, or other

interface—you can add a
micro to the front end to
translate between inter-
faces (see Figure 6).

Although this design

incorporates a number of
different interfaces, you
can save a few bucks by
leaving off those parts that
support the interfaces you

text, the finish command instructs the
WTS701 to begin speech output (com-
mand 0x4C–FIN).

Class and type describe command

transactions. The upper 2 bits of the
command indicate the class (0
through 3). Class 0 commands are
2 bytes (command and data byte) and
executed independently of the state
of the WTS701. They will be execut-
ed even if the WTS701 is busy or
powered down. Class 1 commands
are 2-byte commands similar to
Class 0, except they cannot be sent in
Power Down mode.

Class 2 commands have additional

data bytes following the initial com-

Status commands

Opcode Mnemonic

Class Type

Function

0x04

RDST

0

2

Read Status register

0x06

RINT

0

2

Read Interrupt register

0x12

RVER

0

2

Device version

System commands

0x20

PWUP

0

1

Power up

0x40

PWDN

1

1

Power down

0x10

RST

0

1

Reset

0x57

IDLE

1

1

Go idle

Synthesis commands

0x81

CONV

2

3

Start converting

0x49

PAUS

1

1

Pause conversion

0x4A

RES

1

1

Resume conversion

0x4B

ST

1

1

Stop conversion

0x4D

FINW

1

1

Finish word

0x4C

FIN

1

1

Finish buffer

0x53

VLUP

1

1

Volume up

0x54

VLDN

1

1

Volume down

0x55

SPUP

1

1

Speed up conversion

0x56

SPDN

1

1

Slow down conversion

Configuration commands

0xC0

RREG

3

4

Read Configuration register

0x4E

SCOM

1

1

COM Configuration register

0x4F

SCOD

1

1

CODEC Configuration register

0x50

SAUD

1

1

AUDIO Configuration register

0x51

SVOL

1

1

VOL Configuration register

0x52

SSPD

1

1

SPEED Configuration register

0x14

SCLC

1

1

CLC (Clock) Configuration

0x77

SPTC

1

1

Set speech pitch

Customization commands

0xC8

ABBR_NUM

3

4

Get number of abbreviation entries

0xC9

ABBR_RD

3

4

Read abbreviation table

0xC7

ABBR_MEM

3

4

Get number of free bytes

0xAF

ABBR_ADD

2

3

Add abbreviation entry

0x83

ABBR_DEL

2

1

Delete abbreviation entry

0x0C

ENTER_RRSM 0

1

Swap memory

Table 2—

The WTS701 recognizes a number of command opcodes sent via the SPI inter-

face. The commands allow text-to-speech conversion and speech-parameter modification.

background image

retool with intelligence

September 15 – 18, 2003

Hynes Convention Center
Boston, MA

Conference Sponsors

FREE

Exhibits Pass

$35 value

Save up to $100

Register by September 11th

To register or to view a complete list
of courses and events, visit:

embedded.com/esc

Source Code: MKL

Be sure to use this source

code when registering

> Meet with more than 120 leading vendors

The Boston exhibit floor is your opportunity to
meet with embedded vendors, preview exciting
innovations, and catch up with what's going on
in the embedded industry. See the industry giants
and innovative up-and-comers in person and talk
with field application engineers to get answers to
your toughest design questions.

> NEW Flexible Conference Packages

The Embedded Systems Conference Boston now
offers you more flexibility than ever before with
new customizable 1 to 4-day conference packages.
Choose the 4-Day VIP package to save hundreds
of dollars while gaining new skills and techniques.

What’s New for Boston 2003:

37 industry experts sharing their expertise
in 78 classes and full-day tutorials at the
East Coast’s premier event dedicated to
processor-based design

background image
background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

75

don’t need. Winbond reprogram-
ming supports (for its demo
board) functions through an SPI
interface using the PC’s parallel
port. I added the Winbond inter-
face to allow those of you who
are only buying a chip to experi-
ment with the ability to repro-
gram the chip to try both the
male and female speaking voices
(although you can buy it with
either one preprogrammed).

The interface requires a level

translator to go from the 5-V
parallel interface to the WTS701,
which operates at 3 V, and a translator
to go from 3 to 5 V. Using gates with
three-state output enables, these can
be disabled with a single jumper. They
need to be disabled when other cir-
cuitry is used for normal text-to-
speech operations.

A parallel port connection was

already being used, so it only made
sense to allow the WTS701 to receive
text from the parallel port (printer
output). This required not only a
microprocessor for translation but
also an extra logic chip for insurance.
The printer port checks a printer
busy/*ready control line before plac-
ing data on its byte-wide outputs.

After the data is available, the printer
port drops the strobe line for approxi-
mately 5 µs and then gets ready to
send the next data byte. If the printer
needs time for processing, it can sig-
nal busy to the printer port and get it
to wait. Because this project’s parallel
interface wants to look like a printer,
it must be able to grab data when it
becomes available and, if necessary,
signal to hold up future data.

The 4-MHz part I used has a 1-µs

instruction time. The interrupt laten-
cy is approximately four instruction
cycles, which means that before I can
do anything about it (i.e., start execut-
ing interrupt code), 4 µs could be
gone. I don’t know how long the

printer port will give me to sig-
nal that I am busy, so I could
miss the next data byte. An
option may be to use a faster
clock rate or to implement a
simple external latch to auto-
matically signal a busy state.

The 74HCT73 is a JK flip-

flop with a negative-edge trig-
ger (see Figure 6). The falling
edge of the printer port strobe

sets the Q output high; the J
and K inputs are high and low,
respectively. The Q output is

the busy control signal to the printer
port. The microcontroller can clear
the Q output by placing a low on the
preset input, which allows the micro
to clear the busy signal to the printer
port. The microcontroller can take
its time processing the data without
having to worry about sending a busy
signal to the printer port; it has an
asynchronous parallel slave port,
which can automatically latch in
data. Although this can assure that
the data is read correctly from the
parallel port, it’s interrupt still has
the same latency and doesn’t help
raising the busy signal in time to
ensure no data loss.

Setting up an RS-232 interface is

Figure 5—

The WTS701 is a 56-pin TSOP package that requires a minimum of external components for operation. It operates on 2.7 to 3.3 VDC and has 5-V tolerant inputs.

An output amplifier will directly drive an 8-

speaker.

7 6 5 4 3 2 1 0 f e d c b a 9 8

SSB

Command byte

Command data byte

SCLK

0

0

0

0

0

0

0

MOSI

MISO

ICNT

IB

UFI

ICNV

CNVT

COD

BFUL

BEMP

R/B

RD

Y

IABB

ICMD

Figure 4—

Basic communication occurs through a 2-byte SPI format.

Output data from a host consists of a command byte and optional data
byte. Meanwhile, input data containing the WTS701’s status information
is clocked in the host.

background image

76

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

less complicated. Hardware handshak-
ing can be implemented using
RTS/CTS control signals. Software
handshaking can be employed within
the application. A MAX232 provides
level translation for RX and TX in
addition to RTS and CTS.

You may also use the processor for

I

2

C communication. Although the

throughput isn’t simply data, the com-
munication interface allows you to
easily send control information as
well as text. Although this provides
flexibility, normal text conversion does
not require the tweaking of control
parameters; it allows parallel and serial
ports to simply serve text. An I

2

C inter-

face may have direct control over any of

the WTS701 parameters in addition to
text conversion. Basically, it all becomes
a simple exercise in programming.

In this project, treating the WTS701

as a registered I

2

C interface allows you

to control the speed, pitch, and volume
of the conversion output. Although it
may sound like a great feature, it
doesn’t enhance the quality of the
speech output. The best improve-
ments in quality come by altering the
spelling of the text that’s being con-
verted, which forces a change in pro-
nunciation.

Pronunciation can be permanently

(sort of) altered by adding entries to
the abbreviation table. Entries in this
table allow alternate pronunciations

whenever the WTS701 comes across
particular sequences of letters.
Usually, it is used for recognizing
abbreviations as their unabbreviated
pronunciations, but it also can be
used to correct a mispronounced
word. Another way to break the rules
is to use phonetic spelling. Whenever
the control character 0x10 is found
in the text, the WTS701 goes into
Phonetic mode for the next word
(see Table 1).

POWER THE PROJECT

At power-up, the microcontroller

is responsible for initializing the
WTS701. The WTS701’s clock must
be told which crystal is connected.

Figure 6—

I used a PIC16F874A as the interfacing microcontroller for this project. There are a number of alternate interfaces to the real world including RS-232 serial, parallel

port, I

2

C, and USB. My code implements a simple serial and parallel interface. USB requires a PIC16C765 processor. The interface also supports Winbond’s bit-banging PC

parallel port interface by connecting pins 1 and 2 of JP1. (The microcontroller is not needed for this interface.)

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

77

PROJECT FILES

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

SOURCES

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

WTS701 Single-chip text-to-speech IC
Winbond Electronics Corp. America
(408) 943-6666
www.winbond.com

All of its timing is based on this data.
The CLC command sets this, and it
is the only command that needs to be
initialized. Commands that have
default data do not need initializa-
tion. The

PWUP command moves the

WTS701 out of Low Power mode and
prepares it to receive text. A short
message, such as “Ready,” can be
sent to the WTS701 to alert you that
all is well.

To help relieve the potential bot-

tleneck of endless text, I chose to
filter the text received before passing
it on to the WTS701. Most control
characters, and those with the upper
bit set, are tossed into the bit buck-
et. Any carriage return or end-of-sen-
tence punctuation begins a conver-
sion process. This is accomplished
by sending the

FIN command after

the text.

The microcontroller’s buffer is

considerably smaller than the
WTS701. If it’s filled, the contents
are wrapped in a

CONV command

and sent to the WTS701. The
WTS701 concatenates

CONV text

until receiving any of the termina-
tion commands (i.e.,

FIN).

WANT TO CONVERT?

Winbond has applied its MLS stor-

age technology to create the first sin-
gle-chip text-to-speech IC. When I
started this project, I had to ask for a
few samples because they were not in
distribution. Now you can buy it
from Digikey. (You must have the
proper tools and a steady hand to sol-
der the WTS701 with approximately
five leads per 0.10

″.)

Although not everyone wants their

technology talking to them, I think
there are many applications in which
the spoken word is advantageous.
Such applications are not only for the
visually handicapped; you’ll find
them useful when you’re multitask-
ing, particularly when issues of safety
are of concern.

Visit Winbond’s web site to learn

more about actual text conversions.
After learning about all of the
improvements in text-to-speech tech-
nology, you will probably ask your-

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.

self, how can I work this into my next
design? You won’t be so surprised
when you hear the answer.

I

background image

78

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

I

f the number of meetings I attended

at the recent Embedded System
Conference in San Francisco is any
indication, the embedded market is
faring better than most. Indeed,
although not exactly on a Moore’s Law
slope, I had more powwows and presen-
tations than ever. And it wasn’t as
though I was scraping the bottom of the
barrel. (“Of course I’d love to hear about
your new line of heat-shrink tubing.”)

Sure, with nearly 300 booths, there

was plenty of stuff I was not that inter-
ested in, not to mention outfits that sim-
ply don’t get it about “embedded,” the
term being merely the latest marketing
flavor of the month handed down from
the management minions on high. But
overall, I found plenty of major players
rolling out rather compelling technology.

Doing meetings from dawn to dusk

isn’t easy, not to mention the working
lunches, dinners, and receptions. Coffee,
scotch, and Tums are what you’ll find
in my ESC survival kit. Yeah, it’s an
ugly job, but somebody’s got to do it.
Herewith, a distillation of three days of
meetings and 50 lbs of press kits minus
the sore feet, queasy stomach, and
pitch fatigue. My pain is your gain.

WORKING THE ’NET PART DEUX

Last February, I examined a lineup

of boards and modules designed to
make adding ’Net features to your
embedded application quick, easy, and
cheap (“Working the ’Net,” Circuit
Cellar

151). Given the market interest

and pace of technology, it’s no surprise
the ink was hardly dry on that story
when the next round of latest and
greatest ’Net gadgets made their debut
at ESC.

Chip), the hardwired TCP/IP protocol
processor from Wiznet? I covered this
unique take on the embedded Internet
subject back in 2002 (“I-Way the Hard
Way,” Circuit Cellar 142). Although
intriguing from a technical perspective,
I cautioned that business issues make
it tough for a new kid on the block to
break into the market against a myriad
of larger well-established competitors.

Not that anyone takes my advice,

but at the conference, Wiznet and
Atmel announced a joint i2Chip and
flash memory ’51 marketing program.
Atmel is a major player in the microcon-
troller market, which at least gives the
i2Chip a chance to get in the door. This
deal naturally raises the question, will
we see Wiznet’s network hardware inte-
grated on an MCU chip? Stay tuned.

LCD

Although not exactly on a DRAM

pace, LCDs are slowly but surely
tracking down the price/performance
curve. On the PC front, you can see it
in the proliferation of the 15

″ through

19

″ (and beyond) flat panels that are

emerging as the desktop display of
choice. Prices are falling steadily, and
it seems to be only a matter of time
before LCDs put the old stalwart CRT
out to pasture, or at least relegate it to
the bargain bin.

The boost in LCD action at the high-

end is trickling down to embedded apps
as well. Meanwhile, from the bottom
up, PDAs and other portable gadgets are
assuring a healthy supply of quarter-
VGA, or QVGA, panels (i.e., 240 × 320).

There are numerous ways to put a

pretty face on your product. Besides a
variety of display options, alternatives

ESCape to SF

SILICON UPDATE

by Tom Cantrell

For you car nuts out there, remember

Carrol Shelby’s Cobra from the ’50s? The
recipe for success was simple. Design a
small two-seater with a tip of the hat
to English sports cars like the Triumph
and MG, except stick a really big V8
under the hood instead of a wimpy four-
banger. Ah, the smell of burning rubber.

One of the best photo ops comes

from Digi International, who put their
NetSilicon subsidiary’s latest NS7520
chip (“E-Chips,” Circuit Cellar 153) to
good use in the Digi Connect ME
embedded device server (see Photo 1).
The device represents a breakthrough
in miniaturization, packing a 32-bit
ARM processor, 10/100 Ethernet,
2 MB of flash memory, and 8 MB of
RAM in an RJ-45 connector. Like the
Cobra, that’s a lot of horsepower in a
small chassis (less than a cubic inch).

Not to be outdone, Lantronix intro-

duced its own RJ-45 two-seater, the
X-Port, although it’s a lighter on
horsepower with a 16-bit ’x86 DSTni-
LX chip, 512-KB flash memory, and
256-KB RAM. Think 289 versus 427,
but it’s still a Cobra.

The new NetBurner board deserves

mention as one of the first platforms
using the new Motorola ’5282 chip,
which is arguably the premier E-Chip
on the block with practically every-
thing built-in (see Photo 2). Although
it isn’t as downsized as the Digi or
Lantronix units, keep in mind this is
really a fully loaded SBC with a whop-
ping 100 pins of I/O including 10/100
Ethernet, CAN 2.0, timers, PWM,
UARTs, SPI, I

2

C, and even eight 10-bit

A/D channels.

Remember i2Chip (now known as

the “iinChip,” as in Internet Inside

At the 2003 Embedded Systems Conference in San Francisco, the heavy hitters displayed
their latest and greatest products. Here, Tom highlights some compelling new technologies.

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

79

offer various make-versus-buy trade-offs.

The quickest and easiest solution is

to go with a fully integrated display
such as the aptly named Easy GUI
modules from Amulet Technology,
which I first covered back in July 2001
(“Liquid Crystal Delight,” Circuit
Cellar

132). These handy gadgets com-

bine a monochrome QVGA-class
touchscreen display with a prepro-
grammed controller chip and, most
notably, a bunch of software that makes
it easy to customize the display, includ-
ing the use of GIF and JPG graphics.

Beyond an expanded lineup of sup-

ported displays and a new distribution
agreement with Mouser Electronics,
Amulet also announced at ESC mod-
ules with Ethernet expansion options
using the aforementioned Lantronix
X-Port as well as a similar serial-to-
Ethernet adapter, the SocketEthernetIP,
from Multi-Tech Systems (see Photo 3).

Another variation on the keep-it-

simple theme was the announcement
that Casio will offer LCD panels fea-
turing Triscend’s E5 chip—an 8051-
based MCU with integrated FPGA—
taking advantage of the latter’s royal-
ty-free LCD controller IP (“SoC Hop:
The Sequel,” Circuit Cellar 140). The
four displays mentioned in the release
include color and black and white in
sizes and resolutions ranging from
2.7

″, 160 × 160 to 5.1″, 240 × 320.

Besides handling the display basics,

the Triscend package includes a soft-
ware library with drivers for high-
level graphics and text functions, as
well as routines for handling a resistive
touchscreen. The software is written
in C, and source code is provided.

Even a small LCD can upgrade an oth-

erwise mute design. Consider the cute
little Butterfly Atmel designed to high-

light the built-in LCD controller on its
latest Mega 169 AVR MCU (see Photo 4).
Give the gadget brownie points for
including bells and whistles such as
temperature and light sensors and a nifty
four-quadrant joystick. The Butterfly can
even play simple tunes via a small audio
annunciator. “Für Elise” anyone?

Despite the whimsy, Butterfly is actu-

ally useful as an evaluation and develop-
ment kit. All the key signals are brought
out to 0.1

″ center header pads, and the

design supports the chip’s various pro-
gramming modes (i.e., in-system, JTAG,
etc.). It also comes preloaded with boot
routines that work in conjunction with
the AVR Studio toolchain for down-
loading and debugging user code.

No power supply is needed. Butterfly

comes with a relatively large coin cell
battery. It should last awhile (Atmel
says seven years), considering that the
chip consumes only 20 µA running off
a 32-kHz watch crystal. Butterfly won’t
drain your battery, and at only $19.99,
it won’t drain your budget either.

DSP IS DEAD?

This topic is kind of the Lifetime

Employment Act for tech pundits. Here
in the pages of Circuit Cellar, I and oth-
ers have hit on it going back more than
a decade (e.g., Mike Smith, “To DSP
or Not to DSP: Will a RISC Chip do it
Better?” Circuit Cellar 28). And just
guess what the topic was for the round-
table debate at the recent Embedded
Processor Forum, “The Death of the
DSP,” which was sponsored by, er,
MIPS. Why am I not surprised?

Traditionally, the argument has been

about the underlying processor archi-
tecture à la RISC versus DSP. From an

architectural perspective, I think it’s
clear that DSPs aren’t dead, especially
for the high-end performance-at-any-
price chips that handle the toughest
rocket science-type apps.

At the show, I chatted with Markus

Levy from the Embedded Microproces-
sor Benchmark Consortium (EEMBC).
The EEMBC folks have done good
work bringing some integrity to a
process that’s historically all too prone
to funny business. Checking the freely
accessible scores on their web site
sheds some interesting light on the
“DSP RIP?” issue.

Figure 1 shows results comparing a

high-end DSP—the latest C6x hot rod
from TI and a PowerPC processor (the
MPC7455) from Motorola. A key point
revolves around the difference between
so-called “out of box” and “optimized”
results. The former simply run the stan-
dard benchmark C programs through a
compiler and accept whatever code gets
spit out. The latter feature hand-opti-
mization such as reorganizing the C code
or, dare I say, writing assembly language.

Notice that the two chips’ out-of-

box scores, after compensating for dif-
ferent clock rates, are about the same.
But now check the optimized scores.
The TI chip that just managed to keep
pace with the Power-PC out of box is
suddenly a full five times faster!

Clearly, at least at the high-end,

reports of the demise of DSP (not to
mention assembly language) have been
exaggerated. But the trend with mid-
range parts tells a different tale. There,
the technology and marketing pitch has
“micro,” not “DSP,” written all over it.

Analog Devices issued a press

release announcing their Blackfin DSP
is now supported with the popular

Photo 2—

Question: What I/O feature doesn’t the

NetBurner Mod5282 include? Answer: The kitchen sink.

Photo 1—

Looks like the wire is wagging the dog.

Behind a mild-mannered RJ-45 jack, the Digi Connect
ME packs an entire ARM-based network processor.

Photo 3—

Notice the other RJ-45-on-steroids solution,

the Lantronix X-Port, installed on one of the latest
EasyGUI graphics LCD modules from Amulet.

background image

80

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Green Hills toolchain—just like
PowerPC, MIPS, ARM, and so on.

And really just what is the differ-

ence between the Motorola 56F800
lineup of “hybrid” controllers and reg-
ular controllers? It has an MCU-friend-
ly instruction set, built-in flash memo-
ry, and all the usual suspects when it
comes to I/O (UART, timers, etc.), not
to mention the same CodeWarrior tool-
chain as a lot of other MCUs. Maybe
the ad campaign should be “Don’t hate
me be because I can multiply.”

Meanwhile, there are ’51s from both

TI and Analog with built-in 24-bit
A/D converters. Who deserves the
“signal processing” moniker more?

It’s a semantics game. Digital signal

processors may not be dead,
but they are increasingly
being assimilated, at least in
the sense that every proces-
sor processes signals. Some
just do it faster than others
or have more tailored mar-
keting and support. Ah, but
digital signal processing—
now that’s another story.

One announcement by an

outfit known as Nallatech
brought it home to me. In
conjunction with Xilinx and
others, they’re seeing a world
in which designs that might
otherwise have been consid-
ered in the realm of DSPs are
finding their way into FPGAs.
Perhaps even more important-
ly, instead of the programming
language a processor uses,
they report increasing use of
tools like MATLAB and
Simulink instead of C or
assembly language.

So maybe the argument is less about

what qualifies as a digital signal proces-
sor, and the real question is, what’s
the best way to design and implement
digital signal processing apps?

Throw in the analog FPGAs from the

likes of Lattice and Anadigm and the sit-
uation gets even murkier (see Photo 5).
They aren’t processors, and they aren’t
digital per se, but they target exactly the
same functions (e.g., filters, multiply,
add, etc.) as a DSP. I look forward to
covering the subject again…and again.

BIGGER…

Not all the important developments in

the embedded biz come out of the lab.
Sometimes, for good or bad, it’s an MBA
rather than an EE behind the headlines.

Enter Renesas, a company with a new

name on the releases, but a lot of proven
technology under the hood. Some folks
have trouble pronouncing it, but it
helps to remember that it stands for
Renaissance Semiconductor for
Advanced Solutions. I say “Renaissance”
without the trailing “n” sound.

Whatever you call them, this joint

venture (really more like a merger)
between the semiconductor arms of
Hitachi and Mitsubishi is a pretty big
deal on a number of fronts. Right out

of the chute, this is a startup that has
more than $7 billion in sales and
27,000 employees scattered across the
globe. They say that makes them the
single largest source of microcon-
trollers in the world and gives them
the wherewithal to keep up with the
incredibly expensive fab arms race.

Perhaps the deal makes the most con-

ceptual sense when considered from the
perspective of the parent companies.
Both Hitachi and Mitsubishi are incredi-
bly broad-ranged and diversified con-
glomerates. They make lots of money
the old-fashioned way, be it elevators or
rice cookers. To the folks running the
conventional businesses, the world of
ICs must just seem a scary place indeed.

Invest zillions of dollars in a fab
and then hope like heck you
can sell enough chips to keep
it running 24/7? No thanks.

Call it the “give ’em rope”

strategy. The good news is
that Renesas has a measure of
independence from its par-
ents’ stodgier business coun-
terparts. The bad news is that
it’ll be left swinging if things
don’t work out.

Other challenges include a

merged chip lineup that
brings new meaning to the
term “product overlap.” Let’s
see, between them there are a
dozen architectures including
a half-dozen Hitachi H8 vari-
ations (H8/300L, H8 Tiny,
H8X, H8/300H, H8S, and
H8SX) plus Mitsubishi’s pop-
ular M16 family, plus each
company’s respective 32-bit

offerings, SuperH and M32.
Because each line has its

Photo 4—

Butterflies aren’t free, but this one from

Atmel is only $19.99 and features the new AVR
Mega169 MCU with a built-in LCD controller.

Photo 5—

Is it digital or analog? Only the silicon knows for sure. Call it what you

will, but this PID controller doesn’t rely on a DSP, nor a RISC or any kind of
processor. It’s the latest in the tool bag of tricks Anadigm ships with their FPAA, a
field-programmable analog array.

Figure 1—

Results from EEMBC’s TeleMark benchmark

show that DSPs—at least high-end ones like TI’s C6x—
aren’t dead, but hand-optimizing the code is a must.

Out of box

Optimized

700

600

500

400

300

200

100

0

TI C6416-720 MHz

MPC 7455-1 GHz

background image

background image

82

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

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

RESOURCE

Microprocessor benchmarks

EEMBC, Inc.
www.eembc.com

own family tree of variants (memory
and I/O permutations), I’m talking
about a linecard that looks more like
a phone book.

For now, the company just says

they’re committed to supporting every-
thing until 2007. Beyond that, I sus-
pect a little pruning will be in order.

…AND BETTER

Whew. Writing all this up was almost

as hard as wading through all the
exhibits and meetings. And to be sure,
I only covered a fraction of the stuff at

the show. Indeed, I’m saving some of
the other news for in-depth coverage
in my next columns, so stay tuned.

One major announcement had

nothing to do with technology but
rather the ESC show itself. It’s no
secret the trade show business has
been going through a fair amount of
restructuring as of late, so perhaps it’s
no surprise that next year’s ESC in
San Francisco will be combined with
the Europe-based Electronica show.

As a component-oriented affair,

Electronica should bring some interest-

ing players to the table. For instance, I
look forward to meeting sensor and dis-
play suppliers, because those are increas-
ingly part of the embedded equation.

On the other hand, that means the size

of the show is expected to roughly dou-
ble in terms of attendees and exhibitors.
Reserve your spot early. It also means the
floor space is expanding into both the
North and South Halls of Moscone
Center. I guess it’s just like the old song
says, “These boots were made for walk-
ing, and that’s just what they’ll do.”

I

SOURCES

EasyGUI
Amulet Technologies
www.amulettechnologies.com

Field Programmable Analog Array
Anadigm, Inc.
www.anadigm.com

Blackfin DSP, Microconverter
Analog Devices, Inc.
www.analog.com

Butterfly
Atmel Corp.
www.atmel.com

Digi Connect ME
Digi International
www.digi.com

X-Port
Lantronix, Inc.
www.lantronix.com

MPC7455, 56F800
Motorola, Inc.
www.e-motorola.com

Mod5282
NetBurner, Inc.
www.netburner.com

8-, 16-, and 32-bit Microcontrollers
Renesas Technology America, Inc.
www.renesas.com

C6x DSP, MSC1210
Texas Instruments, Inc.
www.ti.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

83

IDEA BOX

THE

DIRECTORY

OF

PRODUCTS AND

SERVICES

AD FORMAT

: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.

ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2

″″ ×× 3″″ FORMAT

. Call for current rate and deadline information. Send your disk and digital submis-

sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail kc@circuitcellar.com. For more information call Sean Donnelly at (860) 872-3064.

Suppliers Directory now available online. Check out our web site

www.circuitcellar.com to see who has what and how to get it!

Insert-ready Single Board Computer modules in sub-miniature

dimensions (as small as 47x55 mm) populated by:

8-bit:

ADuC812

,

AT89C51CC01

,

DS80C390

,

P87C591

,

P89C51Rx2

,

P89C66x

,

P89C51MX

16-bit:

C167CR

,

C167CS

,

XC161CJ

,

XC167CI

,

PXAC3

,

PXAG49

,

ST10F168

,

ST10F269

32-bit:

AT91M55800A (ARM7TDMI core)

,

Elan SC520

,

MPC555

,

MPC565

applicable controller signals extend to standard pin header (2.54

mm) or high-density Molex (0.625 mm) connectors, enabling SBC

to be plugged like a “big chip” into OEM targets

Low EMI design

achieved via GND circuitry, multi-layer PCB, by-

pass capacitor grid and short signal traces achieved via small

footprint and use of 0402 SMD passive components

32 KB to 64 MB external SRAM and Flash (controller-dependent)

CAN, Ethernet, RS-232 and RS-485 interfaces; ADC, DAC

(controller-dependent); freely-available /CS and I/O lines

available in

Rapid Development Kit

including Development Board,

AC adapter, serial cable and SPECTRUM CD with eval software

tools, electronic documentation and demos

Stick It In!

: insert-ready PHYTEC SBC modules accompany you

from evaluation through protyping to end production...

accelerating your design cycle and reducing your time-to-market

www.phytec.com

phyCORE

®

New Generation
Single Board Computer

(800) 278-9913

PHYTEC America, LLC

203 Parfitt Way SW, G100

Bainbridge Island, WA 98110 USA

background image

84

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

experience xBOB

turn serial data into video text

w w w.decadenet.com

D

ECADE

E

NGINEERING

503-743-3194 Turner, OR, USA

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

85

PC KEYBOARD EMULATION

Interface Keypads, Switches, or RS-232 to your PC Keyboard Input

MODEL KE24

ONLY $

99

95

• Up to 12 x 12 matrix • Programmable • RS-232 Port • Macro Capability

The KE24 is the ultimate in flexibility. Inputs or serial data can

emulate any of the 101 keys from a standard keyboard.

MODEL KE18

ONLY $

44

95

• Up to 9 x 9 matrix • 2.5" x 3.0" Size • PC Keyboard Port • PCXT, AT Compatible

The KE18 combines a multitude of features with small size at an

economical price. Custom units available.

HAGSTROM

ELECTRONICS

11 Fiddlers Green

Lansing, NY 14882

Toll Free: 888-690-9080

Phone: 607-533-4441 Fax: 607-533-4443

www.hagstromelectronics.com

to

RS232

to

TCP/IP

TCP/com v2.0,

RS232 to TCP/IP software.

Plus TCP/IP to RS232.
WinWedge, RS232 or TCP/IP

data direct into any Windows

app. - Excel, Access, etc.

Free 30 day evals at

www.taltech.com

R

TM

NEW

tm

tm

background image

86

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

Ready-Made Graphical User Interface

l

Bright, High Contrast 1/4 VGA (320x240 pixel)

Electroluminescent (EL) or Monochrome Display

l

High-resolution touchscreen

l

Precoded menu managing software

Powerful Controller

l

Programmable in C and Forth

l

Real-time Multitasking Executive

All the I/O You Need

l

48 Analog & Digital I/O Lines

l

Expansion I/O modules

for any need

Plenty of Memory

l

Up to 768K Flash, 640K RAM,

64Mbyte Mass Memory

Mosaic Industries Inc.

tel: 510-790-1255 fax: 510-790-0925

www.mosaic-industries.com

Everything You Need

For Instrument Control!

A C-programmable embedded

computer with a built-in GUI.

Use it for machine control,

embedded systems, scientific

instruments, and OEM

applications - wherever you need an I/O rich computer and

a smart user interface!

The QVGA Controller

TM

JK



microsystems

Call

530-297- 6073

Email

sales

@

jkmicro.com

On the web at

www.jkmicro.com

l

Flashlite 186 controller

l

Borland C/C++ ver 4.52

l

FREE Email Tech Support

l

Serial Driver library

l

AC Adapter and cable

l

186 processor

@

33 MHz

l

DOS w/ Flash File system

l

44 Digital I/O lines w/ CPLD

l

Console / Debug Serial Port

l

7-34V DC or 5V DC power

l

Accepts 8MB DiskOnChip

l

512K DRAM & 512K Flash

l

Expansion options with Peripheral Boards

Flashlite

l



2

Serial Ports

l

2 16-bit Timers

l

Watchdog Timer

186

Development

System

$

99

$

69

QTY 1

Development kit includes:

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

87

background image

88

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

sales@sealevel.com 864.843.4343

www.sealevel.com

USB to Serial

• 1,2,4, and 8-port models

• RS-232, RS-422/485, and

RS-232/422/485 versions

• Supports data rates up to 921K bps

Ethernet Serial Servers

• 1,2,4, and 8-port models

• Ethernet 10/100Base-T (autosense)

• RS-232, RS-422/485, and

RS-232/422/485 versions

• Easy-to-use software included

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

89

background image

90

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

91

SI-SCOPE Analyzer

Full featured PC RS232 Analyzer for Windows

and DOS. No more guess work SI_SCOPE lets

you view and interact with any RS232 line.

Complete with Timestamps, Triggers, Signal

Capture, and more!

SI_COMM ActiveX

Robust 32 Bit Communications ActiveX for VC++

and VB. Full Port Control, Async Callback

Events, Xmodem, Ymodem, Zmodem, and more!

Complete with examples in VB and MFC!
Software InnoVations Inc.

www.sinnovations.com

72 Prospect Hill Rd.

Wallkill, NY 12589

Ph: 845-566-1919

Fax:845-566-1118

info@sinnovations.com

background image

92

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

background image

www.circuitcellar.com

CIRCUIT CELLAR

®

Issue 158 September 2003

93

Email: sales@picofab.net

background image

i

Palm OS Data Acquisition

Speed and Location Data Acquisition

Embedded Networking with MicroMessaging

Minimum Mass Waveform Capture

I

I Above the Ground Plane: Modulation and Demodulation

I Applied PCs: Simple Data Display—Driving LCDs with Microchip and Atmel Micros

I From the Bench: Designing with RGB LEDs

I Silicon Update: In ARM’s Way

94

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

84

Abacom Technologies

91

ActiveWire, Inc.

60

All Electronics Corp.

91

Amazon Electronics

93

AP Circuits

29

Arcom

7

Atmel

85

Avocet Systems, Inc.

84

Bagotronix, Inc.

90

Basic Micro

91

Bellin Dynamic Systems, Inc.

11

Belsoft

84

BMT

82

CadSoft Computer, Inc.

83

Capitol Automation

87

Carl’s Electronics

17

CCS-Custom Computer Services

92

Conitec

37

Connecticut microComputer, Inc.

58

CTIA Wireless

83

Cyberpak Co.

18

Cygnal Integrated Products

1

Cypress MicroSystems

89

CWAV

91

DataRescue

84

Decade Engineering

88

Delcom Engineering

84

Deys Electronics, Inc

86

Digital Products

48

Earth Computer Technologies

30

Easy-Radio USA

The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page

87

EE Tools

(Electronic Engineering Tools)

77

EMAC, Inc.

93

Embedded Micro Software

73

ESC Boston

35

eMachineShop.com

88

eProtos

10

ExpressPCB

85

FDI-Future Designs, Inc.

92

Front Panel Express

92

Futurlec

77

Grand Idea Studio, Inc.

85

Hagstrom Electronics

41

HI-TECH Software, LLC

56

ICOP Technology Inc.

89

IMAGEcraft

84

Intec Automation, Inc

84

Intrepid Control Systems

91

Intronics, Inc.

65

Jameco

64, 86

JK microsystems, Inc.

34

JPA Consulting

20

JR Kerr Automation & Engineering

20

LabJack Corp.

20

Lakeview Research

57

Lemos International

2

Link Instruments

51

Linx Technologies

40

MaxStream

90

Machine Bus Corp.

90

MCC (Micro Computer Control)

37

Microchip

92

microEngineering Labs, Inc.

81

Micromint

17

MJS Consulting

86

Mosaic Industries, Inc.

39

Motorola

88

Mouser Electronics

74

MVS

86

Mylydia Inc.

C2

NetBurner

89

OKW Electronics, Inc.

36

On Time

92

Ontrak Control Systems

19

PCBexpress

87

PCB Fab Express

50

PCBpro

C4

Parallax, Inc.

9, 83

Phytec America LLC

87

Phyton, Inc.

93

Picofab Inc.

86

Pioneer Hill Software

86

Prairie Digital, Inc.

83

PrintCapture

93

Pulsar, Inc.

84

Q-Kits

88

R2 Controls

27

R4 Systems Inc.

47

Rabbit Semiconductor

10

Remote Processing

5,49

Renesas Technology Corp.

15

Renesas Contest

90

RLC Enterprises, Inc.

Page

Page

Page

69

Saelig Company

3

Scott Edwards Electronics Inc.

90

Scidyne

88

Sealevel Systems

86

Senix Corp.

95

Sierra Proto Express

83

Signum Systems

93

Softools

91

Software InnoVations Inc.

83

Square 1 Electronics

50

Systronix

85

TAL Technologies

C3

Tech Tools

89

Techniprise

22, 23

Technologic Systems

90

Technological Arts

89

Tern Inc.

85

TLData Corp.

91

Triangle Research Int’l, Inc.

36

Trilogy Design

88

Vesta Technology, Inc.

93

Weeder Technologies

93

Xeltek

85

Xilor

87

Z-World

91

Zanthic Technologies Inc.

86

Zexus

31, 55

Zilog, Inc

November Issue 160

Deadlines

Space Close: Sep 10

Material Due Date: Sep 19

Theme:

Embedded Development

A

TTENTION

A

DVERTISERS

Call Sean Donnelly to

reserve your space!

860.872.3064

e-mail: sean@circuitcellar.com

B

ONUS

D

ISTRIBUTION

C++ programming professionals

INDEX OF ADVERTISERS

Preview of October Issue 159

Theme: Data Acquisition

background image

For Unparalleled

Quality, Technology,

Delivery and Price

Insist on 2 to 24 layer

PCBs from Sierra Proto

Express

We offer the highest quality, the broadest range of technology (2 – 24 layers), the fastest, most
reliable turns (99% on-time delivery) and a competitive price. And we prove it every day,
with every PCB we ship.

Comprehensive quality checks are throughout our PCB prototype manufacturing processes

– never in the price. Every multilayer board we produce ships with our
unique Evidence of Quality reports – the results of each of these tests.
Microsection Analysis report such as the one featured here, is one test that
provides proof your board meets or exceeds your specifications.

In fact, it is our commitment to total quality that enables us to run our
operation so cost-effectively. And that comes back to you in our
competitive prices.

We’d like you to know more about our commitment to quality, our range
of technology and our 99% on-time track record of delivery. We’d like
you to know why our equipment, our people and our processes are
without parallel in the industry.

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

To start a relationship now, please call a
Sierra Proto Express experienced Account
Manager at 1.800.763.7503, e-mail your files
to files@protoexpress.com, and visit us at
www.protoexpress.com

Microsection
14 Layer Board

q

u

a l

i t y l e a d

e

r

M

IL

-P-5

5110 ISO

90

0

2

80

0-

76

3-7

503

www.protoex

pre

ss

.c

om

background image

E

ver wonder why technology advances the way it does, or doesn’t? I started thinking about this yesterday when I stopped by a local elec-

tronics/appliance store (not connected, but I was looking at electric stoves). While I was there I wandered over to the TV department and
noticed that virtually every set was high-definition this or HD-ready that. There were at least four display technologies and a dozen brands.
High definition is here, folks, at least as far as your ability to see it, finding something to watch on it is another matter.

Since I already have two HDTVs, I wasn’t in the market for another set. Instead, I asked if they had any high-definition DVD players or high-

definition recorders. It seemed like a reasonable question because it’s an obviously untapped market with all the displays they must be sell-
ing. To make a long story short, the answer was “nope!” There was a digital VCR (non-HD) but nothing else anyone knew about.

Wait a second. I bought a 5-megapixel camera last week for half the cost of the 1-megapixel camera I bought four years ago and half the

cost of the 4-megapixel camera I bought last year. What do you mean no HD DVD players? Given the technology I see crammed into every
computer and video game these days, making a high-definition DVD player should be a no-brainer.

Well, it should have been obvious to me, but the no-brainer part is that the industry is holding off producing one because of digital piracy.

Sony, Panasonic, and the like aren’t going to sink a billion dollars into designing and marketing a high-definition DVD player/recorder if none
of the movie or music manufacturers will license media to play on it. The closest I could find to an HD video player is from JVC. Dubbed D-
VHS, the system uses special high-definition VHS tapes, but it’s still an old-clunker VCR in my book. The only reason that there are any pre-
recorded movies available at all for D-VHS, is that JVC has apparently convinced the media giants that the decryption algorithm is locked in
the machine electronics. Because it’s not available on a computer, it can’t be pirated—this week, at least.

Digital piracy, the unrestricted swapping of copyrighted movies and music, has the media giants ripped (pun intended). Perhaps because

of a perception that anything on the Internet is free, there is an entire world of users who do just that. Every day, millions of ordinary people
download billions of files: music albums, movies, cable TV shows, video games, etc. Just download and install a peer-to-peer file-sharing pro-
gram and join the crowd. Everyone has heard of Napster. It is gone now but others have replaced it with a vengeance.

The problem is smart people, not technology. Smart people design the encryption schemes—like Sony’s expensive CD-copy-control tech-

nology. Similarly, it took a smart person to figure out that you could defeat the anti-copy data by simply running a black marker around the
perimeter of the CD. There are no HD DVD players for the same reason. The fear is that shortly after the first DVD is inserted into a comput-
er drive, someone will crack the protection scheme and tell the world. That happened with the original DVD encryption, and it’s naive to think
it wouldn’t happen again.

There is a plethora of solutions being offered. Microsoft has jumped into the game with both feet and will be offering high-definition DVDs.

Initially, they will be encrypted and only play on PCs with a special version of Windows Media Player. Ultimately, Microsoft’s objective is for all
PCs to include special “copyright-material security chips,” viewed by many as simply a new means for corporate and government spying. In
the meantime, the Recording Industry Association of America (RIAA) intends to create a full-employment program for the legal profession—
basically, they plan to sue everybody they can. The RIAA is preparing to file hundreds of lawsuits (with damage claims as high as $150K per
song) against the people who are offering music to others. If you keep a large catalog of music as part of one of these peer-to-peer organi-
zations, you may find yourself a target.

Personally, I’d like to see some high-definition DVD players hit the shelves before the two sets I have become obsolete. I can’t define the

correct path leading to an answer for all this, but somehow I think that finding a legal and profitable way to give people what they want is the
only correct solution. Undoubtedly, much of the piracy is driven by cost. Even if a legal sledgehammer stops the piracy, it doesn’t automati-
cally convert all these people to buying customers if the only way to get the one song they want is to buy a $17 CD. There is a message when
a service like Apple iTunes—with no subscription fees, $0.99 per song cost, and 30-second free previews—sells five million songs in the first
two months of operation. Maybe someone has to set it to music for the RIAA.

Getting Ripped

PRIORITY INTERRUPT

steve.ciarcia@circuitcellar.com

96

Issue 158 September 2003

CIRCUIT CELLAR

®

www.circuitcellar.com

by Steve Ciarcia, Founder and Editorial Director

background image
background image

Wyszukiwarka

Podobne podstrony:
circuit cellar1996 09
circuit cellar2004 09
circuit cellar1995 09
circuit cellar1997 09
circuit cellar2000 09
circuit cellar1993 09
circuit cellar2001 09
circuit cellar2002 09
circuit cellar1994 09
circuit cellar1996 09
circuit cellar2003 09
circuit cellar1994 09
circuit cellar1997 09
circuit cellar1993 09
circuit cellar2004 09
circuit cellar1995 09
circuit cellar1996 09

więcej podobnych podstron