Micro_Cornucopia_#53_May90 Micro Cornucopia #53 May90

Micro_Cornucopia_#53_May90 Micro_Cornucopia_%2353_May90

User Manual: Micro_Cornucopia_#53_May90

Open the PDF directly: View PDF PDF.
Page Count: 100

DownloadMicro_Cornucopia_#53_May90 Micro Cornucopia #53 May90
Open PDF In BrowserView PDF
No. 53

May 1990

THE

$3.95

TECHNICAL

M

JOURNA L

ORNUCOPIA
Controllers
In this, our hysteric final issue, we cover
one of our favorite topics, micro
controllers and their cousins, the data
loggers.

Designing A Micro
Controller
Designing a controller is simple when
you start out with the right micro.

Building A Two~chip
. Terminal

page 26

The perfect accessory for your micro
controller.

Waylaid By Snakes
A low-down look at objects
(in the grass) .

Save The Floppies
Routine, complete with code,
recovering bad sectors on floppies.

And More ...
Shareware/Favorite Tools
Initializing Variables
in Turbo Pascal
Faster Neural Networks

05

a

7447019388

3

with 4MB RAM and Rotary Voice Coil Hard Drive
For extra speed and reliability we've included a 66MB Mitsubishi
MR535 voice coil hard drive with an access time of 28ms,
and a super fast 1: 1 interleave HD controller card.
•
•
•
•
•
•
•
•
•

25Mhz 80386 CPU, AMI Bios, Full Size MB
4MB of RAM, expands to 8MB on MB
1.2MB and 1.44MB Floppy Drives
12" Amber Monitor w/Mono Graphics Card
101-Key Enhanced Keyboard, Focus or Maxiswitch
2 Serial, 1 Parallel, 1 Game, ClOck/Calendar
200-Watt Power Supply
Socket for 80287,80387 or Weitek
Full 1 Year Warranty
w/Std AT Case ...... $2250
wI1MB ................. $250 Less
(Mega Tower) 20Mhz 386 .......... $100 Less

$2350
AT /386S SYSTEMS
Includes: 1MB RAM, 1.2MB & 1.44MB FD,
40MB Hard Drive (28ms), Fast Hard Drive
Controller, Mono Graphics Video Card,
12" Amber Monitor, 101 Key Keyboard,
Serial(2)/Parallel(1 )/Game(1) Ports,
Clock/Calendar, Full 1 Year Warranty.
FREE assembly and testing.
6/1 OMhz 286/AT.. ........................ $1249
8/12Mhz286/AT.. .......................... 1295
8/16Mhz 286/AT.. .......................... 1395
16Mhz 386-SX .............................. 1449
Video upgrades for our systems
(includes video card and monitor)
I

ATI Graphics Solution ....................... 39
CGA Color ....................................... 175
EGA Color ....................................... 349
VGA Color (Analog, 16 bit
w/Amazing monitor) ..................... 379
CGAlEGAlVGA (Multisync) ............. 450

360K

FLOPPY DRIVES

.................................................. 69
1.2MB................................................ 77
31/2" 720K ....................................... 79
31/2" 1.44MB ................................... 85

HARD DRIVES
XT 20MB Miniscribe/Kalok
8425 (65ms) ................................. 229
8425 w/controller .......................... 269
XT 30MB Miniscribe/Kalok
8438 (65ms) ................................. 229
8438 w/controller.......................... 269
AT 44MB Mitsubishi MR535,
Rotary Voice Coil (28ms) ............. 429
AT71MBMFM
Voice Coil (28ms) ......................... 595

Mini Tower

Standard Tower

$225

$269

MOTHERBOARDS

The Most Cost Effective Way to Speed Up
your AT or 386 System!

XTlTurbo 4.77/1 OMhz ...................... $75
AT 6/10Mhz ..................................... 175
AT 8/12Mhz ..................................... 195
AT 8/16Mhz ..................................... 249
386SX 16Mhz w/C& T chip set.. ....... 359
386 8/20Mhz w/Phoenix Bios,
holds up to 8MB on board ............ 679
386 16/25Mhz w/AMI Bios
holds up to 8MB on board ............ 795
386 33Mhz ...................................... Call

Upgrade your hard .drive controller. Discover the NEXT
generation of hard drive controller cards. As the chart below
demons~rates, the speed improvements are incredible!
Controller Card Type
Standard IBM AT, 3:1 Interleave, MFM
DTK WA2, 2:1 Interleave, MFM
AT/3S6 1:1 Interleave, MFM
Western Digital 1:1, RLL, w/Cache

Data Xfer Rate
167 KB/Sec.
261 KB/Sec.
522 KB/Sec.
799 Kb/Sec.

POWER SUPPLIES
150-Watt XT Power Supply ............... 49
200-Watt AT Power Supply ...............59
230 Watt AT Power Supply ............... 75

Note: Test results using 10Mhz AT, Mitsubishi MR535 Hard Drive and

SpmRH.CHSk~t;A Color ONLY $379..._

EXPANSION CARDS

When you buy a complete MicroSphere Computer System; Up~
grade includes: 16 bit VGAvideocard and 1411 Analog VGA
Monitorwitha.28 mm dot pitch.

CONTROLLER CARDS

KEYBOARDS

AT/3861:1 MFM Controller ........... $1 05
WD 1006-SR2 1:1 RLL w/Cache .... 139

Maxiswitch (AT Only) 101-Key ........ $59
Keytronic· Enhanced 101-Key .......... 55
Focus· 101-Key Tactile, Switchable
Control/Caps Lock, Dust Cover...... 59
(#1 Find by Micro C Staff)
• Keyboards are XT/AT switchable

CABINETS
XT Slide Case, Lock, LED ................. 35
AT Slide Case, Lock, LED
3 half ht., 1 full ht. drives ................ 59
Baby Tower, w/200 watt PS,
2 half ht., 2 - 31/2" Drives,
Baby Motherboard ONLY ............. 129
Mini Tower, w/200 Watt PS,
3 half ht, 2 - 3 1/2" Drives,
holds Full or Baby size MB ........... 195
5 Bay Std. Tower, 220 Watt PS,
3 half ht., 1 full ht drives ............... 269
6 Bay Mega Tower, 230WattPS .... 229

MONITORS

VIDEO CARDS

~~:~~I~~ ~~~~~~~.~~.~~::::::::::2::

Mono Graphicsw/Parallel port .......... 37
ATI Graphics Solution
Herc w/CGA Emulation .................. 79
CGAlEGAlVGA 8-Bit.. ..................... 119
CGAlEGAlVGA 16-Bit.. ................... 129

EGAlCGAAutoswitch ..................... 362
CGAlEGAlVGA
Multisync (.31 dot) ........................ 489
VGA Analog
(Amazing .28 dot) ......................... 369

SOFTWARE
MS-DOS 3.3 w/GW Basic ................. 95
DR-DOS 3.3 w/GEM ........................ .45
SpinRite II Disk Optimizer
by Gibson Research ....................... 79
386Max Memory Manager for
386 Systems .................................. 69

==ii

~M·

Clock ................................................. 18
Game (Joystick) ................................ 14
Parallel Port (LPT1, 2 or 3) ................ 18
Serial Port, 2 ports, 1 installed,
(COM1 or 2) ................................... 18
2nd Serial Port Kit.. ......................... 18
Serial Port, 4 ports installed ............... 99
Multi Drive Controller, up to
2 drives, Supports 360K,
720K, 1.2MB & 1.44MB .................. 39
3 & 4th Floppy Controller ................... 79

AT/386
AT Multi-IO, 2 Serial, 1 Parallel,
1 Game ........................................... 35
AT 3MB EMS Memory Card (OK) ...... 99

CHIPS/ETC.
Memory 64K, 256K, 1MB ............... Call
Math Coprocessors ........................ Call
XT Components & Systems ........... Call

~~

here

,crO~D

COMPUTERSrH;RDW~:c~~~B~~ACT~~~R

Orders Only Please!
Tech Calls:

1-800-234-8086

(503) 388-1194 Hours: Mon-Fri 9:00-5:30

855 N.W. WALL· BEND, OREGON 97701

'Prices are subject to change without notice. Shipping CHARGES will be added. '1-year warranty/3D-day money back (subject to restrictions)

Reader Service Number 2

!M[EWU AT&T C++ RELEASE 2.0
SPECIFICATION
C\!J~~J'g MS WINDOWS
COMPATIBILITY

~fE~J'U EASY PORTABILITY
FROM MICROSOFT C
[K!J~~1fg C++DEBUGGER &
EXPANDED C++ TOOLS

[MgWU OS/2 UPGRADE
AVAILABLE NOW!
We listened carefully to
DEBUGGER, and now the
For many, EMS
what you wanted in a next
wait is over.
programming support, built
into the compiler is
generation MS DOS C++
You wanted expanded and
compiler. The answer is
important, so it's in there
improved documentation,
too.
Zortech C++ V2.0
----------w we both
Developer's
listened
You were happy using the
Edition.
and
18 classes provided in
You wanted
delivered.
C++ TOOLS, but we
the latest
revised and expanded it
You
anyway.
AT&TV2.0
wanted to
features
You never asked for a free
be able to
with the
upgrade
TSR
library to be included,
power
but we knew you'd love to
to an
offered by
OS/2 version compiler
use our neat little package,
multiple inheritance and
supporting Presentation
so we included it free.
type safe linkage, so here it
Manager, you did not want
is.
it to cost a fortune, so it's
You liked our FLASH
available r - - - - - - - - - - - - - - - - , GRAPHICS
You wanted compatibility
for $150.
Here is our list of highly
package
with MS WINDOWS, we
recommended C++ Dooks:
for its
added it.
You want
speed, but
to
look
at
c+
+
Language;Stroustrup
$32.25
wanted
a
You repeatedly asked for
C+ + AnsW3r Book;Hansen $26.95
easier portability from
the
C+ + for C Programmers
$29.95
CCI+as+s
Microsoft C, we got the
standard
c+ + Primer ;(.ippman
$30.25
message, and have written
library
interface,
the library functions you
SOURCE
Ask about our new c++ Video Tutorial
so we've
CODE, so
written it.
need.

~Bo'w 10 Order:
Already own Zortech
C++? Call the order
hotline for details of our
low cost upgrades.
To order Zortech C++
for the first time, just call
the order hotline. We
accept payment by,
Mastercard/Visa/COD.
Alternatively, mail the
coupon below with your
check or credit card
details.

ZORTECH INC.,
1165 MassachuseHs
Avenue, Arlington, MA
02174, USA
Voice 617-646-6703
Fax 617-643-7969
ZORTECH LTD.,
106- 108 Powis Street,
London, SE 18 6LU,
ENGLAND.
Voice (44)- 1-316-7777
Fax (44)-1-316-4138

L..-._ _ _ _ _ _ _ _ _ _- - - - '

You wanted the world's first
MS DOS C++ source level

Yes! Please rush me the following
Name
Addres-s----------City-,.--=--_ _ _ _State_Zip _ __
Visa/MC# _ _;-;-_ _ _ _ _ __
Exp.Date _ _ _Tel _ _ _ _ _ __
All MicroSoft trademarks are acknowledged.

C++ V2. a items:

o DEVELOPER'S EDITION$450 (Save $200)
o C++ COMPILER $199.95
o C++ DEBUGGER $149.95
o C++ TOOLS $149.95
o LIBRARY SOURCE CODE $149.95
o COMPILER & LIBRARY SOURCE $299.95
For US orders please add $5.05 shipping
Reader Service Number 70

o OS/2 COMPILER UPGRADE $ 749.95
o C++ VIDEO COURSE $499.95
o C++ Language /Stroustrup $32.25
o C++ Answer Book/Hansen $26.95
o C++ for C Programmers/Phol $29.95
o C++ Primer/Lippman $30.25

Overseas orders at international mail rates.

ENAl
l
Y
.
A debugging
tool tough enough to
handle the DOS
Nasties.

New Version 2.0

How Soft-ICE Works

Soft-ICE memory range break points help you
track down memory over-write problems
whether you are doing the over-writing or
another program is over-writing you.

Soft-ICE uses the power of the 80386 to surround your program in a virtual machine.
This gives you complete control of the
DOS environment, while Soft-ICE runs
safely in protected mode. Soft-ICE uses the
80386 to provide real-time break points on
memory locations, memory ranges, execution,
II 0 ports, hardware &' software interrupts.
With Soft-ICE you get all the speed and power of
a hardware-assisted debugger at a software price.

Hung program? No problem!

Don't want to switch debuggers?

Nasty over-write? No sweat!

You don't have to!

When the system hangs, you now have hope.
With Soft-ICE you can break out of hung
programs no matter how bad the system has
been trashed. And with Soft-ICE's back trace
ranges you can re-play the instructions that led
up to the crash.

Soft-ICE can run stand-alone or it can add its
powerful break points to the debugger you already
use. Use your favorite debugger until you require
Soft-ICE. Simply pop up the Soft-ICE window to set
powerful real-time break points. When a break point
is reached, your debugger will be activated automatically.

Program too large? Not with Soft-ICE!
Soft-ICE runs entirely in extended memory. This means
you can debug even the largest DOS programs. And
since your program runs at the same address whether
Soft-ICE is loaded or not you can find those subtle
bugs that change when the starting address of your
code changes.

System debugging? Soft-ICE is a natural!
Soft-ICE is ideal for full source level debugging of TSRs,
interrupt service routines, self booting programs, DOS
loadable device drivers, real-time kernels, non-DOS O/Ss
and ROMs. Soft-ICE can even debug within DOS &' BIOS.

MagicCV with Soft-ICE
Using Soft-ICE with CodeView gives you the features
necessary for professional level systems debugging.
MagicCV and Soft-ICE can work in concert with CodeView to provide the most powerful debugging platform
you will find anywhere.
"These may be the only two products I've seen in
the last two or three years that exceeded my wildest
expectations for power, compatibility and ease-of-use."
-Paul Mace
Paul Mace Software

New Soft-ICE 2.0 features
$386
$199
$199

Soft-ICE
MagicCV
MagicCV for Windows

[] Back Trace Ranges
[] Symbolic &' Source level debUgging
[] EMS 4.0 support with special EMS
debUgging commands
[] Windowed user interface

Buy Soft-ICE &' MagicCV(W)
-Save $86.
Buy MagicCV and MagicCVW
-Save $100.
-Save $186.
Buy All 3
I •• ~ •

30 day money-back guarantee
Visa. MasterCard and
AmEx accepted

~.

™DNu-Mega

8

\}-TECHNOLOGIES
•
A",

Y

A"

T •

CALL TODAY (603) 888-2386
or FAX (603) 888-2465

0 OJ

O'\T.III(lIO ....

PO. BOX 7607 • NASHUA, NH • 03060- 7607

2

MICRO CORNUCOPIA, #53, May, 1990

Reader Service Number 110

RUN
IN
8KCODEVIEW~M
~ ..

MagicCV

);~,

"

Code View is a great integrated debugger, but
it uses over 200K of conventional memory.
MagicCV uses advanced features of the
80386to load CodeView and symbols in
extended memory. This allows MagicCV to
run CodeView in less than 8K of conventional memory on your 80386 Pc.

NEW VERSION FOR C 6.0
Attention Windows Developers!
Version available for CVW.

THE

M I C R 0

TECHNICAL

JOURNAL

MICRO CORNUCOPIA
MAY 1990-ISSUE NO. 53

8

H. Ward Silver

Designing A Microcontroller
Ward puts together a very simple data logger
and microcontroller based on the 68HCll.

20

Bruce Eckel

26

Karl Lunt

34

Waylaid By Snakes
A fun look at c++ if you don't object to serpents.

Building A Two-chip Terminal
Here's a simple, low-power terminal with a two-line by twenty-column
display.

46
54
70

86 World

64

Culture Comer

65

On Your Own

81

Units and Modules

88

Shareware

90

Techtips

85

Tidbits

96

Last Page

Lance Dannon Bresee

A Roundoff Roundup
Tired of round-off errors? This should help your calculations.

40

57

Dave Gwillim

Initializing Variables In Turbo Pascal
An elegant fix for a popular compiler.
D. Gilbert Lee

Fast Neural Networks
Larry Fogg

Save The Floppies
Stuart R. Bell

Build A Composite Video Adaptor

Cover Illustration by Greg Cross.
MICRO CORNUCOPIA, #53, May, 1990

3

THE M I C ROT E C H N'I CAL J 0 URN A. L

MICRO CORNUCOPIA
Editor and Publisher

David J. Thompson
Associate Editors

Gary Entsminger
Larry Fogg
Cary Gatton
Contributing Writers

Bruce Eckel
Michael S. Hunt
Alfred E. Newman
Karl Lunt

..... :>

Accounting

Sandy Thompson
Advertising & Distribution
Reader Services

Nancy Ellen Locke & Laura Shaw
Graphic Design & Production

Carol Steffy
MICRO CORNUCOPIA aSSN 0747-587X) was
published bi-monthly for $18 per year by Micro
Cornucopia, Inc. 155 NW Hawthorne, Bend, OR
97701. Second-class postage paid at Bend, OR and
additional mailing offices. POS1MASTER: Send
address changes to MICRO CORNUCOPIA, PO
Box 223, Bend, OR 97709.
Recycled Paper

@

SUBSCRIPTION RATES:
1 yr. (6 issues)
2 yr. (12 issues)
3 yr. (18 issues)
1 yr. Canada & Mexico
1 yr. Other foreign (surface)
1 yr. Foreign (airmail)

$18.00
$34.00
$48.00
$26.00
$36.00
$50.00

Make orders payable in US. funds on a U.S. bank.
CHANGE OF ADDRESS:
Please send your old label and new address to:

MICRO CORNUCOPIA
P.O. Box 223
Bend, Oregon 97709
READER SERVICES:
For orders and subscription problems call (503)
382-5060, 9 am to 5 pm, Pacific time, M-F. FAX
your VISA or MC order to us, our FAX number is
(503) 389-6833.

BBS - 24 hrs. 300-1200-2400 baud
8 Bits, No Parity, 1 Stop Bit 503-382-7643

Copyright 1990 by Micro Cornucopia, Inc.
All rights reserved
ISSN 0747-587X

.t}

The
Audit
Bureau

......................................................' ' .. .

.,."r~·notsureh()w·to begin. I've ~tarted this edlitolrial
:~()'inanytimes, in my daydreams, in my sleep, in the
. , shOwer.... But nothing I've come up with really feels
like I feel.
I'm closing down Micro C and I don't know what I'll
be doing next. (Wait till mom reads this .... "Dad! Our
little David's quitting his job. Quick, clean up the spare
. room.")
You may be wondering why it's closing rather than
moving on to other ownership. Good question. Three
groups have come forward, interested in taking on
'Micro C. After long discussions, none felt they could put
together both the finances and the talent to make it fly.
When a magazine folds (a strangely appropriate
word), other magazines often pick up the subscribers.
As far as I know, the only subscribers no one wanted
were the ones taking Profiles (aimed at Kaypro owners)
and CP/M Review. So we've had offers from several magazines wanting to finish your subscriptions. How did I
choose?
Some were willing to pay for your names. Some
weren't. Some were already popular with Micro C sub, scribers. Some weren't. Some were very interested in
picking up the articles already in the pipe for future is,:> sues. One even wanted to continue "Around The Bend"
~ in its entirety. (Led to an, uhm, lengthy discussion
about sanity.)
After considering all the options, I selected Computer
Language. To finish out your Micro C subscription, you'll
get your choice of Computer Language, AI Expert, or
Embedded Systems Programming. If you already subscribe (25% of you already take Computer Language),
they'll extend your subscription. Just fill out the form
you'll receive in April.
If you've got a year of Micro C coming, you'll get a
year of Computer Language-and you'll be getting it at a
really good discount (CL's normally $29 a year, Micro
C's just $18). Plus, Computer Language's sta'ndard
policy is: if you decide you don't like their magazine,
they'll send you a refund for all remaining issues. All
you have to do is let them know.
Look, I know that Computer Language isn't Micro C.
When I looked closely the past few months, I was surprised how far we'd moved away from the other com-

Continued on page 74

4

MICRO CORNUCOPIA, #53, May, 1990

c-:J rying to modify

a program without its
II source code is tough enough without
U having to use an inferior disassembler.
That's why you should look at DASM™
before you invest in any disassembler
product.
Most disassemblers complicate the
process with errors: giving you incorrectly
placed labels, incorrect and misplaced code
and data, data treated as code, or code
treated as data.
DASMTM makes the modification process
easy by keeping track of segment register
usage and mapping code in its execution
sequence. It determines which parts of the
file are code, which are data, and what
labels exist. You simply edit the assembly
language output, make the necessary
changes to the program, and reassemble.

Japan's #1 Seller - Made in America

TlI

Try DASM Risk-Free!

DASM's simplicity, accuracy and power
DASM™ is available through the Prohave made it the top-selling disassembler
grammer's Shop for only $225. And it'sguarin Japan for two straight years. The
anteed to outperform any disassembler on
reason - DASMTM does what other disthe market.
assemblers can't:
Order your copy now and throw your
o Handle problematic segment and instrucworst disassembly problem at it. We think
tion address register loads through interacyou'll be impressed. If not, just return
tive mode
DASMTM for a full refund.
o Track segment register usage
Why settle for anything less?
o Generate appropriate ASSUME's and
segment maps
r=-===:~::""l
[J Handle mUltiple entry points
o Track memory references
• Direct
• Via register
Software
• Implied in OS function requests
To Order Call
o Handle transfer vectors
301·752·1348
o Handle .EXE, .COM and .BIN files
up to 200K

Jb

To demonstrate DASM's superior performance, we gave the same disassembling task
to both DASMT~ and SourcerH'(Version 2.18).

bx~

C1WOH
C1N2H:
mov
mov
int

,

t2

@) Since Sourcer™ generates no segment labels relative to the DS segment,
changes in the DS segment will not be
reflected.
{j) Sourcer™ can't handle jumps or calls
via register, and does not generate the,
code segment label (or reference).

t2

proc

far

mov
mov
jmp

cl, ds:data...3e ~ @
ds, cs:data.4 ~
short loc_1 ~ ~

d

1)5

endp

db

seg-h

mov
mov
ASSUME
jmp
ENDS

'Print string message$'
'P'

ends
end

G

';.JJc:~,.

~b

t:( db

"'::€>
d

21H

.~

ends
~
segment para public
assume cs:seg-h , ds:seg

In short, if you're not using DASM™, be
prepared to spend a long time editing the
file to add and fix the missing and incorrect labels - and expect a lot of bugs!

dX,OFFSET D3BOH
ah,9

a1,D3B15H
bx, OFFSET C1B11H
bx ~ /~

OB4h, 4Ch, OCDh, 21 h.d
start:

Trademark/Owner: DASMTMIJBSoftware;
Sourcer™/V Communications.

®

10c_1:

€b Sourcer™ continues to have the

@ Sourcer™ does not reference the segment value symbolically, so any changes
to the program which alter its location
will not be reflected.

t"Jhile DASMH' generated the correct
assembly code, Sourcer made at least six
major errors.

start

D3SEG

SEGMENT
LABEL BYTE
'Print string message$'
db
LABEL BYTE
'P'
db
org
20H
ENDS
END
C1F15H

Reader Service Number 213

MICRO CORNUCOPIA, #53, May, 1990

5

Rack &Desk
PC/AT Chassis
Integrand's new Chassis/System is not
another IBM mechanical and electrical
clone. An entirely fresh packaging design
approach has been taken using modular
construction. At present, over 40 optional
stock modules allow you to customize our
standard chassis to nearly any requirement.
Integrand offers high quality, advanced
design hardware along with applications
and technical support all at prices competitive with imports. Why settle for less?

Accepts PC, XT, A T Motherboards
and Passive Backplanes
Doesn't Look Like IBM
Rugged, Modular Construction
Excellent Air Flow & Cooling
Optional Card Cage Fan
Designed to meet FCC
204 Watt Supply, UL Recognized
145W & 85Walso available
Reasonably Priced

~QW

~
-_......
.......
- . -.........
.... ..

Passive
Backplanes

ii . . .=;r~~~r=:;.

...--

~~ ~ ~ !!:=~~

.... • r=:ta

--.

!!"-e!

~~

Call or write for descriptive brochure and prices:
8620 Roosevelt Ave. • Visalia, CA 93291

209/651-1203

TELEX 5106012830 (INTEGRAND UD)
FAX 209/651-1353

We accept Bank AmericardlVlSA and MasterCard
IBM. PC. XT, AT trademarks of International Business Machines.
Drives and computer boards not included.

Reader Service Number 22

6

MICRO CORNUCOPIA, #53, May, 1990

Letters

So Long
Today I heard that Micro Cornucopia
is to be no more. This greatly saddens
me even as I recognize the need for
change in all things. Your magazine
filled a niche in the journalistic world
that was very special and unique. You
represented all of us plain folks, who
did not hide behind the shirt and tie but
who loved working with computers at
every level.
You spoke to us, as one enthusiast to
another, not using technojargon to hide
a lack of real understanding so common
in other journals. You held gatherings
where we laughed and joked with the
literary mentors who taught us and
guided us on our own paths to knowledge, even while we wiped the bar-bque sauce off our lips.
You became family. You will be
missed. My best wishes and thoughts go
out to each and every one of you at
Micro C who have touched my life.
Godspeed And Thank You.
Al J. Szymanski (Big AI)
8991 Edcliff Ct. SE
Aumsville, OR 97325

Editor's note: Thanks AI. The entire staff
remembers, only too vividly, your smashing
presence during SOG volleyball. Godspeed
to you, also.
Bend Memories
I have just sent in my subscription renewal. Late. I can't believe that just because I forgot to renew, you stopped
sending me the magazine! Didn't you
know that I still wanted it?
Seriously, I think Micro C is the best
computer mag available. You can imagine my shock when I first saw it a
couple years ago. I couldn't believe such
a great mag was published in Bend, of

all places. I mean, I used to live in Bend
when I was 14, in the year 19-mumblemumble. I don't suppose Bend has
changed any since then? As I recall,
Bend was very small.
I say, Bend was very small. (Did you
say, "How small was it?") It was so
small that if you wanted a business
phone number, you looked it up on the
yellow page. It was so small that every
time I turned on my radio, the electric
trolly slowed down. It was so small we
didn't have a regular village idiot; we all
took turns. Bend had a newspaper,
though. ("Really?") Yeah, a traveling
salesman left it at the feed store.
I may be exaggerating slightly, but
the most interesting thing I did all year
there was ride my bike up the dead volcano outside town. I had just seen The
Last Days of Pompeii and, being 14, I had
hopes it might erupt again and liven
things up a bit. No such luck.
Sounds like I missed something by
not attending the Rocky Mt. SOG. But I
had been to Gunnison before, and
having recently seen Deliverance, I
Letters continued on page 68

.~

,,~ • .e ~"'>~'

, __

W~

,

"

~,

"""

" "

,."

~,,,.,.

'

• ~

"'Y~" ,_.

'~"'_"

•

",>~,,_,., .. ,

'.

,~. ,~,~ •..,,,,,~,

«..,...""

~'"""'"' .. ~~" .... "" ,~.~

.. ~••

,.,W~~

• v~ ","""",,~" . , " _ N M w _ , ' . "

>0>''"'' "' ..,....

~,,~

... ""' '"

~ '_".~V'

."

~,

...~~,

""~<

""

~ ....... "

,"",

~>

•.• ,,"

""~ ....

,

""''''''''''''.'V",~"M"..,."

~

,

"\(jood Lucl(f'=::·:·~·: :. ~'
/) rJJave & Sanay
Jennifer & 'Erin
II

fi

II

Try the 1st truly low cost LAN
• Connect 2 or 3 PCs, XTs, ATs
• Uses serial ports and 5 wire cable
• Runs at 115 K baud
• Runs in background, totally transparent
• Share any device, any file
• Needs only 14K of ram

Skeptical? We make believers!

·~

OveJt;

15. 000 ~JJ ~

~

Information
Modes
P.o. Drawer F

m

I 0 e

I
Denton, TX 76202
...--_ _ _...., 817-387-3339 or 1-800-628-7992

Why waste money on Simple file transfer systems?

Love,
'Don & Xim
'Dona{d & Court{and
Reader Service Number 149

MICRO CORNUCOPIA, #53, May, 1990

7

Designing A MicroControlier
The MC68HCll In Action

Ward walks us through a microcontroller
design project based on the 6811. If you're
thinking about designing a monitor to watch
the real world or control a process this
project, the DataBear, should make great
reading. (Now that I've spilled the name of
his board, you suspect I'm going to make one
of my unbearable puns. Right?)
he best way to describe a particular
microprocessor is to show how it's
used. In this article, I'm using the
Motorola MC68HCll in a batterypowered data logger, the DataBear from
Langan Products, Inc., of San Francisco.
The 6811 is one of the more flexible
and powerful eight-bit microcontrollers.

T

8 MICRO CORNUCOPIA, #53, May, 1990

See Figure 1 for a list of features and Figure 2 for the way it's organized.
Not only is the 6811 well supported
by software and hardware development
tools (including C compilers and emulators), it's quite cheap. Unlike some of the
latest whiz-bang processors, a 52-pin
version with 512 bytes of EEPROM costs
only about $12 in onesies. Plus, you can
easily interface inexpensive 8-bit support
chips to the 6811.
See Figure 3 for a list of variations on
the 6811.
What Is A DataBear?
I designed the DataBear as a small,
simple unit, powered by just about anything and capable of monitoring ordinary analog data at very ordinary rates.

Of course, I wanted to include as
many features of more expensive loggers as I could while keeping down the
chip count and printed-circuit size. The
6811 makes that possible.
The DataBear packs the 6811, 8K or
32K of static RAM, 8K or 32K of
EPROM, bus logic, real-time clock, serial
interface, temperature sensor, and two
external channels of analog input onto a
board 2.6x3.0 inches. With the battery
packs, the whole unit is only 1x4x6 inches. It's portable and powerful, thanks
to the 6811.
Slow And Steady Continuous Mode
I set up the DataBear to collect data
over a long period of time, from once
per second to once every 18 hours. Each

By H. Ward Silver
RBRDesign
P.O. Box 1608
Vashon, W A 98070
(206) 463-2833/9173
Fax (206)463-9122

Figure 1-Basic 6811 Features
Internal Memory: 256 bytes static RAM
512 bytes EEPROM
o - 12K bytes mask ROM (programmed at factory)
External Memory: 64K byte address space with mux'd bus
Serial Communications Interface (SCI), to 131K baud
Serial Peripheral Interface (SPI), clock speed to 1/2 crystal freq.
Parallel I/O: up to 38 bits, some dedicated Input or Output
16-bit Timers: Four-Stage Prescalar
3 Event Capture Counters (ICF)
5 Counter Controlled Outputs (OCF)
Pulse Accumulator Input (PAl)
8 Channels of 8-bit Ratiometric A/D Conversion
2 Hardware External Interrupts: XIRQ (non-maskable) and IRQ (maskable)
Programmable Real-Time Interrupt and watchdog Timer
WAIT/STOP Low Power Modes
6801-based instruction set plus: 16x16 Integer and Fractional Divide
Bit Manipulation Instructions
Direct, Extended, and Indexed (2 16-bit Index Registers) Addressing

•••

sample is an average of eight rapid
samples,
thus
minimizing
high
frequency noise.
You'll probably use Continuous
Mode for most field, shipping, or remote
applications. When you're sampling at a
very slow rate, the processor can shut
down between samples, saving power.
Programmable Fixed Mode
A second mode uses the real-time
clock to take bursts of data at preset
times. This is called Fixed Mode and it
lets you control the time resolution of
the data.
Real Time Mode
The third logging mode samples on
request by a host computer. A command
string from the host triggers the sampling. The Bear then reports its data in
either binary or ASCII. The maximum
rate is approximately 20 samples per
second, limited mainly by the speed of
the serial link.
The
DataBear's
time-controlled
operation makes heavy use of the 6811' s
SPI port to service clock interrupts and
read the clock time and date. Because of
the SPI's high speed, these transactions
don't take long, providing for low
power consumption and a high sampling rate.
Analog Conversion Numbers
The DataBear has three analog inputs. The 6811 has an eight-channel
AID Converter, but I used two to monitor the power and left three for expansion. Of the three left, I used one channel
to monitor internal temperature. You get
the other two for data. The converter resolution is eight bits, its accuracy limited
by the voltage reference and by the performance of your sensor.
Eight bits of resolution is acceptable
resolution for the vast majority of field
data logging requirements. For example,
MICRO CORNUCOPIA, #53, May, 1990

9

with the built-in LM34 temperature sensor, we measure 0 to 128' degrees
Fahrenheit with a resolution of 1 degree.
Host Interface
Interaction with the DataBear happens over an RS-232 serial port at 9600
baud. Any type of computer can talk to a
DataBear. To avoid the bulky and expensive DB-25 type connector, I used a telephone handset (RJ-11) style jack.
The serial port uses only three lines:
receive data, transmit data, and ground.
The modular jack has proven to be a
wise choice because of its durability. I
chose a handset-size jack to prevent accidental connection to a 50 Volt phone
line with its 100 VAC ringing signals.
These voltages would damage the Bear.
Processor & Memory
See Figure 4 (on pages 14-15) for the
functional schematic. If you're familiar
with the Motorola 6801 family, you'll see
that I've implemented a standard multiplexed memory bus. The data lines and
the eight least-significant address lines
are multiplexed at the processor, and
demultiplexed by a 74373 octal latch.
The 6811 Address Strobe (AS) signal
controls the '373.
The 6264 8Kx8 static RAM and 27C64
8Kx8 EPROM are the only bussed devices. The RAM is mapped at $0000 and
the EPROM at $EOOO. Because of the
simplicity of the external memory-map,
you can use A15 as the master chip
select, gated with the processor's E clock
for timing. The 6811's on-chip resources
reduce or eliminate the need for separate
peripheral chips such as DARTs, parallel
I/O, timer/counters, etc.
As memory prices fall, I'll change to
32Kx8 RAM. This way the Bear will
handle more data and more channels.
Adding more EPROM space for enhanced firmware is easy also. Because of
the size of the printed-circuit board,
adding more complex memory mapping
would require a CMOS PAL.
A neat feature of the 6811 is that the
internal RAM (256 bytes) and the internal I/O control registers (64 bytes) can
be "moved" by firmware to any 4K
boundary. These can be overlaid with
external memory without bus conflicts.
Both the internal RAM and control registers can overlay each other, sacrificing
the lowest 64 bytes of internal RAM.
A less-than-neat feature of the 6801family multiplexed bus timing, often
overlooked by designers, is that data is

10

MICRO CORNUCOPIA, #53, May, 1990

Figure 2-0rganization of 6811

MODA

(lJ!<)

11m

MODB
(VSTBY)

(Vpp)

XIl'm"

ROM BK BYTES

EEPROM 512 BYTES

[5
U

TIMER
SYSTEM

CPU CORE

RAM 256 BYTES

SERIAL
COMMUNICATION
INTERFACE

SCI

4B-PIN VERSIONS

A-Block Diagram

I~5
1

1

1

1

01 7

a IS-BIT ACCUMULATORS A ANa B

a

o

15

IX

o

I INDE~ REGISTER X

15

IY

o

I INDEX REGISTER Y

15

SP

a 1 STACK POINTER

15

PC

o

I PROGRAM COUNTER

C

I CONDITI ON

Is

X

H

I

N

Z

V

OR 16-BIT DOUBLE ACCUMULATOR 0

I

CODE REGISTER

CARRY/BORROW FROM MSB
OVERFLOW
ZERO
NEGATIVE
I-INTERRUPT MASK
HALF CARRY (FROM BIT 3)
X-INTERRUPT MASK
STOP DISABLE

B-Programming Model

Introducing ...

The 1st Family of
Low Cost, Powerful
Text Editors

\

VEDIT Jr.
$ 29
VEDIT
$ 69
VEDIT PLUS $185
Finally, you can choose the best editor for your needs without
compromising performance or paying too much. And organizations that want the "same" editor for everyone can pick VEDIT®
for most users and VEDIT PLUS for their power users.
The new family of VEDIT text editors are upwards compatible,
easy to use and offer exceptional performance, flexibility and
stunning speed. (3 to 30 times faster than the competition on
large files where speed really counts.)
Call for your free evaluation copy today. See why VEDIT has
been the #1 choice of programmers, writers and engineers
since 1980.

VEDIT Jr.- Unmatched performance for only $29.
All VEDIT editors include a pull-down menu system with "hot
keys:' context sensitive on-line help, pop-up status and ASCII
table, a configurable keyboard layout and flexible, unlimited
keystroke macros. Edit files of any size and any line length.
Perform block operations bycharacter, line, file or column. Undo
up to 1000 keystrokes- keystroke by. keystroke, line by line, or
deletion by deletion. Automatic indent, block indent and parentheses matching speed program development. Word wrap,
paragraph formatting, justification, centering, adjustable margins and printing for word processing. Run DOS programs.
VEDIT-A best value at only $69.
Simultaneously edit up to 36 files and split the screen into windows. Search/replace with regular expressions. Includes the
best compiler support available-menu driven, easy selection
of compiler options, supports "Include" files and MAKE utilities.
VEDIT PLUS-Ultimate programmer's tool for only $185.
VEDIT PLUS adds the most powerful macro programming
language of any editor. It eliminates repetitive editing tasks and
permits creating your own editing functions. The macro
language includes testing, branching, looping, user prompts,
keyboard input, string and numeric variables and control over
the size, position and color of windows. Source level macro
debugging with breakpoints and tracing. Macros developed
with VEDIT PLUS also run under VEDIT.
30 day money-back guarantee. Call for pricing of XENIX, OS/2
and FlexOS versions. Very attractive quantity pricing is available for schools, hardware and software vendors.

FREE Evaluation Copy*
Call1·800·45·VEDIT
Compare Features and Speed
Pull-Down menus
Pop-Up ASCII table
Keystroke macros
Regular Expressions
"Cut and Paste" buffers
Text (book) markers
Undo keystroke by keystroke
Undo line by line
Normal/max Undo levels
Variable tab positions
Configurable keyboard
Integrated mouse support
FILE LIMITS
Edit files larger memory
Maximum line length
Maximum lines/file
COMPILER SUPPORT
Menu driven
Select Compiler options
Support "Include" files
BENCHMARKS 5DK FILE
Simple search
Save and continue
1000 replacements
BENCHMARKS 3 MEG FILE
Simple search
Save and continue
60,000 replacements
Block-column copy (40 x 200)
Insert 1 Meg file in
middle of 1 Meg file
PRICE

VEDIT and CompuView are registered trademarks of CompuView Products, Inc. BRIEF is a
trademark of UnderWare, Inc. Norton Editor is a trademark of Peter Norton Computing Inc. OEd it
is a trademark of SemWare.
"Supports IBM PC, XT, AT, PS/2 and clones with CGA, MGA, EGA, VGA, Wyse 700, Amdek 1280
and other displays. Also supports Concurrent DOS, DESOview, Microsoft Windows,
PC-MOS/386 and most networks.
"Also available for MS-DOS (CRT terminals), TI Professional and others.
"Free evaluation disk is fully functional and can edit small files.
Reader Service

VEDIT
BRIEF 2.10 Norton 1.3 OEdit 2.07
Yes
No
No
Yes
No
No
Yes.
No
1
100+
No
100+
Yes
Yes
No
No
100
36
1
1
10
10
No
No
Yes
Yes
No
No
Yes
No
No
No
500/1000
30/300
Yes
No
Yes
No
Yes
Difficult
No
Yes
Yes
No
Yes
No
Difficult
65,535
>65,535
None

Yes
>8096
8,388,607

Yes
512
65,535

Yes
Menu
Yes

No
Difficult
No

-

-

0.2 sec
1 sec
3 sec

1 sec
2 sec
19 sec

1 sec
2 sec
17 sec

0.3 sec
1 sec
2.5 sec

1:40 min
1:05 min
3:18 min
2 sec

1:36 min
3:23 min
1:44 hour
30 sec

Cannot
Cannot
Cannot
Cannot

Cannot
Cannot
Cannot
2 sec

1:11 min
$69

15:13 min
$195

Cannot
$75

Cannot
$54.95

-

No
512
20,000
None

CompuView
Number 7

1955 Pauline Blvd., Ann Arbor, MI 48103
(313) 996-1299, Fax (313) 996-1308
MICRO CORNUCOPIA, #53, May, 1990

11

Figure 3-MC68HCll Family Members
ROM

EEPROM

RAM

CONFIG3

Comments

8K

512

256

$OF

Family Built Around this Device

MC68HCIIAI

0

512

256

$OD

Same Die as ' A8 but ROM Disabled

MC68HCIIAO

0

0

256

$OC

Same Die as ' A8 but ROM and EEPROM Disabled

XC68HCIIB8

8K

512

1

256

$OF

Early Experimental Version

XC68HCllBl

0

5121

256

$OD

'B8 with ROM Disabled

XC68HCIIBO

0

0

256

$OC

'B8 with ROM and EEPROM Disabled

MC68HCI1E9

12K

512

512

$OF

Four Input Captures and Bigger RAM and 12K ROut

MC68HCI1El

0

512

512

$00

'E9 with ROM Disabled4

MC68HCI1E0

0

0

512

$OC

'E9 with ROM and EEPROM Disabled4

MC68HC811A2

0

2K2

256

$FF

No ROM Part for Expanded Systems

MC68HCIID3

4K

0

192

N/A

Economy Version, No A-D and Smaller Memories4

Device Number

/

' MC68HCIIA8

Notes:
1. The EEPROM on B Series parts requires an external 19-volt supply for programming and is not byte erasable.
2. This 2K EEPROM is relocatable to the top of any 4K memory page. Relocation is done with four bits in the CONFIG register.
3. CONFIG register values in this table reflect the value programmed prior to shipment from Motorola.
4. Available in 1988.

only guaranteed for 10 nanoseconds following the trailing E-clock edge. Either
you carefully watch the number of gate
delays between the processor E-clock
and data receiving device or you
generate an intermediate clock edge.
6809 users have the quadrature (Q) clock
edge available to help grab data.
You can also operate the 6811 in the
Single-Chip Mode if you install the program in the internal masked ROM (great
for high-volume developers).
For the best of both worlds, Motorola
makes a companion chip, the 68HC24,
which restores lots of parallel I/O to an
external memory design .. This device
connects to the 6811's address/data bus
and restores the 16 bits of parallel 1/ 0
lost to the bus. It's as if the parallel ports
were built into the 6811! So you can have
it all .. " For a price.
SCI Software
The 6811 has an on-chip SCI for serial
communications. The SCI can generate
interrupts or set status flags and it
senses Framing and Overrun errors.

12

MICRO CORNUCOPIA, #53, May, 1990

Though the SCI won't automatically
generate and check parity, it will send
and receive parity bits supplied by software. Plus, you can use incoming data to
wake up the processor after you've left it
in WAIT or STOP (low-power) mode.
Since baud rates get generated by
dividing the processor's clock, you'll
want to choose the processor frequency
carefully. I selected 8.0 MHz so the Bear
can talk at all the standard baud rates.
The 6811's SCI output is logic-level,
not the ±12V standard for RS-232. I
chose not to use the familiar 1488/89 RS232 interface because of their hefty
power needs and their use of ±12V.
Instead I used the Maxim MAX232. It
has two line receivers and two line
drivers and it has a charge pump for
generating RS-232 line-output voltages.
By controlling the amount of power to
the charge pump, I control power consumption.
.
Real-Time Clock And Serial
Peripheral Interface (SP!) System
During the initial development of the

DataBear, I used the National MM58167
clock chip. This venerable device
worked well enough, but it didn't offer
absolute year clocking. And it required
four I/O lines plus control lines. On a
2.5x3.0 inch board, that's expensive!
Then I found the RCA 68HC68Tl
clock family, now second sourced by
Motorola. The' 68Tl family offers a 6811compatible SPI port, absolute year,
weekday, time to hundredths of a second, and 32 bytes of static RAM in some
family members. I selected a 32 KHz
tuning fork watch crystal as the timebase, although you can use crystals up to
8 MHz with higher power consumption.
A caveat for clock circuit designers:
tuning fork watch crystals have a poor
temperature coefficient compared to the
standard HC-6/U quartz plate crystals.
A typical watch cry~tal can be adjusted
to 32,768.0 Hz ±0.1 Hz. However, even
at that, the clock can gain or lose several
seconds per week.
It's funny; tell people that you have 3
ppm accuracy and they love it, but
several seconds per week is awful! How

do watches keep time so well? It helps to
keep the crystal at a constant 90 degrees
by strapping it to your wrist! (A warm
hand means a timely person.)
The DataBear communicates with the
clock via the 6811 SPI port. The SPI system is a high bit-rate, synchronous,
Master I Slave, serial data port using two
data lines and a clock.
The interface supports full duplex,
multiple masters, handles limited data
collision detection, and even offers interrupts and status flags.
In most simple single-processor systems, the processor gets to be bus
Master. All other SPI devices become
Slaves. You might scratch your head trying to work out clock polarity (CPOL)
and phase (CPHA), but careful scrutiny
of the data sheets usually solves the
problem. With only four possibilities,
you can always psyche it out with a
scope or debug monitor.
Once you've configured the SPI, all
you need is software which knows how
to talk with each slave. Each slave will
probably speak a slightly different protocol.
Our 68HC68T1 clock speaks data in
nybbles and (of course) in a reverse

order, but that's about par for the
course.
The Master sends data serially out the
Master Out Slave In (MaS!) pin, while
simultaneously generating a shift clock
on the SCK pin. Slaves send data to the
Master on the Master In Slave Out
(MISO) pin. Tie the 6811's SS line high
when it's the Master Device; use the pin
as a device select (Slave Select) when it's
the Slave.
Make sure that the SPI clock rate is
not too fast for any of the Slave devices,
especially CMOS parts. Each Slave will
probably have its own device select line,
so you can program a custom clock rate,
polarity and phase for each device.
I've found the SPI is probably the
most trouble-free subsystem in the entire
DataBear. More SPI parts seem to be
available each month. Other serial devices, such as AID or D I A Converters,
often work fine even though they are not
marketed as SPI compatible;
AID Converter Subsystem
The 6811 AID Converter is a ra-

tiometric converter. The output of the
converter is a digital ratio of the input
signal to the voltage references. With the

QEdl1t™

6811, these references are Vr! and Vrh.
Any voltage between Vrl and Vrh will result in an eight-bit output according to
the formula:
Output (0-255)

The Fast, Easy-To-Use, Full-Featured Text Editor. Now Also Available as a TSR Utility!

QEdit is packed with features:
o Completely configurable, including keyboard and colors
o Simple to install, requires less than
SOK disk space
o Simultaneous file editing-limited
only by available memory space
o Open up to eight windows
o "Pop-Down" menu system and
customizable Help screen
o Easy-to-use macro capabilityincluding keyboard recording

QEdif $5495
M

ADVANCED

from within QEdit
[J Wordwrap and paragraph
reformat capability
o Import files and export blocks
D Great for use with laptops-QEdit
saves battery drain by editing files
entirely in memory

System Requirements _ _ _ __
QEdit requires an IBM PS/2, POAT, PCIXT,
PC, POJr, or compatible. Minimum system
requirements are 64 KB of memory, PC-DOS
2.0 or MS-DOS 2.0 or greater, 50 KB of disk
space. QEdit runs GREAT on floppy based
slstems and laptops.
QEdit TSR also requires EMS, XMS, or a
hard disk.

$7900
OS/2

ALSO.~yAILABLE

Q Edit for

x 255

Continued on page 16

THEt;1

o Column blocks
o Recover deleted text
o Exit to DOS or DOS shell from
within QEdit
o Execute command-line compilers

Vrh _ Vr/

It's easy to tie Vrl to ground and Vrh
to Veo but digital noise can be a problem.
You can reduce the noise by adding an
RC-filter to the Vee power at Vrh. Better
still, use a zener diode or adjustable voltage reference to regulate Vrh.
Also be careful about how you route
a ground to Vr!. If digital currents flow in
ground traces used for Vr!, you'll have a
noise problem again.
I used a National LM235-2.5 as a reference diode for the DataBear. The
LM136/236/336 series of references are
adjustable, conditioned zener diodes.
The nominal tolerance is 5%, and I use a
pot to divide the reference's output
down to 1.280 Volts. Refer to the "Voltage Reference" section of Figure 4 for a
schematic of the DataBear reference circuit.
The AID Converter in the 6811 has
different modes of conversion controlled

~
ttl EDITOR
ADVANCED :-':,;;..'"____________
_

QEdit has always been the text
editor that combined price, performance and value. QEdit TSR makes
that value even better by giving
you instant access to the power of
QEdit-no matter what program
you're working in.

Input - vr/

•• QEdit is a
great piece of software. Highly
recommended. ~ ~
John C. Dvorak,
PC Magazine

September 12, 1989
•• QEdit is, without question,
the smallest, fastest, most
versatile text editor in the
DOSworld.~~

P. L. Olympia, Ph.D.,
DBMS
July, 1989

INTRODUCING QED IT TSa
Instant Access to the
World's Best Editor
SPECIAL PACKAGE PRICE OF ONLY
$®fiJ'OO INCLUDES
'i:I
QEDIT ADVANCED

To order direct call

404·641·9002
extension 12

[EB ~

.cards
. Now, whose
system would benefit from a case of slithers?
nderstand now, I set out to do
what I was supposed to-build a
voice-control system using the
Motorola VCP-200 (Radio Shack #2761308). This chip will recognize five
phrases independent of the speaker: go,
stop, turn left, turn right, and reverse. Its
data sheet (from Radio Shack) includes a
schematic for the chip's circuit. All I
needed to do was connect the chip to the
microphone and analog amplifier/filter
from Micro C #50.
But I didn't do it yet. I became distracted trying to imagine how I'd use my
apparatus. (I should have listened to
Larry, who never gets bogged down in
these kinds of details.)
So I digressed-what was I to do
with the signals from the chip? How
could I use commands like: "left turn"
and "reverse?"
I speculated-draw something on a
screen: an entity which moved under
voice control (leading perhaps to a vocal
PAC MAN). But what entity?
Then (as though in a vision on a hot,
hazy day in the high desert) it came to
me: snakes. A snake (an object) is a
bunch of linked segments (also objects).
To move the snake forward, I'd create a
new segment, call it the head, then tell it
(the lead segment) to send a message
back to the tail saying "add a new segment" or "drop a segment."
So I built snakes instead of connecting hardware. In the process, I generated

U

20

MICRO CORNUCOPIA, #53, May, 1990

some interesting C++ code and utilized
several C++ 2.0 features. SNAKES, my
code creation, is (of course) a riot.
When you run SNAKES, tell it how
many snakes you want, how long you
want each snake to be, and how quickly
you want to see action. By increasing the
delay factor, you can slow things down
as much as you like. Each has its own
ASCII character.
I compiled SNAKES using Zortech
C++ version 2.06 and their disp package
to increase display speed. In the Micro C
listing, I've #ifdefed disp out so SNAKES
will work (albeit slower) with other implementations of C++. (These include
UNIX as long as you have an ANSI terminal, or are willing to rewrite the brief
segment::drawO and segment::eraseO
routines.) You can also easily change
these routines to support graphics.
Classes
Figure 1 (SNAKE.HPP), the header
file, contains the class definitions for
point (which holds x-y information),
segment, and snake. I made point a
struct (a class with all members public)
because I wanted the convenience of
having coordinate information packaged
together without having to bother with
private data.
The constructor simply initializes the
data elements x and y using the initializer list. (That is, you can treat built-in
types as if they had constructors in the
initializer list only.)
We overload the == operator to determine whether one point is equivalent to
another. This prevents a snake from
backing over itself.
random_pointO is a static member
function which returns a random point.
random_pointO creates a temporary object by calling the point constructor.

Note: we don't need an identifier since
the object (a point) immediately returns.
A static member function addresses
the class as a whole, not a specific instance of the class. This could have been
an independent (non-object contained)
function, but I made it static so anyone
using class point can now see (and
access) it. Also the identifier random_point is local to class point, and
doesn't "pollute the global name space."
For this and other reasons, static member functions are an important addition
to C++ 2.0.
Segments
The segment class contains a pointer
to the previous segment in the list. So
any segment can send a message to the
segment behind it ("drop the tail segment, add a segment").
The point object lets the segment locate itself on the screen. It draws itself
and prevents its own redundancy-the
entire snake slithering over itself (although other snakes may slither over it).
segment displays itself on the screen
using a pattern and orients itself through
a variable called heading of the
enumerated type direction. heading determines a snake's direction and tries to
keep it going that way.

(Aside: my original design didn't include
heading. I added it after I got the system
working and saw snakes doubling back on
themselves, creating an ugly mess. Fortunately, it was a simple matter to add heading to the existing system. In general, try to
get the system up quickly. You can't know
some things while you're working on the design, only after you see the design working.
Local Enumerations & Anti-pollution
Notice that enum direction is inside
the class definition. In C++ 2.0, enumera-

By Bruce Eckel
Revolution2
. P.O. Box 760
Kennett Square, P A 19348

Figure 1- SNAKE.HPP
#include 

II

size_t definition

struct pOint { II coordinate representation
int x, y;
point (int xi = 0, int yi = 0) : x(xi), y(yi) {}
int operator==(point rval) { II test equivalence
return x
rval.x && y == rval.y;

When you run
SNAKES, tell it how
many snakes you
want, how long you
want each snake to
be, and how quickly
you want to see
action.

==

static point random-point();

II

generate random pOint

};

class segment {
segment * previous;
point sp;
II position on screen
char pattern; II to display on the screen
enum direction heading; II "tendency of motion" of the snake
void erase () ;
void checkheap(); II make sure this is on the heap!
public:
II this enumeration is local to the class:
enum direction { UP, DOWN, RIGHT, LEFT };
void draw () ;
II re-define operator new for this class ONLY:
void * operator new(size t sz);
segment(point p, char ptrn);
segment(segment * prv, direction dir);
-segment () { erase (); }
int shed tail(); II go back to the tail and drop it off
point seq-point() { return sp; }
int cross over(point); II is this point an existing segment?
direction-path() { return heading; }
void redraw tail(); II redraw everything from here back

};

-

class snake
segment * head;
int length, maxlength;
public:
snake(point p, int size, char ptrn);
void crawl(direction);
void slither () ;
};

•••

tions are local to classes. The enumeration tag is global (everyone can refer to
direction). But the enumeration names
are local to the class, so they don't pollute the global namespace-you must
refer to them as segment::UP, etc.
Preventing namespace pollution is a
very important feature of object-oriented
languages. Big projects often become unmanageable simply because they create
more names than they can keep up with.
You can also use enumerations local
to a class to create "local const" values.
You can define a const inside a class, but
you can't initialize it when you define it
(unlike its definition everywhere else,
when you must initialize it). Do it instead in the constructor initializer list
(thus you can end up with different
values for the const depending on which
constructor you call).
However, you can create the equivalent of a local const and initialize it at
the same time using an untagged enum,
like this:
class x {

MICRO CORNUCOPIA, #53, May, 1990

21

enum {red=7, blue=4};

Iino

tag!

II

Figure 2 -SNAKE.CPP

};

Now you can use the identifiers red
and blue just like const values. Well, almost-at the time I wrote this, different
compilers exhibited different behaviors
when I tried to use red as a dimension in
an array definition. I'm not sure how it's
supposed to work. Note that you can
never use even a const as an array dimension in ANSI C.
Class Overloading Of "new"
Another feature of C++ 2.0 lets you
overload the operators new and delete
(which control dynamic memory allocation) on a class-by-class basis. Normally
you do this when you want to create dynamic objects more efficiently. I've done
it here because segment objects must
never be created on the stack, only on
the heap.
To signal the programmer, segment::operator newO (shown in Figure
2) puts a "signature" in the dynamically-allocated memory. The function
segment::checkheapO looks for this signature. If it doesn't find the signature, it
sends a message to the programmer. It
isn't foolproof, but will usually detect
misuse. All segments must be created on
the stack because they're only destroyed
by segment::shed_tailO when it calls delete.
"segment" Constructors
segment has two constructors. The
first-for the initial segment of the
snake-establishes the starting point and
the pattern to be used. The second
makes a segment which is linked to an
existing segment, in a specified direction. Note that both constructors call
checkheapO to insure the object was
created on the heap ..
The first constructor (Figure 2) is
straightforward, but the second must
"wrap" the coordinate of the new segment around the display screen if it goes
off the edge. Also, the drawO method
isn't called in the second constructor,
since a new snake may need a new segment which crosses over an old segment
of itself. The calling function must check
the new segment before actually drawing it.
Recursive Member Functions
The next three functions are pure fun.
They recurse back down the snake

22

MICRO CORNUCOPIA, #53, May, 1990

#include "snake.hpp"
#include 
#include  II assuming ANSI terminal or ANSI.SYS on a PC
#include 
#include  II memset()
#ifdef
ZTC
II use disp package wi Zortech
#includ;-
#include 
#endif
const height = 23; II screen height
const width = 78; II screen width
point pOint::random-point() {
return point(rand() I (RAND MAX/width),
rand() I (RAND:MAX/height»;
void * segment::operator new(size t sz) {
void * tmp = ::new unsigned cha;[sz]; II allocate with global new()
memset(tmp, 'x', sizeof(segment»; II fill with x's
return tmp;
void segment::checkheap()
if(pattern != 'x') { II check for memset pattern
fputs("can only create segments on the heap!", stderr);
exit(l);

segment::segment(point p, char ptrn)
II capriciously choose old heading:
: sp(p), previous(NULL), heading (LEFT)
checkheap();
pattern = ptrn;
draw 0 ;
segment::segment(segment * prv, direction dir)
: previous(prv), sp(prv->sp), heading (dir) {
checkheap();
pattern
previous->pattern;
II if(pattern++
'z' + 1) pattern
'a'; II pattern test ...
II create new segment in appropriate direction & wrap:
switch (dir) {
case UP :
if(--sp.y < 0) sp.y
height;
break;
break;
case DOWN :
if(++sp.y > height) sp.y = 0;
break;
if(--sp.x < 0) sp.x = width;
case LEFT :
case RIGHT : if(++sp.x > width) sp.x = 0;
break;

=

==

=

=

II
II

Recursive function to go back to the beginning of the
sequence of segments, to find the tail and remove it:
int segment::shed tail() {
if (previous
-NULL) {
delete this; II NULL means we're at the tail
return 1; II indicates to the next call 'up' that the tail was
found
}

II

recursive call until tail is found:
if(previous->shed_tail(»
II 1 means the call removed the tail
previous = NULL;
return 0; II means the call didn't remove the tail

II Recursive check to see if p crosses an existing segment:
int segment::cross over(point p) {
if(previous == NULL) return p == sp;
if(p
sp) return 1;
II recursive call to go to the end, or a cross point:
return(previous->cross_over(p»;

==

II Recursively redraw entire snake:
void segment::redraw tail() {
draw();
if(previous == NULL) return;
Continued on page 23

towards the tail. It's as if you're traversing a linked list, with each link an
object with its own member functions.
This is inspired by the much more
sophisticated "agent" example in Ravi
Sethi's Programming Languages-Concepts
& Constructs (Addison-Wesley, 1989). If
the rest of the book is anything like this
example, it's a gem.
The function segment::shed_tailO
must do three things. If the current segment is the tail (in which case the previous pointer will be NULL), then it
deletes the tail (thus the reason for forcing segments to be made on the heap).
However, if the tail was just deleted,
then the segment just ahead of the tail is
the new tail.
Thus, when the tail is deleted, the recursive function returns a 1 to tell the
next segment up that it should set its
previous pointer to NULL to indicate it's
the new tail. Finally, if nothing happens,
it returns a a to tell the next segment to
do nothing but return ain turn.

Continued from page 22
previous->redraw tail();

void segment::draw() {
#ifdef
ZTC
disp move (sp.y, sp.x);
disp:?utc(pattern);
#else
printf("\x1b[%d;%dH", sp.y, sp.x);
putchar(pattern);
#endif

II move cursor

}

void segment::erase()
#ifdef
ZTC
disp move (sp.y, sp.x);
disp:?utc(' ');
#else
printf("\x1b[%d;%dH", sp.y, sp.x);
putchar(' ');
#endif

// move cursor

}

snake::snake(point p, int size, char ptrn)
: length(O), maxlength(size) {
head = new segment(p, ptrn);

// Just mindlessly goes where you tell 'it:
void snake::crawl(direction dir) {
head = new segment(head,dir);
if(++length >= maxlength) {
--length;
head->shed_tail();

Don't Tread On Me!
segment::cross_overO takes its argu-

// find it's own way, tending to the current path:
void snake::slither() {
const int chance = 10; // 1 in 10 chance to change directions
direction old = head->path();
1/ Choose a new direction by first throwing the dice to decide
/1 whether to actually change direction. If so, choose a new
II direction randomly:
if (rand() I (RAND MAX/chance) != chance/2)
direction dir ; old; II change only if magic number is rolled
else {
dir = (direction) (rand()/(RAND MAX/4»;
head->redraw_tail(); 1/ occasionally redraw everything
segment * new seg = new segment(head, dir);
1/ check that-the new segment doesn't cross over the existing snake:
if(head->cross_over(new_seg->seg~oint(») {
delete new seg;
return;
new direction causes cross-over

/7

// successfully found new direction
head = new seg;
head->draw() ;
if(++length >= maxlength)
--length;
head->shed_tail();

static void pause (int rate)
for (int i = 0; i < rate; i++)

Unique
Programmer's
Books & Tools for
MS-DOS & OS/2
Professional function
libraries and advanced books
by Michael J . Young. Create
high-performance MS-DOS
programs, TSRs, OS/2
programs, and Presentation
Manager applications.
Items not available
anywhere else!
C and assembly language!

main(int argc, char * arqv[]) {
if( argc < 4 ) {
fputs("usage: snake num of snakes size factor pause rate\n"
"CTRL-BREAK to quit \n", stderr); exit(l);
}

printf("\xlb[=7l"); // turn off ANSI line wrap
#ifdef _ZTC_

Continued on page 24

Please call or write for
free catalog:
Young Software Engineering
20 Sunnyside Avenue, Suite A
Department MC01
Mill Valley, CA 94941

415/383-5354
Reader Service Number 207

MICRO CORNUCOPIA, #53, May, 1990

23

ment, a point, and checks to see if it's
equivalent to the segment's point. If so,
it returns 1 to indicate yes (which means
the point isn't a good choice). If not it
calls previous->cross_overO to check
back until it finds a crossover point or
the tail.
segment::redraw_tailO calls drawO,
then recursively calls itself until it encounters its tail, thus redrawing the entire snake. drawO and eraseO are the
only functions that output anything. So
if you want to adapt the program to a
new system, you only have to change
these (and a couple of minor places in
main()).
The snake" Class
The snake (Figure 1) is quite simple.
A snake consists· of a pointer to a segment called head, and numbers indicating the current length and maximum
length. A single constructor (Figure 2)
creates a new segment for the head, and
initializes length and maxlength. After
that, the snake will crawlO in any direction you say (for the voice command
system).
snake::crawlO simply assigns head to
a new segment made from the previous
head (thus chaining the snake together).
If the snake is too long, it sheds its tail.
II

Chance Slithering
snake::slitherO is a more interesting
function. It "throws dice" using the
ANSI ·C library function randO, which
generates random numbers, to decide
whether to change directions. Note that
RAND_MAX is a constant defined in
stdlib.h which is the maximum value
randO will return. Thus the statement:
if (rand() I
chance/2)

disp open () ;
disp-move(O,O);
disp- eeop () ;
#else 71 ANSI terminal
printf("\xlb[2J"); II clear screen
#endif
II seed the random number generator:
time_t tnow;
time (&tnow);
srand(tnow);
II Create a whole nest of snakes:
const num_of_snakes
atoi(argv[1]);
const size factor
atoi(argv[2]);
const pause rate
atoi(argv[3]);
snake ** snakes
new snake*[num of snakes];
for(int i
0; i < num of snakes; i++)
snakes[i]
new snake(point::random~oint(),
#if 0 II for randomly-chose sizes:
rand() I (RAND MAX/size factor), i + '0');
#else II for fixed si~es: (avoid the bell)
size_factor, «i + 1) % 254 == 7) ? 1 : (i + 1)
#endif
#ifdef
ZTC
while(Tkbhi t () )
#else
while (1) {
#endif
for(i = 0; i < num of snakes; i++) {
snakes[i]->slither();
pause(pause_rate);

=

=
=
=

=

=

%

254);

•••
Figure 3-PAUSE.C : Portable function for delays
#include 

1* This is a pure ANSI C function, so it's portable: *1
void pause (int hundredths) {
clock t start time = clock(); 1* current time *1
while«(clock() - start time) * 100)/CLOCKS PER SEC < hundredths)
; II wait in this loop for the delay time
-

•••

(RAND_MAXI chance) !=

creates a random number between 0 and
chance, and tests to see if it's equivalent
to chance/2. Thus, in a perfect distribution you have a one in chance probability the statement will be true.
Notice that normally you would
think like this: randO/RAND_MAX returns a number between 0 and 1, so just
multiply that by chance to get a number
between 0 and chance. But this would be
wrong. Since the compiler will do integer division, randO /RAND_MAX will
almost always return O!
Thus you must force RAND_MAX to
be divided by chance first to insure integer division doesn't mess up the an-

24

Continued from page 23

MICRO CORNUCOPIA, #53, May, 1990

swer. This logic works in any situation
(there are others in SNAKE) where you
generate a random number in a particular range.
If the above "if" statement is true,
snake::slitherO will slither the snake in
the same direction by using the old
direction. (Thus you can make the
snakes do more twists and turns by reducing chance.) If it's false, generate a
random number between 0 and 4 and
cast it into a direction (to indicate one of
the directions in segment).
Note that C++ 2.0 forces you to cast
an integer into an enum explicitly; it
won't just allow you to sneak it by-better type checking!
Next, we create a new segment, but

we don't assign it to the head-yet. First,
we test to insure that the new segment
won't cross over an existing segment. If
it does, we delete' the segment, and the
function returns without doing anything. The next call to slitherO will try
again with a new direction.
When running the simulation, you'll
see that sometimes a snake will coil in
upon itself and be unable to move. (If
you run the simulation long enough, all
snakes will eventually end up this way.)
A Flexible mainO
In The Tao of Objects (a book I am
coauthoring with Gary Entsminger), and
we maintain that one of the fundamental
tenets of object-oriented programming is

"dynamic programming style." In other
words, we want to determine the conditions (Le., the number and type of objects) of a program at runtime rather than
at compile time. By delaying system decisions, we allow new discoveries and adjustments to be made after we've
"finished" the system.
Not only does this allow us to modify
a program without reprogramming, but
it also allows the user to discover things
about the system the programmer never
even dreamed of (which may work
themselves back into a future version of
the program).
Whether designers like it or not, all
programs go through cycles of design,
use, redesign, reuse, redesign, etc. This
(we maintain) is one of the reasons existing design techniques don't work so
well-they provide good structure and
documentation (at least theoretically),
but not good design flexibility.
In mainO (Figure 2), you can see that
the user specifies the number of snakes,
the size of the snakes, and the speed of
the simulation by entering parameters
on the command line.
After the ANSI C random number
generator is seeded using the current
time, the arguments are picked off the
command line and an array of pointers
to snakes is created on the heap. (Astute
readers will notice I never free this
space-sloppy, but fairly safe since the
program releases the space when it
exits.)
The #ifdef statements determine
whether the sizes of the snakes are
chosen randomly or are a fixed size
(both options use size_factor).
I create a delay function (called
pauseO defined just before main()) using
the ANSI C time functions declared in
time.h (see Figure 3).
Get Distracted
I had a lot of fun playing with this
program-got mesmerized actually. If
nothing else, it's a terrific way to waste
CPU cycles.
The source code and SNAKE.EXE are
available through the usual Micro C
channels. The source- is also part of the
Using C++ source-code disk (see the
Revolution2 ad this issue).

Eventually, I combined the articles
into a self-published book, Computer Interfacing with Pascal & c. (Academic
Press will publish a very revised and expanded version called PC Interfacing with
C & C++ this fall). Next came Using C++,
and soon you'll see The Tao of Objects cowritten with our pal Gary Entsminger.
Writing for Micro C opened the doors
to other magazines (I'm the C++ editor
at The C Gazette), and speaking at SOGs
gave me the practice and nerve to speak
at "real" conferences. Most important, I
met Larry, Gary, and the gang at Micro
C. No question: writing that first article
was one of the best moves I ever made.
I started in the "brown wrapper"
days ("Hmmm ... is this Micro C or
Naked Volleyball Quarterly?"). The magazine has vastly improved in look and
style, and it seems like we've just hit our
stride. I'm sad to see it go, but perhaps
we've finished creating it. Maybe it
would have become an Institution rather
than a platform for experimentation
(Micro C never did figure out what it was
about.. .. ).
There are all kinds of reasons that
Micro C shouldn't have happened: it
wasn't commercial enough, not enough
market research, blah, blah, blah. It did
happen though-a rare and magical
fractal-chaotic event. It happened because we wanted it to happen, and more
important, because you wanted it to happen.
Farewell, and look for me in the computermags ....
Bruce Eckel is the author of Using C++

(Osborne/McGraw-Hill, 1989) and a member of the ANSI C++ committee. He's the
owner of Revolution2, a firm specializing in
C++ training and consulting.
Reference
Sethi, Ravi; Programming LanguagesConcepts & Constructs (Addison-Wesley,
1989).

•••

Farewell
I wrote my first article for Micro C
four years ago. I expected to be
swamped with consulting offers. I
wasn't, but I wrote for every issue since.
MICRO CORNUCOPIA, #53, May, 1990

25

Building A Two-chip Terminal
Motorola's 68HC705 Makes It Si111ple

Karl builds the world's simplest terminal
around one of Motorola's newest controller
chips.

his battery-powered RS-232 terminal has it all; it's cheap, easy to
build, uses readily-available parts,
and boasts the newest micro controller
technology. With this project, you can
get started in 68HC705 design while you
build a versatile piece of computer gear.
The terminal's features make it ideal
for remote and low-power use. The LCD
readout and CMOS micro controller
(MCU) keep the current drain to below
40 mAo Use of a special-purpose levelshifter IC allows RS-232 operation from
a single 5 Volt supply.
The 68HC705's on-chip serial port
and timer system help the terminal run
at 9600 baud while controlling the display and monitoring the keyboard. The
design is flexible enough to allow parts
substitution, if you can't find exactly
what I used in my project.

T

The Display
My screen is a two-line liquid crystal
display (LCD). You can find many formats of LCDs in most of the large mailorder ads. Although this project uses a
2-line by 16-character display, feel free to
use anything else you like. Just be sure
your display is compatible with the one
shown.
How do you determine compatibility? Look for an LCD that uses the Hitachi HC44780 LCD controller chip. This
is a surface-mount technology (SMT)
chip, soldered onto the back of the display. It usually appears with one or
more Hitachi HC44100 driver chips (also
SMT).
The HC44780 chip does more than
handle character generation. It contains
an 80-byte buffer. LCDs built with this

26

MICRO CORNUCOPIA, #53, May, 1990

chip can therefore display only a maximum of 80 characters.
But for many applications, a 2-line by
40-character (or 4-line by 20-character)
display will do. By shopping around,
you can find several different formats of
these LCDs. Examples include the Hitachi H2750 (1 row of 16 characters), Hitachi LM032L or Optrex DMC20215 (2 by
20), or Hitachi LM044L (4 by 20).
Mail-order suppliers known to have
carried LCDs recently include Alltronics,
TimeLine, and Digi-Key. Also check
your favorite surplus house; these displays are becoming common surplus
items.
Most LCDs include some form of
backlighting. The most common style
uses a strip of electroluminescent material (ELM), mounted behind the panel.
When you apply the proper AC voltage
to the two pins on the ELM, it emits a
soft blue or green light. This makes your
terminal easy to use at night or in low
light.
I added a special, three-terminal voltage converter designed for use with
ELM. This module changes 5 Volts DC
to 200 Volts AC at about 500 Hz, giving
my display a soft blue backlight.
You might have to scrounge pretty
hard to come up with such a converter;
mine came off a discarded laser-tag arcade game. Half the size of an ice cube,
the converter's case carries the part
number NEL-D32-45, but no manufacturer's name.
I have also seen a similar part offered
in the Digi-Key catalog. The terminal
works fine without the converter, of
course, but backlighting adds a nice
touch.
The Keyboard
I chose a surplus Cherry keyboard
(very old, it uses TTL chips). This unit
provides a IS-pin connector for hooking
up to a computer. When you press a key,

the ASCII code associated with that
character appears on seven pins of the
connector, while a strobe pin goes from
ground to +5 Volts, signaling there's
valid data.
This means I only need ten wires to
hook up my keyboard; seven data bits,
one strobe line, power, and ground. I
can use a single eight-bit input port to
handle all my keyboard data. (Of course,
the TTL chips make this keyboard a real
power hog; oh well, it only cost $4.)
With this arrangement, I get all the
control codes, all upper-case letters,
special characters, and numbers; no
lower-case and no PC function-key
sequences. Still, it'll serve my purpose.
There are always other options. For
example, you could use a surplus, unencoded switch matrix. This type of keyboard consists of a grid of keys witches,
with the wires tied to each row and
column brought out to a connector.
Pressing a key shorts a specific row to a
specific column; your software just scans
each row (or column) until it detects a
closed circuit. You can then use the row
and column where the short occurred to
determine which key was pressed.
Though this sounds like extra software (it is), the scanned matrix keyboard
offers some benefits. Since the matrix
consumes no power, it makes a perfect
choice for low-power applications. The
surplus market seems glutted with a
variety of unencoded keyboards. If you
shop around, you will surely find just
the right size, shape and style. And the
price will be right; I picked up a brandnew unencoded keyboard from United
Products for just a few dollars.
You could also opt for a PC-style keyboard. The Keytronics 100-style keyboards are usually available; I recently
saw an ad from TimeLine that offered a
new XT keyboard for $15.
Unlike the other two keyboard systems, the PC units provide data for a

By Karl Lunt
th
2133186 Pl., SE
Bothell, WA 98012
(206) 483-0447

Wth this project,
you can get started
in 68HC705 design
while you build a
versatile piece of
computer gear.

pressed key via a serial line. A corresponding clock line tells the host computer exactly when each bit of the data
packet is valid. (Check out Bill Curlew's
article, "Building An IBM PC Keyboard
Translator," in the February IMarch
1990 issue of Circuit Cellar INK, for
details on PC keyboards.)
This synchronous transmission system means the keyboard can send (and,
in some cases, receive) data over just
three wires. At first glance, none of
IBM's three available formats will work
without additional logic. They just aren't
compatible with the 68HC705' s synchronous serial line (Motorola calls this
port the serial peripheral interface, or
SPI).
The problem lies with the number of
bits transmitted per keypress. Mode 1
(the oldest and simplest format) uses
eight data bits and one start bit for each
transmission. The other two modes use

additional bits and support bidirectional
transfers.
The SPI, however, can only accept a
transfer of exactly eight data bits; it does
not need nor expect a start bit. To hook a
PC keyboard to the SPI, you could add a
serial-to-parallel converter to the
68HC705. Or, you could put extra circuitry inside the keyboard to turn the
nine bits into two eight-bit packets.
Neither way was acceptable (I wanted
this project to take only two chips), so
the PC keyboard was out.
As I look that last paragraph over, I
realize there is (as always) another way.
Hooking the keyboard's clock line to an
input port line and the keyboard's data
line to the MCU's TCAP (timer capture)
line would do the trick nicely.
Following a keypress, the data line's
start bit going high-to-Iow would cause
an interrupt and transfer control to the
TCAP server routine. This routine

samples the clock line on the input port,
looking for a low-to-high transition.
Every time such a change occurs, the
routine reads the level on the TCAP line
to get the value for that bit-time. The
server could then construct the keycode,
wait for the stop bit to appear, and exit.
Okay, so you can add a PC keyboard
to this project and still use only two
chips.
The Maxim MAX232 Chip
I've built a couple of projects with
this chip and love using it. Being able to
run RS-232 from a single +5 Volt source
reduces circuit complexity, chip count,
and board size.
The Maxim chip works by generating
+8 and -8 Volts on-chip from the system's +5 Volt supply, using a chargepump technique. You hook up four 22
mfd capacitors for the charge-pump; the
chip gives you two output and two
input buffers that are RS-232 compatible.
You might run into some problems,
however. The chip does not supply a lot
of current to the RS-232 buffers. If you
try to push 9600 baud over a long cable,
you could get errors.
A new version of this chip, the
MICRO CORNUCOPIA, #53, May, 1990

27

MAX233, puts the capacitors on the
chip. This will further reduce the parts
count for your RS-232 interface. But this
chip suffers from the same low drive
current as its MAX232 brother. At least
one engineer I know has cautioned me
about using either chip to talk distances.
Having said this, I'll add that I have
yet to see any data errors directly due to
the Maxim devices. Plus, both enjoy a
wide following in the industry. I certainly intend to keep using them.
TheMCU
Consider what it takes to make an
RS-232 terminal. You need a bidirectional serial port good for 9600
baud and plenty of I/O lines to hook up
to your LCD and keyboard.
You also need a timer system for
properly clocking the control signals into
the LCD, an interrupt system for catching the high-speed data flow on the serial line, and enough RAM and EPROM
to hold your program.
Motorola's 68HC705 provides all this,
at a current drain of less than lOrnA.
Check out Micro C Issue #49 for an indepth look at the 68HC705. For now, I
will only discuss those aspects of the
MCV needed by the two-chip terminal
project.
You control the extensive array of
I/O and timing functions on the MCV
by writing 8-bit values into specially assigned memory locations, called registers. For example, you can use all eight
bits of I/O port A as outputs by storing
the value $FF into location $04, known
as DDRA (data direction register A).
By using a 4.0 MHz crystal, the MCV
can hit 9600 baud on the serial port. Although the project currently does not
support it, you could easily change baud
rates from the keyboard or a row of dip
switches. To alter baud rates, simply
write different timing values to two
baud-rate selector registers.
You must wait a prescribed amount
of time after each change of the LCD. I
use the MCV's 16-bit timer system to
generate 200 Ilsec time slices. The LCD
routines simply wait until the correct
number of slices (called tics) elapse
before sending the next command.
Since the terminal could receive a
stream of 9600 baud data, the MCV
must handle the incoming data immediately. The MCV's serial communication
interface (SCI) can generate an interrupt
upon receiving a character from the serial port.

28 MICRO CORNUCOPIA, #53, May, 1990

Figure l-LCD and Keyboard Interface to '705

68HC7~5

11
10
9
8

7
6

LCD

P1

PA~

DB4

1

PAl
PA2

f[)

t::J

4

E

6

39

14

RS

5

PA5

13

DB7

4

PA4

12

DBS

3

PA3

11

DBS

2

6

47pf ~ 1~

1

+5V

3

5.6M

~

5
Vee

~ 9

38

2

4 MHz
+5V

+5V
4

*

22f.1F
+

~

I

+5V

rt

+
2 21JF
•

+

l~K

IRQ
2
30
29

2

S

RS-232

POl

-=

3

PD0

9

2

+5V

.. 7

1

~~
7805 VIEW

IN

OUT

GND

+

+SV

IN4~~1

l~IJF

+

-=

9-3~V

DC

-=
68HC7~5

12
13
14
15
16
17
18
19

.
---- ....
P2

PB0
PBl

~

_.

PB3
PB4
PBS
PB6

~

--

P87

(15)

2

BIT 1

(14)

3

BIT 2

(13)

.
--. .•

PB2

KEYBOARD
BIT 0

4

BIT 3

(12)

5

BIT 4

(10)

6

BIT S

(11)

BIT 6

(9)

STROBE

(6)

7
8

•
•

+5V

~ 9 ••
.-----+5V

r---

1~

..

GND

(4)
(8)

End diskette compatibility problems.
Call Emerald Microware.
CompatiCard I by Micro Solutions
This four drive universal floppy controller will let you
run up to 16 disk drives (4 per CompatiCard), including
standard 360K, 96 TPI, high density 1.2M, 8" (SSSD
or DSDD), and 720k/1.44M 31f2" drives. The CompatiCard I comes with its own MS-DOS driver, utility programs, and will let you boot on an XT (must be used
as a secondary controller on an AT or 386). Use it
with UniForm-PC for maximum versatility.
CompatiCard I Board. . . . . . . . . . . . . .. $ 119.95
CompatiCard I with UniFORM-PC. . . .. $ 179.95
8" drive adaptor board .............. $ 15.00
External drive cable set. . . . . . . . . . . .. $ 15.00

CompatiCard II by Micro Solutions
Two drive version of the CompatiCard, for the XT or
AT. Same drive support as the CompatiCard I except
no 8" or single density.
CompatiCard II . . . . . . . . . . . . . . . . . . .. $ 89.95
Special
CompatiCard II with
internal 1.2M or 1.44M drive. . . .. $ 199.95

***

***

CompatiCard IV by Micro Solutions
Meet the newest four drive controller in the CompatiCard family. This CompatiCard may be used as a
primary or secondary controller in almost any PC, AT,
or 386 System. Boot or use 360k, 720k, 1.2M, 1.44M,
or 2.88M, at any location in your system. The CompatiCard IV has a BIOS ROM on board so no external
driver software is required.
CompartiCard IV. . . . . . . . . . . . . . . . . .. $ 139.95

CP/M

II ~ ]
"

'MS.oOS

EJAP:- [1]
UniForm-PC

by Micro Solutions

Have you ever needed to use your CP/M diskettes
on your PC? Now you can access your CP/M files
and programs on your MS-DOS computer just as you
would a standard MS-DOS diskette. UniForm allows
you to use standard DOS commands and programs
right on your original diskette without modifying or
copying your files. UniForm-PC allows you to read,
write, format, and copy diskettes from over 275 CP/M
and MS-DOS computers on your PC, XT, AT, OR 386.
With UniForm-PC and the CompatiCard, you can use
5%" high density, 96TPI, 31f2" (720k/1.44M), and
even 8" drives.
UniForm-PC by Micro Solutions ...... $ 64.95
Also available for Kaypro, & other CP/M computers

zao Coprocessor Board
by Micro Solutions

Don't throw out all of those old, reliable CP/M programs, run them at LIGHTNING speed on your PC
or AT with the UniDOS 8MHz. Z80 coprocessor
board. And the UniDOS Z80 runs so smoothly and
transparently that you won't even be able to tell
whether you're running DOS or CP/M. UniDOS emulates most common computers and terminals such
as Kaypro, Xerox 820, Morrow, Osborne, VT100, and
many others. Supports all standard CP/M system
calls, and now works with MS-DOS version 4. Includes UniForm-PC.
UniDOS Z80 Coprocessor Card ...... $ 169.95

UniDOS
Megamate

by Micro Solutions

Apple .. MS-DOS
MatchPoint-PC by Micro Solutions
Apple II or NorthStar diskettes in your IBM? The
MatchPoint-PC board for the PC/XT/AT works with
your standard controller card to let you read and write
to NorthStar hard sector and Apple II diskettes on
your PC. INCLUDES UnIForm-PC program, as well
as utilities to format disks, copy, delete, and view files
from Apple DOS, PRODOS, and Apple CP/M disks.
MatchPoint-PC Board. . . . . . . . . . . . . .. $ 179.95

•

Copy II PC Deluxe Option Board
by Central Point Software
Have a copy protected diskette with a particularly
stubborn protection scheme? Would you like to be
able to read your Macintosh disks in your 31/2" internal drive in your PC or AT? Repair a disk that's
damaged, even between sectors? How about speeding up your hard disk backups (if you are using PC
Tools Deluxe)? The Copy II Deluxe Option Board can
help you do all of this, and more. A must for the
sophisticated user.
Copy II Deluxe Option Board ........ $ 139.95

CentralPoinl

Sof!J£~~~

CP/M .. MS-DOS
UniDOS

You don't have to be a computer expert to install this
attractive 3 1/2" external drive on your PC or AT. Just
plug the MegaMate controller board into any empty
slot, attach the drive cable, run the installation software, and you're ready to run 720k or 1.44M diskettes.
Megamate . . . . . . . . . . . . . . . . . . . . . . .. $ 329.95

Copy II PC by Central Point Software
Don't let a damaged copy protected diskette stop you
cold. Copy II PC lets you back up your master disks so
you can keep going even when your key disk can't.
Copy II PC . . . . . . . . . . . . . . . . . . . . . .. $ 24.95

by Micro Solutions

If you have a fast machine or have a V20 chip installed, you may not need to use a card slot to run
your CP /M programs. Run 8080 code directly on the
V20, or use emulation mode for Z80 programs.
UniDOS by Micro Solutions. . . . . . . . .. $ 64.95
UniDOS w/UniForm & V20-8 chip ..... $ 135.00

MatchMaker

by Micro Solutions

Now you can copy your Macintosh diskettes right on
your PC/XT/ATwith the MatchMaker. Just plug your·
external 3 1/2" Macintosh drive into the MatchMaker
board and experience EASY access to your Mac diskettes. Includes programs to read, write, initialize, and
delete files on your single or double sided Mac disks.
MatchMaker Board. . . . . . . . . . . . . . . .. $ 139.95
MatchMaker w/External Mac Drive ... $ 325.00

PC Tools Deluxe VS.S
by Central Point Software
This is one of the great bargains in MS-DOS utility
software. But with so many features built in, we think
that many people are overlooking the REAL value
in PC Tools: DISASTER RECOVERYI Sure, the shell
is great for copying, viewing, editing, and deleting
files, and the desk top environment is nice for its
appointment calendar, note pad, phone dialer, calculators, and ASCII table. The fast hard drive backups
can't be beaten by any other program, and the file
unfragmenter speeds up hard drive accesses. But
where else can you get all of that along with UNDELETE, REBUILD, and UNFORMAT? Have you
ever entered "ERASE ..... and realised when all was
said and done that you were in the wrong directory?
How about those dreaded messages from CHKDSK,
like "File allocation error ...... ? The very first time you
recover your missing files will make you a believer.
Don't wait until it happens.
PC Tools Deluxe V5.5 . . . . . . . . . . . . .. $ 99.95

EMERRLO
MICROWRRE

P.o. Box 1726
(503) 641-8088 Beaverton, OR 97075
Call or write for our complete catalog of
software, parts, accessories and
complete repair services for the
Kaypro, Xerox 820, and IBM PC/ AT.

Reader Service Number 10

VISA and Mastercard accepted. Please include $6.00
shipping and handling, $8.50 for COD, UPS-Blue or
RED Label additional according to weight. Prices
subject to change without notice. Please include your
phone number with all correspondence.

MICRO CORNUCOPIA, #53, May, 1990

29

I use the SCI's interrupt to grab each
character as it comes in, then stash the
data in a circular queue. Eventually the
mainline code gets around to pulling the
character from the queue and processing
it.
Data from the keyboard arrives much
more slowly. (In my somewhat advanced years, I can no longer type much
above 4800 baud.) The MCU simply
glances from time to time at the keyboard port. If the line tied to the keyboard's strobe signal shows that data is
available, the MCU grabs it.
Data from the terminal to the host
computer also uses the SCI, but the program has no need to send anything in a
steady stream. It (currently) sends a
single character to the computer each
time a key is pressed, so this function
hardly requires interrupts.
On To The Software
I've divided the assembly language
code into several major functions. The
LCD routines initialize and update the
display. The output compare (OCMP)
server handles the 200 Ilsec tic interrupts. The SCI server takes care of incoming data from the computer. The
mainline code does everything else, such
as processing keyboard data and keeping the display looking pretty.
I based my LCD library on information from Ed Nisley's article, "The True
Secrets of Working with LCDs," from
the April/May 1989 issue of Circuit Cellar INK. Ed's explanation of the LCD's
inner workings really helped.
Because he did all his software in C,
Ed didn't concern himself with the requited delays between LCD commands;
the C code ran slow enough all by itself.
Adding Delays
Writing in assembly language, however, means adding delays. These waits
can be significant. The initialization
ritual, for example, calls for delays as
long as 5 msec; the shortest delay (between sending two visible characters to
the display) still takes 120 Ilsec. (Note:
All LCD commands have a required
minimum delay before a subsequent
command will be correctly processed.
However, there is no maximum delay.)
I solved this delay problem with the
OCMP server and a global variable
called WAIT$.
The MCU's 16-bit timer continually
counts down from $FFFF, through
$0000, and starts over again at $FFFF.

30

MICRO CORNUCOPIA, #53, May, 1990

The output compare register (OCR) can
hold an arbitrary 16-bit value. When the
value of the free-running timer matches
the value stored in the OCR, the MCU
generates a timer interrupt.
To generate a fixed-length time slice,
or tic, simply figure out how many
timing counts correspond to the delay
you need, add that value to the current
value of the timer, and store the sum in
the OCR. After the proper number of
counts, the timer will reach the value
you stored in the OCR and trigger an interrupt. Your interrupt service routine
then calculates the sum for the next tic,
updates the OCR. ...
In my case, I needed to count off the
correct number of 200 Ilsec tics. So my
interrupt routine does more than just set
up the next interrupt count. It also
checks the value in WAIT$; if that value
is not yet zero, the routine decrements it.
Therefore, any routine that must wait
(for example) 400 JlSec simply loads a
value of 2 (to wait for two tics) into
WAIT$, then hangs around until WAIT$
becomesO.
You will notice my software only
uses the A and X registers. That's all you
get! The tiny programming model on
this chip really makes you work to get
the most out of your code.
More About LCDs
I connected my LCD to the terminal
board using a 4-bit interface. Since the
LCD interface also requires a register
select line (RS) and an enable line (E), I
could run the whole display with only
six I/O lines. Refer to the schematic for
details. Pay particular attention to the
data lines. Note that the low four bits of
the MCU's I/O port connect to the high
four data bits on the LCD.
Unfortunately, the LCD comes out of
reset in an 8-bit interface mode. You
must follow a carefully defined ritual in
setting the LCD to read the 4-bit interface. The code in LCDINIT does the job.
First off, I reset all the lines to the
LCD and load a 15 msec power-up delay
into WAIT$. I then write a sequence of
three commands, each resetting the LCD
to an 8-bit interface. (Yes, I know we
want a 4-bit interface, but you gotta do
this just like the book says, or it isn't
going to work.) Note the different delays
used following each command.
Next, I set up the display for a 4-bit
interface. The remaining commands fix
the type of display format, cursor control, font, and cursor address. If you

want to try other display characteristics,
check the Hitachi manual or Ed's article
in Circuit Cellar INK for details.
The LCD accepts two types of data.
Commands, such as those discussed
above, must be written to the display
with the RS line low. Data, such as displayed text, must be sent while RS is
high. To make. these operations easier, I
included LCDCMD and LCDCHAR.
These routines use a common section
of code, found at LCDCHARl. Each sets
up the RS line as needed, loads an appropriate delay value into the AR, and
drops into the code at LCDCHARI.
From here, the byte gets divided into
two 4-bit nybbles. Calls to LCDOUT
then transfer the nybbles (MSB first) to
the display.
LCDSTRING simply sends each character of a null-terminated string to the
display. The only tricky bit involves the
load indexed, indirect addressing mode
of the 68HC70S; the chip doesn't have
such a mode.
To provide this essential addressing
mode, I resorted to self-modifying code
(actually, a RAM-based subroutine,
which is just as bad).
The initialization code for the terminal program builds up a two-instruction
subroutine called LDAIND by writing
two opcodes into low RAM. Address
LDAIND holds a $D6 (load accumulator, indexed, with a 16-bit offset), while
address LDAIND+3 holds a $81 (return
from subroutine). The two bytes at
and LDAIND+2 get
LDAIND+l
changed by another routine before calling LDAIND.
At run-time, a section of code stores
the 16-bit address of a null-terminated
string into the two bytes at LDAIND+l.
It clears the XR (X index register), then
calls LCDSTRING. Since the LDAIND
subroutine is all set up, LCDSTRING can
simply call the routine to get the character in the string pointed to by the XR. It
then increments the XR, gets the next
character, etc., until it gets the null marking the string's end.
And Now The Hardware
I built the prototype terminal on a
Radio Shack experimenter's card (276IS8A). You can find nearly all the parts
in a Radio Shack or Active Electronics
catalog; write these companies for a catalog if you don't have one already.
The only part you might have trouble
with is the 68HC70S MCU. You will
need to contact a Motorola distributor

C CODE FOR THE PC
source code, of course

NEW!

NEW!

Upgrade!
NEW!

Cheaper!

NEW!

MS-DOS File Compatibility Package (create, read & write MS-DOS file systems on non-MS-DOS computers)
CQL Query System (SQL retrievals on B-trees plus windows) . . . . . . . . . . . . . . . . . . . .
GraphiC 5.0 (high-resolution, DISSPLA-style scientific plots in color & hardcopy) . . . . . . . . . . .
PC a.mes (Aspen, Software, System V compatible, extensive documentation) . . . . . . . . . . . . . . . . . . . . . . . . .
CoData Manager (Object-oriented data management, persistent objects from runtime definitions, network and entity models) . . . . .
MEWEL (extensible window and even~ library by Magma Software; message-passing & object-oriented; SAA-compatible; dIalog editor)
ThrboTEX (Release 2.0; HP, PS, dot dnvers; CM fonts; LaTEX; MetaFont) . . . . . . . . . . . . . . . . . . . . . . . . . . .
db_File & db_Retrieve by Raima (B-tree and network database with SQL query and report writer; multi-user $475) . . . . . . . . . .
Greenleaf Communications Library (interrupt mode, modem control, XON-XOFF; specify compiler)
CDirect (multi-user hashed file manager; variable length fields, binary or ASCII data, alternate keys). . . . . . . . . .
SilverComm (complete asynchronous communications library) . . . . . . . . . . . . . . . . . . . . . . . . . .
Wendin-DOS Plus (self-bootable, multitasking, multiuser MS-DOS replacement; includes XTC editor) . . . . . . . . .
QuickGeometry Library (1~rge col1e~tion of, mathematics, graphics, display & DXF subroutines for CAD/CAM/CAE/CNC)
CBme (B+tree ISAM dnver, multIple vanable-Iength keys) . . . . . . . . . . . . . . . . . . . . . . . . . .
ThrboGeometry (library of routines for computational geometry, Version 3.0). . . . . . . . . . . .
AT BIOS Kit (roll your own BIOS with this complete set of baSIC input/output functions for ATs) . . .
WKS Library VersIon 2.01 (C program interface to Lotus 1-2-3, dBase, Supercalc 4, Quatro, & Clipper)
C Generator (generates C code to read & write file records defined with C structure syntax) . . . . . . .
OS/88 (industrial-strength U .. x-like operating system, many tools, cross-development from MS-DOS) . . .
Cephes Mathematical Library (over 100 high-~uality, double-precision scientific functions) . . . . . . . .
ME Version 2.1 (programmer's editor with C-hke macro language by Magma Software; Version 1.31 still $75)
Vmem/C (virtual memory manager; least-recently used pager; dynamic expansion of swap file) . . . . . . . . . . . . . . . . . .
Thrbo G Graphics Library (al1 popular adapters, hidden line removal) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rogue Wave Vector & Matrix Classes (inc. C++ overloadin~s for standard operators, matrix inversion & FFT; Zortech or GNU C++)
Power Search by Blaise Computing (regular-expression compIler; generates machine code on the fiy). . . . . . . . . . . . . . . .
Instal12.3 (automatic installation program; user-selected partial installation; CRC checking) . . . . . . . . . . . . . . . .
TE Editor beveloper's Kit (ful1 screen editor, undo command, multiple windows) . . . . . . . . . . . . . . . . . . . . .
Hold Eve~hing (spawn new programs; swap parent to EMS or disk; handles video, interrupts, & environment; returns error level)
B-.St,rings (dy~amlc string han~ling; c~t, copy" paste, se~rch, user input, etc.; non-fragmenting memory management) . . . . . .
MInIX Operatmg System (VersIon 1.3, U .. x-hke operatmg system, Includ~s manual) . . . . . . . . . . . . . . . . . . . .
PC/IP (CMU/MIT TCP/I}> for PCS; Ethernet, Appletalk & NETBIOS dnvers, RVD, gateways) . . . . . . . . .
B-me Library & ISAM Driver (file system utilities by Softfocus) . . . . . . . . . . . . . . . . . . . . . .
The Profiler (program execution profile tool) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
QC88 C compiler (ASM output, small model, no longs, Hoats or bit fields, 80+ function library) . . . . . . . . . . . . . .
Booter ToolkIt (HOrpy disk bootstrap routines, DOS file system, light-weight multitasking, windows, fast memory management)
Otter 1.0 (beautifu theorem-prover by Bill McCune; includes manual & two books by Wos; complete starter kit). . . . . . .
JATE Async Terminal Emulator (includes file transfer and menu subsystem) . . . . . . . . . . . . . . . . . . . . . .
PowerSTOR (upto a gigabyte of heap space on extended memory, expanded memory, and/or hard disk) . . . . . . . . . .
MultiDOS Plus ~DOS-based multitasking, intertask messaging, semaphores) . . . . . . . . .
HY -PHEN-EX a hyphenator for American English with over 4,800 rules) . . . . . . . . . .
Makx ~macros, a I languages, built-in rules) . . . . . . . . . . . . . . . . . . . . . . .
evalU C function to evaluate ASCII infix expression string; 17 built-in functions) . . . . . . .
XT BI S Kit (roll your own BIOS with this complete set of basic input/output functions for XTs) . .
Professional C Windows (lean & mean window and keyboard handler). . . . . . . . . . . . . .
Heap Expander (virtual memory manager using expanded memory, extended memory, and disk space) . . . . . . . .
Quincy (interactive C interpreter) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Symtab/Ptree (general-purpose symbol table/parse tree construction and management package; specify Symtab or Ptree)
Coder's Prolog (Version 3.0; inference engine for use with C programs) . . . . . . . . . . . . . . . . . . . . .
Async-Termio (Unix V compatible serial interface for MS-DOS; stty, iocti, SIGINT, etc.) . . . . . . . . . . . . .
Backup & Restore Utility by Blake McBride (multiple volumes, file compression & encryption) . .
Floppy TAR (TAR backup and restore on MS-DOS devices; direct access to non-standard deVIces)
SuperGrep (exception~lly fast, revolutionary tex~ searching algorit~m; also searches sub-directories)
OBJASM (convert .0bJ files to .asm files; output IS MASM compatIble) . . . . . . . . . . . .
Multi-User BBS (chat, mail, menus, sysop displays; does not include Hayes modem driver) . . . .
LaplaceB (LaPlace polynomials, real and complex) . . . . . . . . . . . . . . . . . . . . .
CLIPS (rule-based expert system generator, Version 4.3; advanced manuals available) . . . . . . . . . . . . . .
Pascal P-Code Compiler & Interpreter (full ISO standard Pascal) . . . . . . . . . . . . . . . . . . . . . . .
PCHRT (40 functions to manage multiple microsecond timers; generate precision delays; insert timers on any interrupt)
Kier DateLib (al1 kinds of date manipulation; translation, validation, formatting, & arithmetic) . . . . . . . . .
Fortran-to-C 'franslator by Polyglot (Fortran-IV -like Fortran to ugly C; plan to adapt to your own Havor of Fortran)
DES i?ncryption ~ Decryption (25,<)() bits/seco~d on 4.~7 MHz PC for on-the-Hy encryption at 2400 baud). . . . .
F1exLlst (doubly-hnked hsts of arbItrary data WIth multIple access methods) . . . . . . . . . . . . . . . . .
Virtual Memory Manager by Blake McBride (LRU pager, dynamic swap file, image save/restore) . . . . . . . . . . . . . '.
Heap I/O (treat all or part of a disk file as heap storage) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bison & BYACC (YACC workalike parser generators; documentation; no restrictions on use of BYACC output) . . . . . . . .
PC-XINU (Comer's XINU operating system for PC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RXC & EGREP (Regular Expression Compiler and Pattern Matching; RXC makes finite state machine from regular expression) .
REGX Plus (search and replace string mampulation routines based on regular expressions) . . . . . . . . . . . . . . . . . .
CCALC (handy extended-precision calculator; real and complex models; many built-in functions) . . . . . . . . . . . . . . .
GNU Awk & Diff for PC (both programs in one package) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-Pack of Editors (baker's half:dozen publi~ domain editors for use, study & hacking; includes microEmacs 3.10 & Stevie, a vi clone)
Crunch Pack (14 file compressIOn & expansIon programs) . . . . . . . . . . . . . . . . . . .
PC-MAIL (UtlCP mailer by Wietse Z. Venema; send, receive, and manage UUCP mail) . . . . . .
FLEX (fast lexical analyzer generator; new, improved LEX; official BSD Version 2.1 with docs) . . .
List-Pac (C functions for lists, stacks, and queues) . . . . . . . . . . . . . . . . . . . . . .
Using C++ Library (the code from the book by Bruce Eckel and then some; Zortech 2.0 compatible)
A68 (68000 cross-assembler) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XLTMacro Processor (general purpose text translator) . ... . . . . . . . . . . . . . . . . .

Data

$750
$325
$325
$290
$250
$250
$250
$245
$225
$210
$210
$180
$170
$165
$160
$160
$155
$150
$150
$150
$140
$140
$135
$125
$120
$120
$115
$105
$105
$105
$100
$100
$100
$90
$85
$80
$80
$80
$80
$75
$75
$75
$75
$70
$65
$60
$60
$60
$55
$50
$50
$50
$50
$50
$50
$50
$50
$45
$45
$40
$40
$40
$40
$40
$35
$35
$35
$30
$30
$30
$30
$30
$25
$25
$25
$25
$20
$20

Mo~
Mo~
Mo~

Pronunciator (150,000 words & phrases encoded with full IPA pronunciation & emphasis points; 900 distinguished by part-or-speech)
$160
Part-of-Speech (200,000 words and phrases described by prioritized part(s)-of-speech) . . . . . . . . . . . . . . . . . , . .
$120
Hyphenator (150,000 words fully hyphenated/syllabified) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
$105
Mol:1; Words (500,000 words & phrases, 9,000 stars, 15,000 names) . . . . . . . . . . . . . . . . . . . . . . . . . . .
$65
Smithsonian Astronomical Observatory Subset (right ascension, declination, & magnitude of 258,997 stars) . . . . . . . . . .
$60
U. S. Cities (~a~es & longitude/lat.itude of.32,OOO U.S. cities and 6,000 sta~e boundary points) ~ . . . . . . . . . . . . . . .
$35
The World DIgItIzed (100,000 !ongltud~/IatItude ofwo~ld country 1?oundanes) . . . . . . . . . . . . . . . . . . . . . .
$30
KST Fonts (13,200 characters In 139 mlXed fonts: SpeCIfy 'lEX or bItmap format) . . . . . . . . ; . . . . . . . . . . . .
$30
Interactive Computer Ephemerii (high-precision moon, sun, planet & star positions; USNO (no source) & Downey 4.8 (C source)) . . .
. $30

The Austin Code Works
11100 Leafwood Lane
Austin, Texas 78750-3409 USA
Free surface shippmg for cash in advance

info@acw.com
For delivery in Texas add 7%

Voice: (512) 258-0785
BBS: (512) 258-8831
FAX: (512) 258-1342
MasterCard/VISA

Reader Service Number 4

MICRO CORNUCOPIA, #53, May, 1990

31

directly for this chip, as I don't think it is
in the mail-order houses yet. Almac
Electronics (206-643-9992) in Bellevue,
Washington, will handle the parts mailorder in singles; price fO'1- the -S version
of this part (with the EPROM window)
is about $18.
Be sure to get a copy of Motorola's
HC705 CB Technical Data book, literature
number MC68HC705C8/D. Besides all
the technical info on using the 'HC705,
this book includes a full schematic for
building a programming board (piece 0'
cake). It also includes instructions on
using the programming board.
You can use just about any wiring
technique you want for this project. I
used point-to-point soldering with 30
AWG wire; wirewrapping would work
also.
By the time you read this, I will have
a
general-purpose
experimenter's
printed wiring board (PWB) for the
68HC705. The board will contain all the
basic circuitry needed to build a working MCU project, and could easily be the
only PWB you might need to develop an
application.
For example, this two-chip terminal
project would consist of a working ex-

STOMP OUT

EPROMMADRESS
+

'.
(

~

1,r

",'

~

' /

•

-.~,;:

•

r

,

",

'"
~

'Ij ,: ~ ~~ j:',;::r.-'ll,',\~l'

'\

~ .... ~

.
"

~

..

The PROM KING emulates EPROMS, saving
both time and money during your development
cycle. Programmable in seconds via your PC
printer port or any computer RS232 port, it can
emulate most 27xxx devices.
• 8K-8M bit devices
• 8-256 bit downloads
• High speed download: • Easily expandable:
-Universal RS232
-4 EPROMS per unit
-PC printer port
-Up to 8 units
• Menu driven software • Also programs like
a real EPROM
• Battery backup
$599 for 150nS units with 256K bits
Ask for pricing of other options
- - - - - Made in USA b y : - - - - -

TI¥IXEL lABS INC.
BOX 239, RONKONKOMA,NY'11779
516·737·5147

Reader Service Number 178

32

MICRO CORNUCOPIA, #53, May, 1990

perimenter's PWB connected to a keyboard and LCD.
After you get your terminal wired up,
you need to assemble the source code. I
use a PC/XT clone running Motorola's
ASS Freeware cross-assembler. Borland's Sidekick handles my editing, and
I burn the finished code into the MCU
using Motorola's M68HC05PGMR programmerboard and PROG7 support
software.
You can download both PROG7 and
ASS from the Motorola Freeware BBS
(512-891-3733; 8 data, no parity, 1 stop).
Motorola uses the BBS to distribute free
cross-assemblers (available for both the
PC and Mac), working source code for
MCU designs, technical updates, and
marketing announcements. Dial up and
take a look.
Even if you don't yet have a keyboard, you can still hook up the display
and apply power (use a DC source from
+7 to +25 Volts). Your LCD should show
the power-up announcement "Working ... "
If you don't get the proper display,
use an oscilloscope or logic probe to
check pin 35 of the MCU. My software
toggles this line each tic; you should see
a 50% duty-cycle square wave that
changes state every 200 Jlsecs. If you see
this signal, you likely have an error in
your LCD connection.
If you don't see this signal, check
your board's power supply and oscillator circuitry; you may not be getting +5
Volts to the chip, or your crystal may not
be oscillating.
After you get the display working,
wire up your keyboard using the schematic as a guide. The software expects
you to supply seven data bits (on port B,
bits 0-6) and a positive-going strobe
(port B, bit 7); you can use any keyboard
that will supply these signals. Note that
the circuitry does not supply +12 Volts;
keep that in mind when you hit the surplus stores.
With your keyboard installed, temporarily short pins 2 and 3 of the RS-232
connector. When you apply power and
press a key, the display should echo that
key. If so, you have a working terminal!
Time To Tinker
Since everything about this terminal
can be found in the software, you can really customize this project. Consult the
Hitachi manual for the low-level LCD
commands if you want to change the
shape/blink of the cursor. The Maxim

chip has a pair of unused RS-232 buffers;
you could hook these up to I/O pins on
the MCU and provide hardware handshaking on the serial line.
Since a keyboard character goes
through the MCU before it gets shipped
out the serial port, you can easily imbed
function codes or signature keys into the
software.
This design leaves an entire 8-bit port
vacant; how about hooking up relays,
lights, a piezo-beeper (for a control-G
bell code), or other control devices? You
could even hook up an external A/D
converter and have a stand-alone en. vironmental control station. The station
could then download data over the serial port to a host computer, while the
keyboard lets you run programs on the
host for evaluating data.
Anyone doing field work would
probably find a use for this terminal.
How about hooking up some rechargeable batteries (or a solar panel, if you use
a switch matrix keyboard) and taking
the terminal outdoors?
If you run road rallies, you could
easily connect the terminal (complete
with backlighting) to a small rally computer stashed in the backseat, and do
some real digital navigation.
That's About It
This project was great fun. Everything I develop with the '705 makes me
want to try another design or two. If you
customize this project (as I am sure you
will), I'd like to hear what you have
done.
Active Electronics
P.O. Box 9100
Westborough, MA 01581
(800) 888-9939 (outside New England)
(800) ACTIVE6 (New England)
TimeLine Inc.
1490 W. Artesia Blvd.
Gardena, CA 90247
(800) 872-8878 (outside California)
(800) 223-9977 (California)
United Products
1123 Valley Street
Seattle, W A 98109-4425
(206) 682-5025

•••

SAYW!'!O greatT~IS.

The lightning-fast
screen generator.

The breakthrough
DBMS toolkit for Pascal
If you'd like to combine the raw power
~
and speed of Turbo Pascal or Micro~*'
soft's QuickPascal with the simplicity.? ~ 'X~S
and elegance of dBASE, Topaz is L~~~Z
just what you're looking for.
That's because Topaz was
1
specially created to let you
Y,. ~ ~
/.
enjoy the best of both worlds./.~,:¥ )
The result? You create com-OVf'/-...-'~
plete, truly dazzling applicat- : / ' _ (/-'1 ~
ions in a very short time. And no wonder.
Topaz is a comprehensive toolkit of
~~
dB~SE-like commands and functions,
"'\ \ \\
deSigned to help you produce
outstanding, polished programs, fast.
Check out these powerful features:

Whether you're a novice
programmer longing for
simplicity, or a seasoned
pro searching for higher
productivity, you owe it
to yourself to check out
(/'.")
Saywhat. You see, with
\ \
:;/";;. Saywhat, you can build
~ ~
beautiful, elaborate, colorcoded screens in minutes!
(( A ~~
/
That's right. Trulyfantastic
\ t-\
~ screens for menus, data
~
entry, data display, and
help-panels that can be
displayed with as little as one
line of code in any language.
"

I

L

c.5:.i]""'-/1
I

i

I '""

)/)

--j

Here's what you get:

moving bar menus!
• Easy-to-use, powerful editor lets
you create screens in a jiffy.
• Pop up your screens and menus
with one line of code in dBASE,
all the dBASE compilers, your
favorite BASIC, Pascal, or any

other language!
• Screen Library Manager.
• Generates runtime code.
• No runtime license or royalty fees.
• Comes with a 100 page manual,
plus dozens of sample programs
and free utilities.

0(C3

4L"t1

Software Science, Inc.
100 Valley Drive, Brisbane, CA 94005
_.

,., > ") ) T) ) ') ~ ) \)

_.___
I »)
J
\)

OlUf
-

I

• Data entry routines like SAY, GET,
PICTURE, RANGE, color selection, unlimited data validation.
• Open up to 10 DBF files, with up to
15 indexes with USE, SELECT,
SKIP, APPEND, PACK, INDEX
ON, SET INDEX TO, and FIND.
• No need to buy dBASE. CREATE,
BROWSE and REPORT utilities
included.
• Easily implement Saywh at and
Lotus-style moving bar menus.
• BROWSE or EDIT any DBF file
with just one line of code! Programmable and windowed too.

)

~

or Topaz, for any reason, return them wlthlO
30 days for a prompt, friendly refund.
Ct
r.
~

oJ \

..'>.Jo.,..........,--

Dealers: SAYWHAT?! and TOPAZ are
available from Kenfil Distribution.
and in Europe from

• Pick from windowed data or filenames with one line of code.
• Comprehensive Time & Date
math in 7 international formats.

i

____

')

/1-\'> '- \, I MONEY BACK GUARANTEE.
I~y/ I'I'~. Ifyouaren'tcomp1etelydelightedwithSa~h31t

(~

• Over 220 routines all with easy-touse, dBASE-like syntax.

ORDER NOW.
YOU RISK NOTHING.
Thousands of satisfied customers
have already ordered from us. Why
not visit your dealer or call toll-free,
right now and putSaywhatand Topaz
to the test yourself? They're fully
guaranteed. You don't risk a penny.
Special limited-time offer! Save $26.
Buy Saywhat?! and Topaz together
for just $99 (plus $5 shipping and
handling, $10 Canada, $25 International, Calif. residents add 7%).
Visit your nearest dealer
or call toll-free:
800-468-9273
In California: 800-231-7849
International: 415-571-5019

• Design screens, windows, and

t:::';:;

,<:,,..!)\

•
•

~owledrfiudl~odeandreportgenerators

lnc u e .
C omes WI'th a compIete 320 page
manual, plus samp Ie programs to
get you started.

comFmiifOOd!
SOFTWARE

SCIENCE

INC.

Reader Service Number 129

MICRO CORNUCOPIA, #53, May, 1990

33

A Roundoff Roundup
When Rational Numbers Aren't Really Rational

Are rational numbers really rational?
Perhaps not. Does it matter? Most likely.
ary Entsminger, in his Tidbits
column "Faith in Numbers:
Chaos in Chaos" (Micro C #48,
July-August 1989), discusses the problem of roundoff error in recursive iterations of non-linear equations. Mr. Entsminger points out a problem facing
computer mathematics which, at least
for some applications, has a simple solution. This article makes several references to Mr. Entsminger's column, so
you may wish to reread it.
Mr. Entsminger defines a rational
number as a real number which is either
reducible to an integer, expressible as a
terminating decimal fraction, or expressible as a decimal fraction with a repeating
sequence of digits. This is a common and
workable definition, but not an exact one.
Take an ordered pair (x,y) of integers
and define an equivalence relation = such
that for any two ordered pairs (x,y) and
(a,b) with x= N then begin
Pr := true;
Done := true:
end
else if « N mod Divisor)
0) then
Done := true
else begin
Count := (Count + 1) mod 4;
If count = 1 then
divisor := divisor + 4
else divisor := divisor + 2;
end;
Prime := Prj
Endi {Prime}
Function GCD( A,B : longint) : longint;
Var
x,M,N : longinti
Done : boolean;
Begin
M := abs (A);
N := abs(B);
x := M;
If N <= x then x := Ni
Done := false;
While not done do
If «N mod X)=O) and «M mod X)=O) then
done:=true
else x := x - li
GCD := x;

Endi
Function LCM( A,B : longint ): longinti
Var
X,Y,N,M : longint;
Done : boolean;
Begin
M := abs(A):
N := abs(B);
Y := M;
IfN < Y then Y := Ni
X:=Y;
Done := false:
While not done do
I f «X modM)
0) and.( eX mod N) = 0) then
done := true
else x := x +Y;

.=

LCM := X;

End;

Procedure Reduce ( Var X
Var
A
longinti
Begin

IfX[l]

0 then begin

X[l) := Oi
X[2) := 1;
, end
else begin
A := GCD(X{l),X[2)i
X[l) := X[l) div Ai
X[2] := X[2] div A;
end;

End;
Procedure Invert ( Var X Rational) i
Var
A : .longint;
Begin
If X[l) = 0 then
Writeln('DIVIDE BY ZERO ERROR!')
else if X[l) < 0 then begin
A := X[2)i
X[2] := Abs(X[l]);
X[l] := 0 - A;
end
else begin
A := X[l);
X[l] := X[2);
X[2) := Ai
end;
End;
Procedure Radd( Xl,X2: rational; Var Y: rational);
Var
Z,A : longint;
Begin
Z := LCM(Xl[2),X2[2)i
Y[2) := Zi
A := Z div Xl[2);
Y[l) := Xl [1) * Ai
A := Z divX2[2);
Y[l] := Y(l] + ( X2 [1) * A) ;
Reduce(Y):
End;
Procedure Rsub( Xl,X2: rational; Var Y: rational);
Var
Z,A
longint;
Begin
Z := LCM(Xl[2],X2[2);
Y(2) := Z;
A := Z div Xl[2];
,Y[l) := Xl(l] * Ai
A := Z div X2[2];
Y[l) := Y[l) - (X2(l) * A);
Reduce(Y)i
End;

rational) ;
Procedure Rmult(Xl,X2: Rational; Var Y: Rational);
Var
A,B : Rational;

Continued on page 38

36

MICRO CORNUCOPIA, #53, May, 1990

;868Z:9991 »xref=<96817>«
:868Z:9994 »xref=<8&999>«
:COaversiOD ta~le

call

sl

.:lV

ax

.:lV
EV

is -.aiale-

xor

si fttil

al

:e68Z:8897
;e68Z:8889

Su~roath.e

;868Z:989b
;Loai rqister
;e68Z:898i

Orilil
.:lV
.:lV

lax

:»»> Conversion Section
les
Us
EVZX

repz
sti

,
•
-

.':'
w

xrer

,.

~

..

,.,

.

4 ;
•

:

l

WI

8

;868Z:8818

address

;e68Z:9912 >}xref=<86888>«
;coaversiol ta~le
b x . - - - - - - h :8682:9916
;9682:991h get 'Yte COUlt
cx Help
s t I!:::=======!II ;9682:981£
;Store AL at £5:(11]
;968Z:ee21
;Turn,On Ilterrupts
;e6e2:ee22
;e68l:ee25 DOS:1c-te~iaate
di Yard
Address

Continued from page 36
{Subtract D*l from 2}

Begin
A[l] := X1[1]:
A[2] := X2[2];
B[l] :=X2[1]:
B[2] := X1[2];
Reduce (A) ;
Reduce (B) ;
Y[l] :=A[l] * B[l];
Y[2] := A(2) * B[2);
Reduce (Y):
End;

x := d;

Procedure Rdiv(X1,X2: Rational; Var Y: Rational):
Var
X : Rational:
Begin
X := X2;
Invert (X);
Rmult(X1,X,Y);
End;
End.

•••
Figure 2-GAUSS.PAS
Program GAUSS;
Uses RATIONALS;
Var
A,B,C,D,E,F,X,Y,Z : Rational;
Ar,Br,Cr,Dr,Er,Fr,Xr,Yr,Zr : Real;
Begin
A[l] := 131;
A[2] := 1;
Ar := 131;
B[l] := 23:
B[2] := 1;
Br := 23;
C[l] := 31;
C[2] := 1;
Cr := 31;
D[l] := 7;
D[2] := 1;
Dr := 7:
E[l] := 27;
E[2] := 1:
Er :=.21;
F[l] := 67;
F[2] := 1;
Fr := 67:
{Using Rationals}{First divide 1 by a}
X :=·A;
Rdiv(a;x,y) :
a := y:
Rdiv(b,x,y);
b

:=y;

Rdiv(c,x,y);
c :=y;

38

MICRO CORNUCOPIA, #53, May, 1990

Rmult(x,a,y);
. Rsub(d,y,z):
d := z;
Rmult(x,b,y):
Rsub(e,y,z);
e := z;
Rmult(x,c,y);
Rsub(f,y, z):
f := z;
{Divide 2 bye}
x := e;
Rdiv(e,x,y) ;
e := y;
Rdiv(f,x,y) ;
f

:= y;

{Subtract b*2 from 1}
x := b;
Rmult(e,x,y):
Rsub(b,y,z);
b := z;
Rmult(f,x,y);
Rsub(c,y,z);
c := z;
Writeln('Using rationals we get ... ');
Writeln(a[11,'/',a[2],'X
',c[11,'/',c[2]):
Writeln(e[1],'/',e[2],,'Y = ',f[1],'/',f[2]);
writeln;
{Using reals}{Divide 1 by a}
xr := art
ar := ar / xr:
br := br / xr;
cr := cr / xr:
{Subtract D*1 from 2}
xr := ar * dr;
yr := br * dr;
zr := cr * dr;
dr := dr - xr:
er := er - yr;
fr := fr - zr;
{Divide 2 bye}
xr .- er:
dr .- dr / xr;
er .- er / xr:
fr
fr / xr;
{Subtract B*2 from 1}
xr := br * dr;
yr := br * er;
zr := br * fr;
ar := ar - xr:
br := br - yr;
cr := cr - zr;
Writeln(' Using REALS we get');
Writeln;Writeln(ar:S:9,' *x = ',cr:S:9);
Writeln(er:S:9,' *y = ',fr:5:9):
End.

.-

•••

cant properties of the rational numbers is
that given any two rationals a and b,
there must be a rational z such that a< z<
b, I can never represent a complete range
of the rationals. In modeling natural systems, I do not need to.
The set of all numbers which exist in
nature is discrete. In making such a bold
claim, I feel compelled to defend it.
Using the most accurate measuring
instruments available, and the best techniques of extrapolation, you can measure
a quantity to only finite tolerance. You
will then be able to get two measures for
which no intermediate measure can be
found.
Consider Zeno's paradox. Zeno
asserts that if a turtle and a rabbit were
to run a race, and the turtle were given a
head start, the rabbit could never pass
the turtle. His reasoning is that when the
rabbit achieved the turtle's starting position, the turtle would have moved some
distance ahead. The distance between the
two, though less, would still be positive.
Continuing in this manner, Zeno says
that the turtle must always be some positive distance ahead.
This is true only if distance is infinitely divisible. Try this experiment
yourself with two objects moving at constant velocity, one faster than the other.
Give the slow one a head start and you
will see that the fast one does pass the
slow one. The distance between them reduces to a point where no smaller distance exists.
Mr. Entsminger's example of the
equation Nextx + RX(1 - X) yields values
between a and 1, representing some portion of the maximum population of
wolves. If the maximum number of
wolves is some number z and the population after any iteration is given by
z*Nextx, we see that values of Nextx of
minute enough significance are not useful. Suppose Nextx = (K(z + 1) + l)/(z +
1) for some rational K. We then have a
fraction of a wolf, which is not likely to
reproduce.
For many applications, all discrete
representations of the rational numbers
are equally flawed. Trigonometric equations, for example, rely on the irrational
number pi. The results obtained using
ordered pairs will be at least as inaccurate as those obtained using floating
point notation. But for many applications, representing rational numbers as
ordered pairs of integers will greatly increase accuracy.

•••

CITIZEN PRINTERS
Citizen
Citizen
Citizen
Citizen
Citizen

120D 120/25 CPS 80 COL
180D 180/35 CPS 80 COL
HSP500 300/66 CPS 80
HSP550 300/66 CPS 120
GSX140 200 CPS 24 PIN

$165.00
$180.00
$350.00
$475.00
$345.00

GOLDSTAR MONITORS
MBM-1210A 12" TTL AMBER
MBM-1401A 14" Flar Screen TTL
MCH-1420 14" EGA 640x350
MCH-1430 14" VGA 640x480

$ 90.00
$135.00
$345.00
$375.00

VIDEO CARDS
VIP Card VGA,CGA,EGA,MGA,
ANALOG AND TTL 800x560
ATI VGA Wonder 256 1024x768
ATI VGA Wonder 256 16 bit
Paradise Basic EGA 640x350
Paradise Basic VGA 640x480
Paradise VGA Plus 800x600
Paridise VGA Plus 16 Bit

$175.00
$225.00
$375.00
$ 99.00
$175.00
$199.00
$275.00

ATI

HARD DRIVE CONTROLLERS DOR XT & AT
WD WX1 Auto Config
PC/XT
WD WX2 Auto ConfigPC/XT
LONGSHINE LCS-6210D PC/XT
WD WAH AT 16 Bit 2 Hard Drive
WD 1003SM1 AT 2:1 Int.
WD 1003SM2 Hard/Floppy 2:1
WD 1006SM1 AT 1:1 8K Cashe
WD 1006MS2 Hard/Floppy 1:1
WD 1003SR1 RLL 2:1 Int
WD 1003SR2 RRL Hard/Floppy
WD 1006SR1 RLL 1:1 8K Cashe
WD 1003SR2 RLL Hard/Floppy

$ 65.00
$ 55.00
$ 45.00
$ 75.00
$ 99.00
$125.00
$125.00
$135.00
$125.00
$135.00
$135.00
$145.00

SEAGATE DRIVES AND CONTROLLER IN STOCK
Please call for current price.

**********

2400 BAUD MODEM **************
by Computer Peripherals
2400 Baud Internal and Software $85.00
2400 Baud External and Software $140.00
CASCADE ELECTRONICS, INC.
ROUTE 1· BOX 8
RANDOLPH, MN 55065
507-645-7997
Please ADD shipping on all Orders
COD Add $3.00
Credit Card ADD 5%
MN Add 6% Sales Tax Subject to change
Reader Service Number 15

MICRO CORNUCOPIA, #53, May, 1990

39

Initializing Variables In Turbo Pascal
Handling Initialization During The Link Rather Than At Run Time

This is hacking at its best. Dave obviously understands the limitations of Turbo
and he's sent along some fixes. Fun stuff.
he most recent versions of Turbo
Pascal (5.0 and 5.5), have a great
deal to offer in terms of flexibility,
code readability, and development
speed. However, because of the way the
compiler and its internal linker work,
and because of Borland's support for
only one memory model, it has some
real limitations.

T

Procedure Tables To Go
One of Turbo Pascal's annoying limitations is the compiler's inability to initialize arrays of procedures (procedure
tables) at compile time.
Procedure tables are easy in C. The external linker automatically initializes the
address values in an initialized array of
procedures (at link time after they have
been resolved). See Figure 1 for a simple
example. (I'm not a C programmer by
trade, so the example may not be elegant.)
If you were to translate this directly
into Pascal (see Figure 2) and then try to
compile it, Turbo complains about the
line that initializes the array of procedures.
So what do you do if you want to create a procedure table in Turbo Pascal?
Normally you have to waste some runtime code to assign each of the procedures to the array members (see Figure
3).

For an array of four procedures, this
doesn't add much to the run-time. But
how about 500 procedures? Then it adds
up. The .EXE file for the small interpreter
you just knocked together using procedure tables would be fatter than it should
be. Plus, I think it's kludgy to do all those

40

MICRO CORNUCOPIA, #53, May, 1990

.1

By Dave Gwillim
159 Woodbury Road
Hicksville, NY 11801-3030
(516) 942-8697

One

begin
writeln('Procedure 3');
end;
{$F-}
const
Proc : array[O .. 3] of procedure = (ProcOiProcl,Proc2,Proc3)i
var
n : word;
begin
for n := 0 to 3 do
Proc[n);
end.

•••
Figure 3-PROCTABL1.PAS
var
Proc : array[O .. 31 of procedure;
n: word;

of Turbo
Pascal's annoying
limitations is the
compiler's inability
to initialize arrays
of procedures
(procedure tables)
at compile time.
assignments, especially when the linker
knows what the addresses are before it
creates the .EXE file.
Is there a way to make the compiler
handle this at compile time? Using only
Turbo Pascal, no. The compiler handles
the initialization of typed constants
before linking. At that time it isn't sure
where the procedures will be located.
However, by using a dash of assembly language, you can force the compiler'to handle most of the initialization
during the link, leaving only the initialization of a single pointer variable for the
run-time code. Figures 4 and 5 show one
way you can do this.
The fake procedure Procs is never
called (and never should be, unless you
feel like reaching for the red button). It's
simply used to export a pointer from an
external assembly language program.
Since you cannot declare any data PUBLIC in an external procedure and still
have Turbo Pascal see it, you have to
cheat.
Fortunately, cheating will make your
.EXE file smaller, especially when you
MICRO CORNUCOPIA, #53, May, 1990

41

have lots of procedures in your table. The
trade off is that you have to maintain a
PROCS.ASM file in addition to the Pascal
source code.
Typed Constants Without Limit,
Anyone?
We all know how valuable that 64K of
data segment for variables in Turbo Pascal is, right? Every typed constant (initialized variable) gets its bite (or two). Sometimes 64K seems downright tiny!
Of course, you can allocate all your
variables on the heap. But then you have
to initialize them with assignments to
constants embedded in your code or load
in a separate data file. Both approaches
add considerably to the size of your .EXE

me.

You don't have this problem in any
implementation of C that supports multiple data segments. So wouldn't it be nice
if Turbo Pascal could manage it? If only
you had some way to assign initialized
variables to their own segment. Perhaps
you wouldn't have to switch to C!
Using a little assembly language, you
can do this in Turbo Pascal. Using only 4
bytes of that valuable Turbo Pascal variable space you get access to as much as
64K of initialized data. This trick turns
code space into initialized data space. See
Figures 6 and 7 for a way to do this.
Note that to get 64K of initialized data
space using this technique, you would
have to make the external procedure containing the data the sole member of a
separately compiled unit. And do it so
that virtually none of the code space
would be taken up by executable code.
When unitizing, you should also include the pointer variable in the unit and
use the run-time initialization capability
(placing an assignment statement between a BEGIN and END in the implementation part) to set up the pointer
variable. You only use the unit to have all
the initialized data available. Using the
unit approach is also a good way to hide
the fake procedure _DataSegl.
See Figures 8 and 9 for a sample using
the unitized approach.
Putting the initialized data into the
.ASM me also means you can use the
power of TASM or MASM operators and
macros to generate complex patterns of
initialized data that Turbo Pascal can't
match. Just try initializing a typed constant with the equivalent of 1000
dup('TEXT ') in Turbo!

42

MICRO CORNUCOPIA, #53, May, 1990

DefaultOUtputFile db 12,'DATA_OUT,DTA',
InitFileOffset
dd 1623447
BigAnay
db 1000 dup (' TEXT ')

: string (79)
; longint
; array(1 •• 5000] of char;

Confusing Code?
'Include 
text count(){lnt c,nllnes,nwords,nchars,lnword;
Inword.tlO; nllnes-nwords-nchars-O;wh Ile( (c
·getchar(» I·EOF) {.. nchars: If (c •• ' \n' )
.. nllnes: If «c·.' '):: (c •• ' \n' » Inword·tlO;e Ise
1ft Inword··NO){ I nword.YES: .. nwords:} }prlntf (
"%d %d %d\n", nllnes,nwords,nchars):}

_OataSeql endp
code ends
end

•••

CIt Your Way!

Figure 7-INITDATA.PAS

.Include 
~ext_count

{$F+}
{$L OATASEG1.0BJ}
procedure _DataSeql; external:
{$F-}

type
DataSeqlType
record
OefaultlnputFile : strinq[79];
DefaultOUtputFile : strinq(79];
InitFileOffset : lonqint:
BiqArray : array(1 .• 5000] of char;

=

()

Int c, nlines, nwords, nchars, Inword:

'DATA IN.DTA' }
, DATAOUT. DTA' }
1623447 }
1000 dup('TEXT ')

end;

Inword • NO:
nllnes • nwords • nchars • 0:
while «c· getchar() I· EOF) {
.. nchars:
If (c •• '\n')
.. nllnes:
if « c •• ' ') :: (c •• '\n'»
Inword • NO:
else if (Inword •• NO) {
Inword • YES:
Hnwords:
}

prlntf ("%d \d \d\n", nllnes, nwords, nchars):

var
DataSeg1
n : word:

ADataSeqlType:

begin
DataSeql := @ DataSeg1; {point to initialized data in DATASEG1.0BJ}
with DataSeqlAdo
beqin
writeln(DefaultlnputFile);
writeln(OefaultOUtputFile)i
writeln(InitFileOffset):
for n := 1 to 30 do '
write(BiqArray(n])i
writeln;

with C·ClearlytM, format C source
NOW
code exactly the way you want it.
C-Clearly's context sensitive analysis will
format any C program in your own personal
or corporate style.
to use, C-Clearly's style templates
EASY
are a snap to modify, since they
resemble C source code you edit into your
preferred format. Templates are included for
several common styles as well as standard
K & R.
can a!so be created with
LISTINGS
function names and
comments highlighted for improved readability.
Listing options include line numbers, headers
and/or footers and flow lines.
for making obtuse code clear.
Allows all of your source code
to be presented in a consistent format of your
chOOSing. Also great for code walkthroughs and
final documentation listings.

IDEAL

with all IBM PC, XT, AT, PS/2
WO
RKS
and compatibles, with 512K
RAM. Automatically processes all include files
and pre-processor statements. ANSI-C compatible. Not copy protected.

C-C/ear/y $129.95
Shipping & Handling USA $5; Canada/Mexico $10; Other Countries
$15; CA Residents add sales tax, Visa/MasterCard/COD accepted,

For orders or information call:

1-800-662-8266
V COMMUNICATIONS, INC.
4320 Stevens Creek Blvd., Ste 275. Dept. MC6
San Jose. CA 95129 (408) 296-4224

Reader Service Number 62

MICRO CORNUCOPIA, #53, May, 1990 43

Initializing Large Amounts Of Data
For large amounts of initialized data,
a program that reads the data structure
definition and then creates the appropriate db, dw, dd directives, etc., would
make creating the .ASM file easier. You
might write an include file that has the
initialized data appear after each of the
members in the record structure definition. Then feed this include file to your
program as a data file and have it create
the .ASM file.
See Figure 10 for an example.
Your program could parse each line to
determine the equivalent assembly language data type and number of elements
and then initialize it with the data in the
comments. As the famous cop-out goes,
"Such a program is left as an exercise for
the student."
Editor's note: Yes, yes. I enjoy writing in
Turbo Pascal but I, too, am running up
against limitations in the language, especially
with the 64K limit on the data segment.

•••

MultiPurpose Lab Interface for Your IBW
Tum your IBM-compatible computer into a powerful laboratory
instrument with our MultiPurpose Lab Interface (MPLI) hardware
and software. MPLI allows you to use a wide variety of sensors to
make measurements and to analyze and graph the results. Data
can be collected at a rate of thousands of samples per second or
slowly over periods as long as several months. Sensors available
include assembled. ready-te-use units and parts kits. The MPLI
hardware-software combination consists of:

~:

=

• A 12-blt AID Interface Board: A 12-bit. 8-input analog-to-digital
converter with built-in sample and hold. Conversion time of the A-to-D is 9 J!Sec. There are three bipolar
and three unipolar software-selectable voltage ranges. The board also includes one 12-bit analog output
and access to 16 digital 110 lines. Includes manual and sample programs disk. (Order Code AI B-PC. $240)

• MultiPurpose Lab Interface Box: Includes three 8-pin DIN sockets which allow quick connection to 3 of the analog inputs. voltage out and
power leads. A prototyping area for building your own circuits is included on the circuit board inside the box. A variety of sensors and probes
are available which plug into the MPLI box: pH. thermocouple. temperature (AD590). force. microphone. etc. (Order Code BOX. $45)

it . .'."_'..(

• MultiPurpose ~b Interf~ce Software:

~e Mu.ltiPurpose Lab Interface Program allows three input ~;~
....._....
t:
]
channels to be calibrated to display any type of Input signal; for example. channel A can read temperature.
{>:. .....
channel Bcan read pH. and channel Ccan read pressure. Data from each ofthe channels can becollected... .. ·,·· .. ·tt·t,~· .. ·· .. ·:·:r·,. ..... ·;:I ..~.~.' .... '....
graphed. and saved on disk. The output voltage can be controlled by the program. The Oscilloscope mode
V' '.......
!i
lets the computer act as a triple-trace. storage oscilloscope with a sampling rate of at least 40.000 samplesl
sec (on an 4.77 MHz. IBM PC). much faster on other computers. The program even does X vs. Yplotting.
ICY Plottl_:-';;_~~=--("AA-::"'=--=-B~)· so you can display Lissajous figures on the monitor. (Order Code MPP-IBM. $49.95)
~:~:~~: ....·i~_~

f'"- . ./

t

~Q~:u.ulu.lJWuili.Luhw.L.t of time goes into
incrementing the index and testing
when to exit the loop. To save time you
can "open the loop" by enlarging the

/* Initialize Sum */

}

•••

/* Use normal approach */
/* for the last few
*/
/* Multiply and Accumulates */

code within the loop to perform several
multiply / add calculations (see Figure 4).
This approach will improve performance (to varying degrees) no matter
which processor you use. In fact, the
fastest code (assuming we're using a
non-caching processor) would require
no looping. Of course this is unrealistic
for all but the smallest neural network
because of the memory required for the
instructions.
How much should you open the
loop? You can determine this by taking
advantage of how the transputer works
with constants. The fastest executing instructions are a byte long and use the
first nybble to indicate the instruction
and the second nybble for a constant.
Thus, constants between 0 and 15 are
easily handled in one-byte instructions.
If it needs larger numbers, the transputer builds them a nybble at a time
(also using a byte-long instruction). The
instruction associated with the last
nybble necessary to form a constant will
also operate on the constant (e.g., load,
store, etc.). For example, if you need a
number between 256 and 4095, you need
three nybbles (with an additional nybble
instruction for each, i.e., a total of 3
bytes). Of course each additional nybble
requires an additional clock cycle.
Therefore a good amount to open the
loop up by is 16 (for constants between
0-15). This requires only one nybble (and
therefore one instruction) to access each
operand. To make the code usable for a
neural network of any size, add regular
loop code after the opened loop code to
handle the situation when the number of
nodes is not divisible by 16.
RAM
The second key feature of the transputer is its internal RAM. Most compilers use this RAM for stacks and
workspace pointers, but we can tell the
compiler to set aside space within internal RAM for a small routine or two. Instructions and data found in this area
(4K) can be retrieved in a single clock
cycle.
Since the less expensive TRAMs use
external memory requiring four clock
cycles for access, we can speed up the
matrix vector multiply by using the internal RAM. It's too bad we can't get the
arrays in there also.
Now what are we up to? Using the
hand-optimized assembly language to
maximize the floating point operation
and opening the loop by 16 to minimize

OK, piece a cake!
Berry Computers presents The Tele Operating System
A MULTITASKING MS-DOS COMPATIBLE
Computer software exists in layers.
Tele contains the layers between
your application and the hardware.
Tele executes binary programs
intended for MS-DOS in a multitasking, windowing environment.
You can use Tele to run several programs at once thereby.eliminating
boring and unproductive delays.
For instance, in a software development environment, you can set a
compiler running and Simultaneously
edit an()ther source file.
Tele uses a preemptive task scheduler.
Its file system is fully compatible
with MS-DOS. It runs on any processor compatible with the Intel
8086 family.
Most programs intended for MSDOS will multi-task under Tele.
Microsoft could find no way to make
MS-DOS multi-tasking and still support all its existing applications.
Tele simply does the best possible.
Tele services the documented interface to MS-DOS, fits in less than
lOOK of memory, and proVides the
important features of OS/2., including installable file systems.
Tele improves display performance
by a factor of 2, whether you use
multiple windows or not! On processors slower than 20 MHz the
improvement is even greater.

Source code in C and assembly is
included for the interface to MSDOS. If you have to have MS-DOS
idiosyncracies, you can easily put
them in yourself.
Treat yourself to an operating
system where the marketing and
financial folks had no say at all in
the design. The result is an efficient,
structured program that either provides or specifically anticipates all
features of modern mainframe and
desktop operating systems.
Tele Operating System
Tele Tool Kit
Multitasking (MT)*
Windows (Wl)*
File System (FS)
Tele Operating System
and Tool Kit
Demonstration Disk

$100
$ 50

$ 40
$ 40

$200
$ 5

*MT formally ,ailed SK. WI formally ,ailed CD

Telephone support is freely available.
Tele is available from:
Crosby Associates
P.o. Box 248
Sutter Creek, California
95642

CALL NOW TO ORDER:
(209) 267-0362
FAX (209) 267-9246*
* Note new Fax

#

Visa, Mastercard. American Express &. Discover Card accepted.

MS· DOS and OS/2 are trademarks of Mkrosoft Corporation

Reader Service Number 147

MICRO CORNUCOPIA, #53, May, 1990

49

the loop instruction overhead, I got
around 675,000 MAC/sec. When I put
the code in internal RAM, the speed improved by 50,000 MAC/sec to over
725,000 MAC/sec. Now we're talking!

Note: You can download the code for the
matrix vector multiply and the code for performing the transposed vector matrix multiply (needed during the error correction
phase of the neural network simulation) from
the Micro C BBS. The transposed code isn't
quite as efficient as the first but still does
over 700,000 MAC/sec.
Whew! I think we've eked every bit
of speed out of the transputer. You can
use this code with both online and epoch
training. Take your PC code and modify

it to insure that the data for the weight
matrix is arranged correctly. Otherwise,
code written for the PC using Turbo C
(from Borland International) or Microsoft C compiles under the Logical Systems' C compiler with little or no
modification.
Using Transputers In Parallel
So far, I've used a single transputer to
simulate neural networks. If you want to
process more data and/or process data
as quickly as possible, then a parallel approach to transputing is the ticket.
The underlying architecture of the
transputer, with its multitasking and
synchronized communications capabilities, almost eliminates the programming
hassles associated with controlling
several tasks concurrently.
Processor Farms
To implement a problem on several
transputers, you need to distribute the
workload as evenly as possible.
Some algorithms fit more naturally
into a parallel implementation than
others. So, you look for algorithms
which (when applied to parallel proces-

50

MICRO CORNUCOPIA, #53, May, 1990

sors) increase linearly in performance
with an increase in processors.
One such approach is a "processor
farm.,,4 In a processor farm one processor serves as the "farmer" and the remaining processors serve as "workers."
The worker processors execute identical
code. The farmer processor sends packets of data to each worker. When a
worker finishes with its work (its
packet), the farmer retrieves the results
and sends a new packet. Farming continues until the work is done.
This approach is probably the most
appropriate for using multiple transputers to simulate neural networks. Each
worker runs its own neural network.

weights and the weight corrections
through the pipeline. Each pipe processor has a complete copy of the neural
network's nodes as well as the input and
output values for each exemplar vector
that it's responsible for.
The weights are stored and modified
in the administrator processor· at one
end of the pipeline (typically another
transputer). The administrator processor
is connected to the host PC and to the
first and last processors in the pipeline.
It gets the topology and exemplar and
test vectors from the PC (typically in
files) and then uses this information to
configure the pipe processors.
When the pipe processors have their

Pipelining
While a processor farm makes sense
once you know the neural network's
weights, it's not good for training. An algorithm called pipelining is a better approach for training.
Pomerleau et. al. 5 describes the algorithm for use with the Carnegie Mellon
University Warp machine (a very expensive systolic array processor). Chong
and Fallside6 describe it for the transputer.
This algorithm uses a group of processors arranged in a pipeline (see Figure 5). In a pipeline, each processor
receives intermediate results and/or
data from its upstream neighbor,
processes the data, and then sends its results/ data to its downstream neighbor.
For best results, try to communicate
(send/receive data) and compute
(process data) in parallel. Also, each processor's work load should be relatively
equal. So no processor waits for another.
For neural network simulations on an
array of transputers, you typically send
a subset of the exemplar vectors to each
pipe processor. Then you pipe the

exemplar vectors and a copy of the
neural network nodes, the administrator
processor sends a copy of all the weights
down the pipeline. As a pipe processor
receives the weights, it immediately
sends them to the next processor
downstream. Then (in parallel) it uses
the weights to make a pass through the
neural network for each of its exemplar
vectors.
The pipe processor compares the calculated output values with the exemplar
output values, then calculates an error
value which it sends back to the administrator processor. The administrator
node receives the error values from all
the pipe processors and determines if
the total error for all the exemplar vectors meets the desired criteria.
If the error is low enough, the administrator processor transfers the weights
back to the PC and runs through any test
vectors that have been supplied.
If the error is too high, the administrator sends a message to each pipe processor instructing it to calculate a change
of weights based on its exemplar vectors. The administrator processor then
sends an empty array down the pipeline.

When a pipe processor receives the
array, it adds the change in weights that
it's calculated to the array, then sends it
downstream to the next pipe processor.
When the administrator processor
gets the array back, it will have the sum
of all the changes for each weight based
on all the exemplar vectors. The array is
then multiplied by the lea~ning rate constant and added to the previous changed
weight vector (which has been multiplied by the desired momentum constant) to produce a new weight vector.
The administrator creates a new set of
weights by adding the present weight
vector to the new weight vector. Then
the whole process begins again with the
administrator node sending the new
weights down the pipeline.
Programming Transputers
To implement the pipelined neural
network simulation on the transputers
requires only three programs, no matter
how many processors are involved. The
first program (ADMIN) is the administrator processor program.
This program interfaces to the host

PC and to the pipeline. It's responsible
for:
(1) Retrieving the topology of the
neural network;
(2) Transmitting the information
down the pipeline so that each pipe processor can configure itself;
(3) Retrieving all the exemplar vectors from the host;
(4) Transmitting evenly divided subsets of the exemplar vectors to each pipe
processor;
(5) Transmitting the weights into the
pipeline;
(6) Getting error measurements from
each processor in the pipe;
(7) Determining whether the total
system error is below a user specified
value;
(8) If necessary, instructing the pipe
processors to calculate the weight
changes;
(9) Sending an empty weight change
array downstream;
(10) Collecting the filled weight
change array from the pipe processors;
(11) Using the host (Le., user) supplied momentum and learning rate con-

stants along with the weight change
array to calculate a new weight vector;
(12) Looping back to step 5;
(13) When training is complete,
saving the weights;
(14) And, if necessary, running test
vectors on the trained neural network
and collecting statistics.
The program (PIPE) is run on all the
pipe processors. It's responsible for:
(1) Receiving and retransmitting the
topology of the neural network;
(2) Setting aside enough space for the
weights and its own exemplar vectors;
(3) Reading and storing its own exemplar vectors;
(4) Receiving and retransmitting any
exemplar vectors destined for processors
downstream;
(5) Receiving and retransmitting the
weights;
(6) Using the weights to calculate the
output for the neural network for each of
its exemplar input vectors;
(7) Comparing the neural network
calculated outputs with the exemplar
output vectors and calculating an error
value;

Save "Mao-Years of Effort~ with Thrbo 5.5
Don't Start from Scratch
with Object-Oriented Pascal

Object Professional includes
clear, comprehensive documeiltation,
on-line help, full source code,
technical support, and hot demo
programs. Pay NO royalties. You'll
get up to speed fast with OOP!

Object Professional is a huge library
of over 200 object types and 2000
methods that
will multiply
iliThe range of objects is
your productanttm;ttc. Object Professional
tivity. Window
could literally save you
object types let "';;;=;;;~II ~ ~I'!!!!~a.
man-years of effort. JJ
you use overJeff Duntemann
lapping and
resizeable
~iiiiiiiiiaii• •l',',j(",:!~
Object Professional 1.0,
windows. The ...
only $150.
windows include _ scrolling data
entry screens _ pick lists _ menus
_ file selection _ printed forms
AMulti-User B-Tree Toolkit
_ help capability and more.
Write powerful network
Build your programs using
compatible databases faster and
proven data object types like stacks,
easier using B-Tree Filer 5.0.
linked lists, virtual arrays, and more.
You'll have the fastest, safest, most
System-oriented routines provide
flexible databases - no rigid strucswappable TSRs in only 6K of RAM,
ture, no TSR hassles, no running out
EMS management, and much more.
Satisfaction guaranteed or your money back within 30 days.
Add $5 per order for shipping in U.S. and Canada. Inquire
about other shipping charges. OPro requires Turbo 5.5.
BTF requires Turbo 4.0. 5.0. 5.5. or QuickPascal.

of files. And they're compatible with
Novell, 3Com, MS-NET, and others.
You get _ Fixed and variable
length records _ Two billion
records per database _ Up to 100
indexes per index file _ Fail-safe
mode with joumaling _ Units for
sorting, browsing, reindexing, and
network control.
B-Tree Filer includes full source
code, documentation, technical
support, and you pay NO royalties.
iii B-Tree

Filer ... a well rounded,
feature-rich approach to
B-Tree databases. JJ
Computer Language, 1/90

B-Tree Filer 5.0, only
$125. (single user)
With network support, $175.

Call toll-free to order.
1-800-333-4160

8AM - 5PM PST Monday through Friday. USA & Canada.
For more information call (408) 438-8608. Fax: (408) 438~86\O.
TurboPower Software PO Box 66747 Scotts Valley. CA 95067-0747

Reader Service Number 194

MICRO CORNUCOPIA, #53, May, 1990

51

(8) Transmitting its error value
downstream;
(9) Receiving and retransmitting any
error values produced by upstream processors;
(10) Receiving and retransmitting any
instructions regarding a backward pass
through the network;
(11) If necessary, using the output errors from all the exemplar vectors to calculate the changes in the weights;
(12) Receiving the weight change
array from upstream, adding the locally
calculated changes, and transmitting the
array downstream;
(13) And looping back to 5.
The third program (TAIL) runs on the
last transputer in the pipeline in parallel
with a copy of the PIPE program. Unlike
the other processors that used the hardware DMA channels Oinks) to transfer
data from one processor to the next, the
PIPE and TAIL programs on the last
processor communicate with each other
over a memory channel.
From a programmer's perspective,
memory channels operate identically to
hardware channels. This means that the
last PIPE program is identical to the
PIPE programs on the other processors.
The TAIL program primarily transmits information coming out of the pipeline back to the administrator processor
and collects garbage. When the neural
network topology information reaches
the last pipe processor, there's nowhere
to send the data.
Since all the PIPE programs are identical, the last PIPE program will try to
send the data on anyway. TAIL receives
the topology data and discards it. The
weights transmitted down the pipeline
are likewise garbage collected. The error
values and .the weight change array,
however, are sent back to the administrator.
Each of the processors has a harness
program. The harness programs specify
whether specific channels are hardware
or memory channels and which programs (ADMIN, PIPE, or TAIL) are to be
run together. The TAIL program can run
on the same processor as the ADMIN
program instead of with the last PIPE
program. Or, if space allows, a copy of
the PIPE program can run on the administrator processor. To maintain load
balance, it might be necessary to reduce
the number of exemplar vectors that this
first PIPE program processes.
Finally we must write a short configuration file (used by the network

52

MICRO CORNUCOPIA, #53, May, 1990

loader program) to indicate which program is to run on which transputer. The
network loader is responsible for resetting all the transputers and loading each
one with its specific program. From the
file, the network loader can tell which
transputers and which links a program
must be transmitted through before it arrives at the transputer on which it's to
(ultimately) run.
Unfortunately, programming transputers isn't always as simple as I've
made it sound. Fortunately, vendors are
improving their operating environments.
For example, some vendors support
message handling protocols. With some
of the protocols, a communications
process runs continuously in parallel
with the application program. Any time
data must be sent to another transputer,
the application program uses a vendor
supplied function or a memory channel
to pass the data to the communications
process. This process adds a header to
the data and sends the message out the
appropriate link.
Another transputer receiving the
message uses the header to determine
whether the message is intended for
another transputer or for itself. If necessary, the process forwards the message
off to another processor. Otherwise the
process strips the header off the message
and sends the data through a memory
channel to the appropriate application
process. While this scheme slows down
applications, it can make communications simpler.
More important, these communications processes give you a means for debugging remote transputers. Although
the application program may have
stopped on a remote processor because
needed data hasn't communicated to it,
the communications process can still
send and receive messages. One of those
messages can be an instruction to read a
particular memory location or register
and send the data back over a link.
Discussion
The topology of the neural network,
the number of test vectors, and transputer memory resources will determine
how you manage the transmission of
weights. In most situations the administrator transputer transmits the weights,
storing them in the pipeline processors.
During the error correction phase of
the training cycle, each processor generates changes for the weights. These

changes are then sent back to the administrator where momentum and learning
rate adjustments get made. This approach requires few (if any) parallel
processes.
If, however, the network is very large
and there are memory limitations at the
nodes, you might have to break the
weights into packets (say all the inbound
weights for a hidden unit) and send
them sequentially down the pipeline.
The PIPE program would then calculate all the partial sums for each exemplar vector. With all the weights for one
layer received, the activation function
would be calculated for each unit.
There are, of course, other approaches to dividing a neural network
simulation among transputers. For example, reference 7 describes how each
transputer can process a subset of the
nodes. Other researchers have used
transputers with non-back-propagation
neural networks. 8,9,lO
In Sum
The back-propagation simulation of
neural networks maps very nicely into a
parallel processing environment. While
other parallel processing platforms are
available, transputers provide a cheap
way to optimize neural network simulations. Plus, we can use these transputers
for other applications as well.
References
1 Pelczarski, M., "System Review:
Microsoft Softcard," BYTE, vol. 6, no. 11,
November, 1981, pp 152-162.
2 Inmos Limited, The Transputer Reference Manual, Prentice Hall, London,
1988.

3 Atkin, Phil, "Performance Maximisation," Technical Note 17, InmosSGS Thomson, Bristol, UK, March 1987.
4 "Some Issues in Scientific Language
Application Porting and Farming Using
Transputers," The Transputer Development and iq Systems Databook, Inmos Ltd.,
1989.

5 Pomerleau, D. A., Gusciora, G. L.,
Touretzky, D. S., Kung, H. T., "Neural
Network Simulation at Warp Speed:
How We Got 17 Million Connections per
Second," Proceedings of IEEE International Conference on Neural Networks, San Diego, USA, July 1988, pp
11-143-150.

6 Chang, M. W. H., and Fallside, F.,
"Implementation of Neural Networks
for Speech Recognition on a Transputer
Array," Technical Report CUED/F-IN-

FENG/TR8, Cambridge University, Department of Engineering, Cambridge,
UK, March, 1988.
7 Beynon, T., "A Parallel Implementation of the Back-Propagation Algorithm on a Network of Transputers,"
Research Initiative in Pattern Recognition, Royal Signals and Radar Establishment, Malvern, UK, Poster Paper,
1988 IEEE International Conference on
Neural Networks.
8 Di Zitti, E., Caviglia, D. D., Bisio, G.
M., and Parodi, G., "Neural Networks
on a Transputer Array," Proceedings of
the 1989 International Conference on
Acoustics, Speech, and Signal Processing, pp 2513-2516.
9 Abbruzzese, F., "A Transputer Implementation of a McCulloch & Pitts
Network," Parallel Processing and Applications, E. Chiricozzi and A. D'Amico
eds., North-Holland, 1988, pp 135-140.
10 Board, J. A., Jr., and Lu, J. S. J.,
"Performance of Parallel Neural Network Simulations," Proceedings of the
Second Conference of the North American Transputer Users Group, J. A. Board,
Jr., ed., Durham, North Carolina, USA,
North American Transputer Users
Group, 1989, pp 185-200.
11 Lee, D. G., Jr., "Preliminary Results of Applying Neural Networks to
Ship Image Recognition," Proceedings
of the 1989 International Joint Conference on Neural Networks, June 18-22,
1989, Washington DC, IEEE, San Diego,
II-576.
12 Rumelhart, D. E., Hinton, G. E.,
and Williams, R. J., "Learning Internal
Representations by Error Propagation,"
in Parallel Distributed Processing Volume
1: Foundations, Rumelhart and McClelland ed., Cambridge, Massachusetts,
USA: MIT Press, 1986, Ch. 8, pp 318-362.
13 Leung, H. c., and Zue, V. W.,
"Applications of Error Back-Propagation
to Phonetic Classification," Proceedings
of the Neural Information Processing
Systems - Natural and Synthetic Conference, November 28 - December I, 1988,
D. S. Touretzky, ed., Morgan-Kaufman,
1989.
Vendors
Companies advertising Transputer
TRAMs and/or language compilers for
use with the Transputer:
Inmos-SGS Thomson
1000 Aztec West
Almondsbury Bristol BS12 4SQ
UK

Levco
6181 Cornerstone Ct. East, Ste. 101
San Diego, CA 92121

Transtech Devices Ltd.
Unit 17, Wye Industrial Estate
London Road
High Wycombe
Buckinghamshire HPlllLH
UK

Multis Corporation
99 Willie Street
Lowell, MA 01854

Companies advertising neural network software using coprocessor cards
and IBM PC compatible computers:

MicroWay, Inc.
P.O. Box 79
Kingston, MA 02364

SAIC
10260 Campus Point Dr.
San Diego, CA 92121

Computer Systems Architects
950 North University Avenue
Provo, UT 84604

HNC
5501 Oberlin Drive
San Diego, CA 92121

Logical Systems
P.O. Box 1702
Corvallis, OR 97339

Company advertising neural network
software for Transputers and Apple
Macintosh II computers:

3L Limited
Peel House
Ladywell Livingston EH54 6AG
Scotland

Neurix
One Kendall Square, Suite 2200
Cambridge, MA 02139

Sension
Denton Drive
Northwich Cheshire CW9 7LU
UK

•••

You're in charge
Don't be limited by someone
else's idea of the perfect menu. SuperMenu's unique graphical interface
adds a level of creativity, individuality, and ease-of-use not found anywhere else. Why shoehorn your
software into a stuffy, preconceived
mold when SuperMenu gives you
complete control over the structure,
format, and appearance of your
menu? Most menu systems give you
a modest choice of screen colors and
then claim to be customizable. SuperMenu gives you color plus a palette
of drawing tools, multiple fonts, fill
patterns, line styles, pop-up notes,
and more. You can even edit the
background pattern. In fact, SuperMenu has many features you'd only
expect to see in an expensive drawing
program, much less a menu generator.
• Graphical mouse-driven
interface
• Instant access to your softw::re :md DOS options
• Worksw/allpopularprograms
• Easy-to-use drawing
tools, fonts, fill patterns,
line styles, and colors

e
u t c Opy

...

Pt

r1"
•
.

.,,'

F ron t B k G roup

MASTER

Ii

~

ISN..ESPEOPlEII

mITJ
L
Too'.'

PIAlLISHING

4

ACCOUNTING

Pr.v .. N.xt

III

Scale

..

MENU

'h
•

rSus.n'sClienu

W

,

~

~ ~

W _~

Backups I FORMAT

'"

I

I
I
G'~--I
I
I
SACKUP - TUESOA'!'

?

BACKUP -

WEONESDf'IY

I BACKUP - HlJRS(lAV J
I BACKUP - FRIDAY I

1~Il-KlRDPRQC[SSlNGI

Ho•• l { End

--w

DOS Cornlrlands

.. Ga. . .

~

flIiJ"-IOIOI0IAI

SuperMenu's easy-to-use
mouse driven interface makes
running your favorite software a
snap. Other computer tasks,
such as daily backups, can be
easily automated and accessed
with a simple mouse click.

• Multiple menus, each
with up to 99 pages
• Hypertext-like links
between pages
• Pop-up notes
• Passwords prevent unauthorized modifications
to your menus

AI,gn

~!zDp.

1Inli'1I jIlilUtD

o

1lARRY'SNOIJEI.."

Unogroup

Because SuperMenu has a
wide range of powerful tools,
menus can be as complex or as
simple as you desire. Like we
said, you're in charge.

~lID~~~lID

Add$S.OOS&H
• Date and time display
Please specify 5W' or
• NOT memory resident
3
Vi' when ordering
• Enter DOS commands or
-----------invoke a DOS Shell
• Supports eGA, EGA,
VGA, and Hercules
graphics
1293 NW Wall Street,· Suite 71

49 95

~~[ZJ
Bend, Oregon 97701

Requlfes: mMpc,·.XT, 286;386; psiiOrcompatible.··rios io· or.·greatei,256K RAM?

. .•. rvtic1?so.f~ .~.it~h?!.c9r?~~ti"I~r?9\1s~: SgA,§gA,ygA.~ ~~~\lI~~of~ompati"ledisplaX'

(503) 389-5489

Reader Service Number 216

MICRO CORNUCOPIA, #53, May, 1990

53

Save The Floppies!
Rx For Slipped Disks

This is probably the easiest to use disk
recovery program I've ever seen. You just
insert the flaky disk and fire up the program.
When it finishes, every sector on the disk
will be readable, probably.
ata error reading drive B
Abort, Retry, Ignore?
Grrrrr ...
Back in the old days, when CP1M
had trouble reading a floppy, I could
break out the dependable and userhostile program DU (Disk Utility) for a
little rescue work. DU didn't care about
bad sectors; it would read with reckless
abandon. Often, the "bad sector" had
just a single bad byte. An easy repair job
would restore the file's readability.
I thought it would be useful to have
this ability in an MS-DOS system. Forget
for the moment that MS-DOS already
lets you repair disks with its RECOVER
program. At the beginning of this project, I hadn't made the acquaintance of
RECOVER.

D

A Little Background
Each sector on a disk consists of sync
bytes, ID address marks, ID fields (cylinder, head, sector, bytes per sector), a
CRC value for the ID fields, a gap, more
sync bytes, data address marks, data
(whew, at last), a CRC for the data, and
yet another gap. That's at least 105 bytes
of overhead for each 512 bytes of data.
Add another 146 (or so) bytes of header
info for each track and you'll get an idea
of what the Floppy Disk Controller
(FDC) has to wade through.
At the lowest level, the FDC, acting
under orders from the CPU, selects a
drive, fires up the drive motor, seeks to
the track, performs the requested function, and reports the results to the CPU.
During a read, the FDC looks at the

54 MICRO CORNUCOPIA, #53, May, 1990

Assuming that a
CRC error means a
data error, and
barring physical
damage to the disk,
simply rewriting the
questionable data
to the same sector
should (and has, on
numerous
occasions) restore
the file.

data have changed (or that the CRC has
been corrupted). Why'd they change?
Beats me: a stray magnetic field, a glob
of peanut butter, cosmic rays ....
It would be nice to isolate the data
CRC error from the ID field CRC error.
But after a wade through the XT BIOS
listing, I can't see that it differentiates between the two. So we can either make
the rash assumption that any CRC error
will come from the data, or we can dive
into the FDC to get a closer look at the
error.
Leave your trunks at home (leave
your rash, too). It doesn't make sense to
try to fix the sector ID since it gets written only during formatting; reformatting
a track would wipe out the information
we want to recover. We probably
couldn't read the sector anyway, since
the corrupted ID fields wouldn't match
those requested by the CPU.
Assuming that a CRC error means a
data error, and barring physical damage
to the disk, simply rewriting the
questionable data to the same sector
should (and has, on numerous occasions) restore the file.

track until it either finds ID fields matching those requested, or sees the disk's
index hole pass twice without finding
the matching fields (sector not found). If
it finds the sector, the FDC sends the 512
bytes of data to the host-in MS-DOS
systems, to the Disk Transfer Address
(DTA).
As the FDC scans sector ID fields, it
generates a CRC value for the IDs and
compares this with the CRC recorded on
the disk. If the two don't match, the controller returns a CRC error.
A second type of CRC error comes
when the CRC calculated during the
data read doesn't match the data CRC
recorded on disk. This is the error we're
after. It means that one or more bytes of

Levels Of Disk Access
Most programs use DOS interrupt
21h to read a floppy. DOS deals with
files, so application programmers like it.
No fuss, no muss. But we'd like to get
into some real trouble here. We can get
at the whole disk by dropping one level
closer to the hardware and making use
of the BIOS.
Nestled in ROM, the BIOS doesn't
know or care about directories, files, or
any of the other high level nonsense that
DOS requires. With the BIOS you can
access any sector on any disk, whether
it's allocated to a file or not (including
the directory and FATs). And, like DOS
INT 21h, you can choose to ignore error
conditions.

Larry Fogg
187 NW Jefferson PI.
Bend, OR 97701

Figure I-FLOPFIX.C
1* FLOPFIX.C - Reads all sectors of a floppy. Any sectors with bad
CRCs are rewritten. *1
#include 
#include 
int crc failures;
int sectors recovered;
int non_crc:failures;

1* reset the floppy disk controller *1

void reset FDC ()
{
union REGS in, out;
in.h.ah = 0;
int86 (Ox13, 'in, 'out);
1* reset_FOC () *1

1* service 0 = reset *1
1* INT 13h *1

unsigned char read_sector (unsigned char track, unsigned char side,
unsigned char sector)
union REGS in, out;
in.h.ah = Ox2f;
intdos (&in, 'out);

1* get OTA *1
1* do the INT, ES:BX holds address on return *1

in.h.ah = 2;
in.h.al = 1;
in.h.ch = track;
in.h.cl
sector;
in.h.dh = side;
in.h.dl = 1;
int86 (Ox13, 'in, &out);
return (out.h.ah);
1* read_sector () *1

1* read diskette *1
1* # sectors to read *1

=

1* drive B: *1
1* do the read *1
1* return read status *1

unsigned char write_sector (unsigned char track, unsigned char side,
unsigned char sector)
union REGS in, out;
in.h.ah = Ox2f;
intdos ('in, &out);

1* get OTA *1
1* do the INT ,ES:BX holds address on return *1

in.h.ah = 3:
in.h.al
1;
in.h.ch = track:
in.h.cl = sector:
in.h.dh
side;
in.h.dl = 1;
int86 (Ox13, &in, &out);
return (out.h.ah);
1* write_sector () *1

=
=

void fix_disk ()

1* write diskette *1
1* # sectors to write *1

1* drive B: *1
1* do the write *1
1* return write status *1

continued on page 56

The key here is that, even though an
error condition exists, the data has been
read. It's alive and well at the DTA, and
all you have to do is rewrite it to disk.
Code Notes
You won't find anything very startling in FLOPFIX.C (see Figure 1). fixdiskO makes three attempts to read each
sector. It takes a while for the drive
motor to spin up, so a well behaved program should do these retries to ensure
that any errors are real. (Reads from a
half-fast drive don't have much chance
of success.) A call to reset_FDCO follows
any read failure-again, a required programming practice.
Once we're sure an error has occurred, fix_diskO checks the status returned by read_sectorO. If the status
indicates a CRC error, write_sectorO attempts to rewrite the sector. Global variables for the number of bad sectors and
recovered sectors get updated and we
move onto the next sector.
You'll notice that each sector access
(in write_sectorO and read_sector())
starts with a call to determine the DTA.
This could have been done only once
during program initialization, since the
DTA doesn't change during execution
(unless the program changes it explicitly). But the call to DOS function 2Fh
provides a convenient way to load
ES:BX with the DTA.
But Why Bother?
Sure, sure. Once again, I've reinvented the wheel. But in some situations
it's a better wheel, a bit more round. RECOVER has not been as successful as
FLOP FIX in restoring damaged sectors
to readability (at least, in my humble
opinion). On one occasion a RECOVERed file was not TYPEable. Besides, diving into the guts of the
machine keeps me out of trouble. It's alMICRO CORNUCOPIA, #53, May, 1990

55

ways instructional to try to understand
the inner workings of a system.
If I had more gumption, I'd disassemble RECOVER to see what makes it
tick. I could rip off the good stuff and
add it to FLOPFIX. But wisps of cloud
over the nearby Cascades promise a fine
day of early spring back country skiing.
Some other time for the disassembly.

-~

Continued from page 55

..

unsigned char track, Side, sector, status;
char tries;
reset FDC 0;
for (track=O; track<40; track++)
for (side=O; side<2; side++)
for (sector=l; sectorEXIF.tools

Navigation menu