EDITOR’s ’ N K Working Smarter, Not Fader t’s time we admitted to a character flaw common among engineers. Now, I’m not...
23 downloads
1005 Views
3MB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
EDITOR’s ’ N K Working Smarter, Not Fader t’s time we admitted to a character flaw common among engineers. Now, I’m not talking about the kind of problem that leads to major stories in the newspapers and evening newscasts. No, this problem is insidious, working its way into the applications we design and the products we design. What is this terrible problem, this scourge of the honorable profession of engineering? Horsepower Lust. Yes, whether you’re an automotive engineer trying to shoehorn a V-12 into an econobox, a mechanical engineer still searching for the fulcrum and lever to move the earth, or a civil engineer reflecting on a dam for the Strait of Gibraltar, there’s a general search for more and more power to use in bigger and bigger projects. Computer engineers are as much afflicted as any. I’ve never met an application designer who wasn’t looking for more MIPS, MOPS, FLOPS, or other unit of power. The problem from all of these manifestations of Horsepower Lust, is that the afflicted tend to try to substitute raw horsepower for intelligent design. The computer and controller industry has been particularly offensive in this respect, largely through the heroic efforts of microprocessor and microcontroller designers. If you want to do something that simply soaks up too many clock cycles to be reasonable, just wait six months for a faster processor. Hardware speed improvements have stayed ahead of applications needs for the last 15 years or so, letting application designers and programmers “shoot for the moon” and get away with it. Now, for better or for worse, we’re running out of silicon’s ability to give us more horsepower. (OK, I know about GaAs and optical computers and other new technologies, but they only postpone the problem.) It looks like we’re all going to be forced to (gasp!) look for new ways to solve problems, search for new ways to save cycles, and find new applications for old control and computing solutions. That’s where CIRCXJIT CELLAR INK comes in. In this issue on Intelligent Applications, we look at intelligence from a couple of different prospectives. The first is the quest to make an electronic analog of the human brain. Neural networks hold much promise for grand design in the future, but they’re also useful for problem-solving today. We show you two different approaches to neural networks,and hope that you will experiment with what you see. The second intelligence perspective is that of offloading processing to outboard devices. I think it makes sense: If the applications are getting too complex for a single central processor, start feeding the processor predigested information. It works for baby birds, why not for data acquisition systems? In short, what we’re talking about is substituting designintelligence for raw horsepower. It’s a trade that can get you some surprising performance wins, and let you bring in cost-effective solutions when others are offering goldplated bells and whistles. (Of course, if you can combine lots of horsepower with an intelligent design, then you’re way ahead of the game, aren’t you?)
I
Odds and Ends
You’ve probably noticed that there’s been an interruption in the Home Satellite Weather Center series. We’re not abandoning those who have been following the series: Mark has just taken some extra time to get everything in order for the conclusion of the project. The Weather Center should be back soon, getting wound up for a big finish. In the next issue, C IRCUIT CELLAR INK will focus on controlling one of the most complex environments around: The Home. The center of the theme will be built around networking. In addition, there will be articles on control of and by telephone, as well as a fascinating project for receiving television broadcasts from the Soviet Union. Think of it as a technical response to the oromise of Glasnost.
Curtis Franklin, Jr. Editor-in-Chief
June/July 1989 1
FOUNDER/ EDITORIAL DIRECTOR
A I
Steve Ciarcia PUBLISHER
N
K 8
Daniel Rodrigues EDITOR-in-CHIEF
Curtis Franklin, Jr,
The X- 10 lR543 Infrared
ASSOCIATE PUBLISHER
Control your lights with your trainable IR remote by Ken Davidson
ENGINEERING STAFF
Infrared remote control is becoming more important as a gateway in to building control sys terns. Having that
John Hayes Ken Davidson Jeff Bachiochi Edward Nisley
gateway and knowing how to control it can give you a leg up in thb burgeoning control area.
CONTRIBUTING EDITOR Thomas Cantrell Jack Ganssle CONSULTING EDITORS Mark Dahmke
Larry Loeb
CIRCULATION COORDINATOR
Rose Manse/la CIRCULATION CONSULTANT
Gregory Spitzfaden
ART DIRECTOR
A Neural Network Approach to Artificial Intelligence Using a Neural Network for dealing with Real- World Data by Christopher Ciarcia Neural Networks are a promising technology in the push for more capable computers. The theoretical foundations of neural nets are important tools for building real-world applications. Shape recognition and discriminating machine vision are examples of applications possible today.
Tricia Dziedzinski
PRODUCTION ASSITANT
Lisa Hebert BUSINESS MANAGER
Editor’s INK
Jeannette Walters STAFF RESEARCHERS
1
Reader’s INK-Letters to the Editor
5
William Cur/e w Richard Sawyer Robert Stek
Visible INK-Leffers to the INK Research Staff
a
Jon Eison Tim McDonough
From the Bench
Northeast Eric Albert
Midwest
West Coast Frank Kuechmann
Mark Voorhees
Cover Illustration by Robert Tinney
2
Working Smarter, Not Faster by Curtis Franklin, Jr.
CIRCUT CELLAR INK
Silicon Update
The Invisible Net by Jeff Bachiochi
44
The Waferscale Integration PAClOOO Microcontroller, RISC, or PLD? by Tom Cantrell
50
Circuit Cellar BBS-24 Hrs. 300/1200/2400 bps,
8bits. no parity, 1 stop bit, (203) 871-1988.
THE COMPUTER APPLICATIONS JOURNAL
The ADALINE Learning Neuron
A One-Node Net for Computer Learning by Scott Farley
Most neural network research involves large budgets and even larger mainframe computers. But artificial neurons can be harnessed for useful work on a modest desk-top computer, Handling ‘fuuy” data is not (I problem limited to the luborutory: a simple neuron on u common microcomputer can bring irregular data into useable focus.
An Intelligent SCSI ata Acquisition System for the Apple Macintosh PCXI 1 -Building the Hardware
by John
Eng
The SCSI Bus offers important performance benefits compared to standard 175-232 links. Properly implementing the protocol requires an intelligent peripheral, but the intelligence and performance cun bring impressive application results. The first of two parts looks at the hardware for an intelligent 12-bit A/D converter.
An Apple Macintosh is the host computer for this application of distributed intelligence.
Software by Design
Firmware Furnace
Computing CRCs in Parallel by Jack Ganssle
55
From Fixed Point to Floating Point and Back Again by Ed Nisley
60
Writhing Reals
Advertiser’s Index
65
Updde: Build an 87xx Programming Adapter
69
ConnecTime-fXcx?rptS from the Circuit Cellar BBS Conducted by Ken Davidson
74
by Jeff Bachiochi
Steve’s Own INK
The Good Old Ways by Steve Ciarcia
80
The schematics provided in Circuit Cellar INK are drawn using Schema from Omation Inc. All programs and schematics in Circuit Cellar INK have been carefully reviewed to ensure that their performance is in accordance with the specifications described, and programs are posted on the Circuit Cellar BBS for electronic transfer by subscribers. Circuit Cellar INK makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the consequences of any such errors. Furthermore, because of the possible variation in the quality and condition of materials and workmanship of readerassembled projects, Circuit Cellar INK disclaims any responsiblity for the safe and proper function of reader-assembled projects based upon or from plans, descriptions, or information published in Circuit Cellar INK. CIRCUIT CELLAR INK (ISSN 08968985) is published bimonthly by Circuit Cellar Incorporated.4Park Street,Suite X).Vernon, CT 0 6 0 6 6 (2031 875275 1. Secondlclass postage paid at Vernon, CT and additional offices. Oneyear (6 issues) subscription rate U.S.A.andpossessions $14.95,CanadaS17.95,all other countries $26.95. All subscription orders payable in U.S. funds only, via international postal money order or check drawn on U.S. bank. Direct subscription orders to Circuit Cellar INK. Subscriptions, P.O. Box 2099. Mbhopac, NY 10541 or call (203) 875-2 199. POSTMASTER: Please send address chanaes to Circuit Cellar INK, Circulation Deat.. P.O. Box 2099. Mahopbcl NY 10541. Entire contents copyright 1989 by Circuit Cellar Incorporated. All rightsreserved. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.
June/July 1989 3
cm
READER’S ’ N K
Letters to the Editor
I have just finished reading the January/February If you’re using a new technique to solve a problem, you bet issue of G~curr CELLAR INK . It reminded me why, after we’d like to hear from you, Many of our articles are written by quitting the computer business several times, I am still so working engineers or designers who write in to describe their attracted to silicon. Cr~curr CELLAR INK has rekindled that latest project. If you would like an Author‘s Guide, send your wide-eyed feeling of awe and power I felt after construct- request to: ing my first 2-bit adder in college. Circuit Cellar INK After seeing a letter from Dr. Huong of Computer Age Author’s Guide Ltd. in one of last year’s issues, I went to see him; some4 Park St. thing I hadn’t done in five years! Dr. Huong showed me a Vernon, CT 06066 voice card he built and I purchased it as a companion to the The efhical considerations of engineering are many and ImageWise transmitter I own. Now my IBM PC can see, varied. If anyone else has an answer (or maybe just an opinion) hear, and talk. Dr. Huong was talking about some of the on the subjecf, let us know. data compression techniques used by Toshiba in the voice When you mention “case study,” you come vey close to a chip he uses. I wondered if similar techniques could be detailed review. We haven’t had any reviews so far (fhe “April used on a .PIC file. After some preliminary investigation Fool” arficle notwithstanding), and we’re not sure that we need it seems that 64- or 256-color files can always be com- to. Affer all, there are many other magazines fhat focus on pressed from 63K to about 8K! The conversion process is reviews. It boils down to this: if we feel that we can offer CIRCUIT not yet perfect but under certain circumstances could be CELLAR INK readers information fhat they need and can’t get useful. I can send you a copy of the compress and uncom- anywhere else, we’ll do if. Until fhen, we’ll stick with the press program I am developing if you would like a first- technical information and leave the reviews to others. E&for. hand look. I would welcome the opportunity to do an article for CIRCUIT CELLAR INK readers. High-resolution pictures could move over ISDN line at one frame per second or faster. With more sound and images being digitized, and the quality of the renditions improving, I am starting to worry about the opportunity this presents for distortions of the In Circuit Cellar BBS On Disk Issue 5 you indicated truth. I can’t help but wonder when the first news clips that you would like suggestions for topics and content. could be generated entirely from bits. How do other Here are mine.. . CIRCXJIT CELLAR INK readers feel about the technologies that Reviews-None of any kind. are being developed? My preference is for construction project articles or Finally, have you considered doing case-study reports hardware/software combined application information. I on interesting hardware/software systems? These feel that the software source for projects should be made wouldn’t be reviews, they would be done by someone who available so that we can modify it for our own uses. used an interesting system to solve interesting problems. Iamnot interested inany IBM PC-related applications As an example, those new neural network programs--can except (perhaps) for development purposes. I would they be used to keep track of all the facts I forget as the years rather see dedicated stand-alone microprocessor applicapass? tions. Please try to maintain the continuity of articles by Steve Carter keeping them together and not continuing the last part on Miss., Ontario back pages. It would also be nice if all advertising could be
June/Ju/y
1989 5
CCINK’s 1st Year Re rids
lout of the first year of INK. Our fast rise in circulation has resulted in avirtual seP So as not to disappoint any of our readers, we are offering a B&W offset reprint of CCINK’s first year (issues 1-6). Available for $20.00 in the U.S. and $24.00 to Canada and Europe (shipping and handling included). Send check or money order to: p\o* Circuit Cellar INK - 1st Year Reprint B to ,2‘HeeKS P.O. Box 772 - Vernon, CT 06066 to’c ~e\iyely Visa or MasterCard accepted, call (x)3) 8752199
put between articles or on the back pages, not put in the middle of articles. Deslar Kyn Patten Hayward, CA
AVAILABLE BACK ISSUES
Thanks for the input: we really do depend on readers to let
Issues #l-4 are sold wt Issue #%-Remote Video Surveillance ROVER: Remotely Operated Video-based Electronic Reconnaissance * Home Satellite Weather Center: Focus on the MC68000 Peripheral Controller - lOMHti-bit Digitizing Board for the IBM PC Precision Pulses: Carrier Current Transmission Timing Issue #6-Data Acquisition ROVER: The Software Home Satellite Weather Center Adding Serial and Parallel Ports to the Peripheral Controller Building a Remote Analog Data Logger ImageWise/fJC-The Digitizing Continues DDT-51 Revealed Issue #7-Computing III Real Time * ImageWise/PC: The Hardware Build a Remote Analog Data Logger Home Satellite Weather Center: Finishing the Firmware for the Peripheral Processor - Writing a Real Time Operating System Issue #&Creatlve Computrng * Switching Power Supplies Writing a Real Time Operating System: Memory Management and Applications for the HD64160 ImageWise/PCThe Digitizing Continues * HfX47160-A New E-bit Microcontroller The True Secrets of Working with LCDs - Creating a Network-based Embedded Controller
us now how we’re doing. We started the IRS at the end of each article to make talking to us easier. Fill out the post-paid card, drop it in the mail, and you’ve told us what you did and didn’t likeabout theissue. Ofcourse,wesM like theletters wegetfrom readers; we just know how busy most of you are. We ty for a balance of articles in C IRCUIT CELLAR INK. You’ll see hardware, software, stand-alone, and host-based articles in OUY pages. We hope that each one will have something eng’neers can use, even if they don’t do development for the particular system used in the article. Running the beginningand end of anarticlein twodiffeerent parts of fhe magazine is known in the publishing industry as “jumping.” CIRCUIT CELLAR INK has not used jumps, and there aren’t any in our future plans. As for advertising, we feel that CIRCUT CELLAR INK Advertisers providea service to OUT readers. Having a mix of advertising and editorial material in OUY pga makes for a better magazine for everyone. Editor.
l
l
l
l
l
l
l
l
l
l
l
l
Send $4.00 per issue (indudes S&H) in chedc or money order to : Circuit Cellar INK, P.O. BOX 772, Vernon, CT 06066. Visa And MasterCard accepted, call (203) 675.2199.
EXPRESS CIRCUITS MANUFACTURERS OF PROTOTYPE PRINTED CIRCUITS FROM YOUR CAD DESIGNS TURN AROUND TIMES AVAILABLE FROM 24 HRS - 2 WEEKS Special Support For: l
TANGO.PCB
l
FULL TIME MODEM
l
TANGO SERIES II
l
GERBER PHOTO PLOTTING
l
PROTEL AUTOTRAX
l
CAMERA REDUCTIONS
l
smARTWORK
l
HiWIRE-Plus
l
EE DESIGNER I
l
EE DESIGNER III
l
OTHER PACKAGES ARE NOW BEING ADDED
Circle No. 122 on Reader Service Card 6
CIRCUIT CELLAR INK
Express Circuits
314 Cothren St., P.0. Box 58 Wilkesboro, NC 28697
Quotes: l-800-426-5396 Phone: (919) 667-2100 Fax: (919) 667-0487
Ctrl
V[SlBLE I
N K
Letters
to theINK Research Staff
Answers; Clear and Simple
A Little Misdirection We are users of an Epson Equity III+ microcomputer. We run under MS-DOS 3.20 and do most of our programming with RM-COBOL 1.5D. We have two Epson printers attached to our system via parallel ports. The interface between major and minor screens of our menu-driven program consists of CALL S to subprograms. The main program is called by typing the name of a batch file from the DOS prompt. The problem is this: We need to address either of the two printers from within the subprograms depending on what type of report we need to print. Our compiler doesn’t provide a facility to do this, and we can’t use the MODE command since the choice isn’t made at the DOS prompt level. We have resorted to the following unsatisfactory method of printing: fa.bat echo off mainprog MODE lptl:=lpt2 LISTING MODE lptZ':=lptl LISTING (mainprog is the main COBOL program that dis-
plays the main screen, CALLS the subprograms, and creates the LISTING.BAT file. LISTING.BAT contains the invocation of the printing program.)
This is unsatisfactory because the system hangs on the first MODE command. Please help us find a simple way to make this work. Ramon Gonzales Barroeta Caracas, Venezuela
This is a fairly common problem of swaw’ng printer ports. The simplest programming to do the swap uses BASIC. This program simply swaps the contents of the memory locations in DOS where the two parallel ports are referenced. If you run it once, it sends LPTZ output to LPT2. Run it again and everything is back to normal. If you compile this with QuickBASIC, 8
ClRCUlT CELlA R INK
you should be able to call if from within another compiled program. DEF SEG = &H40 TEMPl = PEEK (8) : TEMP2 = PEEK (9) POKE 8, PEEK (10) : POKE 9, PEEK (11) POKE 10, TEMPl : POKE 11, TEMP2 SYSTEM
The only problem with this is that if compiles into a relatively large .EXEfile. Ifyo~ want compact, though, you’ll have to dig out your assembler and do your own research!
Just Give Me Time
I was one of the early buyers of the SB180 single-board computer(“Ciarcia’sCircuitCellar,”Sept/Oct 1985BYTE). I’ve since added a number of upgrades, including the COMM180 SCSI board with XBIOS and ST225N. The only thing my system lacks is a permanent clock. The easiest way to add one is through a SmartWatch under the boot ROM. The problem is, the SCSI board uses a lot of real estate for a modem chip which I don’t need, and the board leaves insufficient space over the boot ROM for me to install the SmartWatch. Just to complicate matters, I built the system into a very small case. I only have room for one expansion board. My way out was to buy some SCSI chips and build my own board. I used the 53C80 since heat was a problem in the small case. I read a number of relevant articles and used the circuit shown. I needed the lowest chip count to reduce both the board size and the number of connections. It almost worked! Running with XBIOS the machine hangs in the boot process, but with the SB180 3.1 BIOS I get a more useful “phase error” message. I can’t decipher it, however, since I have no hardware debugging tools except for a logic probe and DVM. I have traced to be sure that the constructed hardware is identical to the schematic. Can you spot some problem with my circuit? I’d be grateful for any help. This is a trivial design, but when you build without proper debugging tools you have
Figure 1 --The SCSlportion of the COMM 180 uses the NCR5380 to interface to the SCSI bus.
no way of telling if the fault is in concept or execution-an original design that is known to work is very comforting. C.W. Rose San Diego, CA P.S. The 220/330-ohm resistors on the SCSI bus consume an awful lot of power. Can they be increased to 440/ 660 or even 2200/3300? You are correct that a Smart Wafch is the best way to add a real-fimeclocktoanSB180system. Thepreferred way to provide clearance is to extend the SCSI board above the main board with an extension connector, but that obviously won’t work if clearance is too tight. Your schematic looks fine. There isn’t a lof involved in connecting the 53C80 to the SB180 XBUS. It might simplify thingsfor you to know that neither interrupts nor DMAareused in current software, so you can get away with leaving off the connections to EOP\, DRQ, READY,and lRQ\ on the53C80. (EOP\ should be pulled up; just connecf it to DACK\.) The phase error you’re receiving generally points to a problem with the processor talking to fhe SCSI chip, so it’s not terribly helpful by itself. A number of very useful tests could be performed with an oscilloscopeand theSB180’s monitor, but we won’t go into solutions involving equipment you don’f have. 10
CIRCUIT CELLAR INK
We’ll just suggest checking your wiring against the schemafic onemore timeand makingsure that you’veproperlyin~erprefed the pin numbering on the XBUS connector itself. As for the terminating resistors, fhe ANSI SCSI spec specifically calls for 330-ohm pull-up and 220-ohm pull-down termination on the bus. If you want your interface to agree with thespec, you’ll have to leave them as is. Only if you have a short run of cable and if you don’t mind possible noise or echoes on the line and if you don’t care whether your bus matches the spec should you play with the values of the resistors.
IRS
201 Very Useful 202 Moderately Useful 203 Not Useful
In Visible INK, the Circuit Cellar Research Staff answers microcomputing questions from the readership. The representative questions are published each month as space permits. Send your inquiries to: INK Research Staff c/o Circuit Cellar INK Box 772 Vernon, CT 06066 All letters and photos become the property of CCINK and cannot be returned.
The X-10 lR543 Infrared Gateway/Controller Confrol your lighfs wifh your fruinuble IR remofe by Ken Davidson
ow does the television commercial go? WIy wife left me, so I bought an expensive television set, and it came with a remote. Then my dog died, so I bought a VCR, and it came with a remote. Then I was transferred to Alaska, and it came with two remotes.. .”
Well, you get the picture. It seems every device even closely related to consumer electronics comes with a hand-held infrared remote control these days. And once you start putting together your entertainment center, you end up with a pile of incompatible, but necessary, remotes. To combat the problem, a host of trainable controllers have been introduced to themarket. Indeed,Stevedid a Circuit Cellar article for the March ‘87 issue of BYTE which described his design of just such a trainable remote. So now we can control the TV, VCR, cable box, CD player, and so on with a single IR remote. What about thelightsorotherappliances wemight iavepluggedintox-lOmodules? How :an we remotely control those without Ising the hard-wired consoles?
When BSR first introduced their System X-10, there was a hand-held ultrasonicremoteavailableforit. Back in the late seventies, those TVs that had remotes usually used ultrasonic, so the choice was appropriate. When System X-10 was taken over A Solution Appears by X-10 (USA) Inc., the ultrasonic remote/base pair was discontinued Thelatest addition to X-lo’s prodand replaced by an RF system, the uct line goes a long way toward rectiRC5000. The RT504 hand-held re- fying the situation. The IRS43 is an motecan send out signals to theRR501 infrared-to-X-10 gateway/controller base unit to turn modules on or off which will receive X-10 commands and can dim or brighten lights. While from a hand-held IR remote control, you have all the advantages of RF tack on house code information, and (youcanusetheremotefromvirtually broadcast them over the power line. The schematic for the IR543 is anywhere within your house), you still can’t point the hand-held RF unit shown in Figure 1. The box contains at your trainable IR remote and expect the usual requirements for an X-10 the IR unit to learn the signals. Add transmitter: power supply, zero-crossone more box to the remote pile. ing detector, free-running 120-kHz June/July 1989 11
t
oscillator, and output drive circuitry. (For details about how the X-10 system works, see “PowerLine-Based Computer Control” inissue#3ofCIRcurrCELLARlNK.) The key element in the IR543, though, is the custom 78542C controller chip. The 78542C takes care of all the unit’s operating details such as scanning a keyboard, translating a keycode into an X-10 bit sequence, tacking on housecode information, and sending the code onto the power line by watching the zero-cross- encased IR receiver section. ing input and gating the 12O-kHz . _ signal onto the power line using the trasonic control unit didn’t mean the correct timing. In addition, the chip end of the 78542C, however. The chip has a surreptitious “serial” pin for ac- hasbeenusedfor yearsas thebasisfor cepting serial input. the SC503 maxi controller and, until This serial input pin has been recently, the MC260 mini controller. quietly overlooked for years. It turns (The MC260 has eight small push butout that the 78542C was used in the tonsand twolargebuttons. Thenewer original BSR ultrasonic unit. The ul- MC460 mini controller has six rocker trasonic front end’s output was sent switches and uses a different controlto the chip’s serial input so the signal ler chip.) The serial input pin has could be rebroadcast over the power simply been tied to ground in these line. The end of production of the ul- controllers for all these years.
It logically follows that the overlooked capability of the 78542C would one day be tapped again. With the addition of an IR front end in place of the old ultrasonic front end, we can extend the system’s functionality with a remote control. The IR front end of the IR543, which is encased in a metal can for added noise immunity, is responsible for receiving the IR from the hand-held remote and translating it into a seriesof bits for the 78542C’s serial input. Hand-held Dilemma So now we have a box that will receive IR commands and retransmit them onto the power line. How do the IR commands get to the box, though? Unlike the RF remote/base pair, X-10 doesn’t make a low-cost, hand-held transmitter that is dedicated to the IR543. The IR543 was originally designed for a company who built the commands into their own “universal”
Figure 1 --The schematic for the lR543 is virtually identical to that of the MC260 mini controller. 12
ClRCUlT CEL!AR INK
IR remote (the URC-5000 “ONE FOR ALL” from MTC/USA). If you’re already in the market for an all-in-one remote, buying the URC-5000 for use with the IR543 may be a good alternative. However, if you already own a trainable remote, or don’t want to spend the $100 for one, there must be a better way to generate the proper IR signals for use with the IR543. Even though X-10 tells me they may make such a low-cost, dedicated remote in the future, there is a definite gap that needs filling. Since X-10 was able to give me complete specs on the IRcodes being used, I decided to build my own IR command generator. And since it would only be used to train my trainable remote anyway, it could be quick,and dirty. The Better Alternative
Figure P-The basic circuit used for generating X- 10 IR codes consists mostly of un EPROM, a few counters, and a master clock.
.
SIP1
.
I0k
.
-XMIT
a)
t T\
b)
Keyboard
:igure 3-a) A set of DIP switches plus a ‘transmit’ switch are all that are necessary for 1 one-time-use circuit. b) A keyboard may be added for everyday use of the circuit.
It is possible to interface a simple IR LED driver circuit to an output bit on a personal computer, then drive the LED with some software to train the trainable remote, but it was more fun to build a dedicated, hardwareonly board to generate the IR command strings. Using a hardware-only solution also opened the door to the addition of a real keyboard so those who don’t have a trainable remote and don’t want to spend the money on one can build a usable dedicated remote for use with the IR543. Figure 2 shows the basic circuit for generating the IR commands. Figure 3a has the additional circuits necessary to build a one-time-use-only circuit for use with trainable remotes, and Figure 3b shows what is necessary to add a keyboard to the circuit. Figure 4 shows a sample command string expected by the IR543. “One” bits are represented by a 4-ms burst of 40-kHz signal, followed by 4 ms of silence. “Zero” bits are represented by a 1.2-ms burst of 40 kHz, followed by 6.8 ms of silence. In both cases, one bit time is 8 ms long. The command string consists of a “one” bit, followed by five command bits, the complements of the five command bits, then an “end code,” which is a 12-ms burst of 40 kHz followed by 4 ms of silence. June/July 1989 13
As far as timings go, a complete command string consists of an 8-ms start bit, ten 8-ms data bits, and a 16ms end code, for a total length of 104 ms. Suppose we divide this string into discrete time segments, where each segment is described with a “1” to represent the presence of 40 kHz, or a “0” to represent its absence. We need to generate envelopes for the 40kHz bursts of 1.2,4,6.8,12, and 16 ms, so the largest subdivision we can use is 0.2 ms. The complete command stringcan then bedescribed asa series of 520 bits, eachbit representing a 200microsecond slice of time. Theoretically, we could assemble a table of all 22 commands (16 module numbersand six truecommands) with the bits packed into &bit bytes that would end up being 1430 bytes large. If this command table is going into EPROM, though, why throw away most of the EPROM and make the external circuitry more complex by trying to pack things together? If we encode just one bit per byte, we still only take up 11K of a 16K 27128 EPROM.
For the sake of simplicity, let’s round the 520 bits down to 512 bits. The missing eight bits represent 1.6 ms, so the delay between bursts will only be 2.4 ms instead of the 4 ms called for in the spec, however the spec also says the minimum delay between bursts can be as short as 2.5 ms, so we’re pretty close. It turns out 2.4 ms works just fine. Now all we have to do is clock 512 bits out of the EPROM, one bit every 200 its. Two 74LS163 synchronouscounters (U2 and U3) plus half of a 74LS74 (U4a) provide us with the 9-bit address necessary to access the 512 bits. The outputs of synchronous counters change simultaneously, so we don’t have to worry about glitches coming from the EPROM data line caused by rippling address lines. The output of the EPROM is fed into a 74LSO0 (U&Z) which gates the 40-kHz signal coming from the master oscillator. The output of the LSOO is inverted and drives a highcurrentFET(Q1). ThisFETdrives the IR LEDs (Dl and D2) plus a visible LED (D3) so we know something is being sent.
Heathkif
Powerful Kit Laptop and Desktop Computers
A leader in quality electronics for the technically sophisticated customer. When you need kit or assembled electronic products for work, home or hobby, you can be sure Heathkit products are designed to perform reliably and effectivelv...vear after vear. See whaiwe have to offer. To get your FREE Heathkit Catalog, fill out and mail the coupon below or call toll-free today!
I-800~44-HEATH (l-800-444-3284) r------------
; I I
1
YES!~~~~~~~~~~~~~CO~Y Send To: Heath Company, Dept. 026-774 Benton Harbor, Michigan 49022
Address
Circle No. 127 on Reader service Card
14
ClRCUlT CELLAR INK
i I I
0
Dynamic Home Entertainment Products
The master clock for the counters is derived from an 80-kHz oscillator made up of an LM555 (U8) and a few discretes. The80kHzisdivided down by another synchronous counter (U5) to generate the 40-kHz IR signal (+2) and a 5-kHz signal (+16) whose period is 200 ps. Almost any counter can be used (synchronous or asynchronous), but why not keep the parts list simple and use the same kind all around? To start the transmission of the command string, we use a push button which is debounced with a pair of NAND gates (U6a and b). When the button is pushed, U4b is cleared, the Q\ output goes high and enables the low-order counter, and code transmission begins. When U3 overflows (the count has reached some multiple of 16), it enables U2 for one clock cycle so the high-order counter increments once. When U2 overflows (the count has reached 256), the overflow output clocks U4a, causing the Q output to go high so the second 256 bits of the command can be accessed. Also note that the Q\ output of U4a goes low at the same time. When counters U2 and U3 reach 256 for the second time, the overflow output of U2 clocks U4a again, causing the Q output to go back to zero and Q\ to go to one. If the push button is still being held down, U4b will continue to be held clear and a second transmissionofthecodebegins. Transmissions continue until the button is released. Once the button is released, the rising edge of U4a Q\ generates a clock signal for U4b, which clocks a one bit into the flip-flop. This action causes the Q\ output to go low, disables the counters, and stops the transmission process. To restart things, the button must be pushed again. To select which command is sent, a set of DIP switches is connected to the five high-order address lines of the EPROM. Just set a code from 0 to 21 on the switches, press the “send” button, and the selected code is sent out. Obviously, setting DIP switches and pressing a button would be pretty inconvenient for everyday use, but remember, all we want to do is train the trainable remote. After that we can throw the circuit away.
Dl
p.ue 4-
code.
D2
D4
I314
D1
D2
D4
D8
IX6 End Code
commana srfM-t.us Conslsf Of a leading Start bit, the command coae, me compiemenr or me commana coae. ana an en
;:>~:f$$+ _. :?s>: , . . ‘. . . . .. . ..,. . . . ._ ., B
Input Averaging
! In3 :;:;:;:;:: ,,::::.’C : .::.::.::.>: ::.::.;:. :5’: :: :.::.:., _” . ’ D I j
r
il Back
Propagation
Figure 4-lhe mumpliers of the neuron begin cd a random value between - I and + 1. They are modified by the back-propagation process to bring the actual output closer to the desired output. pattern on which it was originally trained. Simply insist that the output number for the bytebeing tested match the trained output number. For singlebit errors, you allow a percentage difference between the two output numbers. For multibit errors, you allow a larger percentage difference. The process is the same regardless of the bit position in which the error occurs. What is a Neuron?
Real neurons exist only as part of a biological nervous system. We choose to copy their actions in hardware or software because they can accomplish things not normally considered possible with digital computer systems. In particular, they lend themselves to pattern matching and parallel processing. An individual neuron cell has several inputs (Dendrites) and one output (Axon). It is interconnected withmanyotherneuronsand uses the frequency of electrical pulses to have itsoutput influence inputs for several other neurons. The cell has the ability to have inputs from other neurons increase or decrease its output frequency, or have no effect. This is based on its past history and shows that it is “trained” to respond in a particular manner as shown in Figure 2. These neurons are the basis of all of 30
C/KU/T CELlA R INK
our nervous system and thinking functions. Understanding Neurons You can think of a neuron as a biological simulation of a digital AND gate. If we take a multi-input AND gate and “train” it by adding inverters in the input lines and the output line as shown in Figure 3, we can have a particular input pattern producea particularoutput state. Thisisequivalent to providing digital inputs and a desired digital output state to a neuron and having it train itself to those conditions. While the neuron/AND gate can help you understand the neuron, there are significant differences between the neuron and an AND gate, as we shall see shortly. Any continuous process which occurs over a period of time in the real world can be simulated (represented) by measuring its value at different points in time. This is usually done by measuring at regular intervals, such as once per second. The parameter which is measured can be analog or digital. An analog example would be measuring a voltage which changes, but is somewhere between 0 and 5 volts. A digital example might be the opening or closing of a switch. The program I wrote to solve the data problem simulates an analog system by breaking the analog values
into numbers between +1 and -1. It also simulates the passage of time by taking a set of numbers and modifying them a little bit every time the program loop is run through. In this way, successive loops of this part of the program can cause numbers to change in specific directions at specific rates. The way these changes are handled is really quite simple. The value of a variable is equal to its old value plus some modifier value. The modifier value is calculated from the group of old values with which we enter the calculation pass. In this program, some of the old values are modified in each pass, and others do not change. Understanding the ADALINE Neuron One early artificial intelligence concept (in thelate 1950s) was the idea of duplicating the way a neuron works using electronics. This single neuron was first doneby Bernard Windrow of Stanford University. He called it the Adaptive Linear Neuron, which today is shortened to ADA-LI-NE, or ADALINE. You will find three substantial differences between it and the AND gate. TheANDgatewill,fromthefirst operation to the last, give uniform output from uniform input; with
ADALINE, the output for any given input pattern initially depends on random factors. The AND gate is “hard wired” to give a specific output from a known input; given a desired output and a likely input, the ADALINE changes its initial random factors to “train” itself to output the desired state. Finally, where the AND gate is a binary device, outputting either a “f” or a “0” depending on the input, the ADALlNE has a number as part of the output which represents the degree of match between the pattern it was trained on and the pattern presented to it for analysis. Figure 4 shows the various functions the ADALINE uses to perform its processes. The two major divisions are initial learning on a particular pattern, and comparison of other patterns to determine how closely they match the original. Adaline Learning You initialize the learning process by presenting the desired input pattern (digital ones and zeros in this case), the desired output state (one or zero), and randomly generated multipliers which control how much effect each input bit will have on the output state. The output state is represented by a number which can range continuously between +l and -1. This process is called Forward Activation and is the first of three steps in the learning process. The second step consists of determining whether the value of the output state number is close enough to the desired output state to stop the processandsayleamingiscompleted. If the learning is complete, the system can proceed to ADALINE pattern comparison. If the output is still not sufficiently close to the desired result, the process proceeds to step 3.
Human Input TRUE FALSE TRUE
Computer Input 1 -1 1
Back Propagation is the name of the third step. It is started by comparing thedifferencebetween the desired outputstateandtheactualoutputstate from step 1. The error value (difference) is used to modify the randomly generated multipliers from step 1 so that they are changed in a way which will reduce the error value. The amount of change is purposely kept small to prevent oscillation about the correct values when the output is nearly correct. The initial random values will become trained values as this iteration looping proceeds. Adaline Pattern Comparison Now that the neuron has left the training iteration loop and the initial random values have been converted to trained values, theoutput state value is now close enough to the desired state for the ADALINE to recognize the pattern it was originally trained on and produce the output state it was trained to have. When you present the trained ADALlNE a bit pattern for it to respond to, it goes through the Forward Propagationprocessdescribedasstep 1 under ADALINE learning. Since the training process is completed, it does not attempt to train itself to the new pattemoralterthevaluesofthemultipliers. The output state will be correct (match what it was trained to) only for the bit pattern it was trained on. For most other bit patterns, the output value, which can range continuously between +1 and -1, will be far enough from the desired output that they cannot be digitized and have to be represented as indeterminate. For the exact inverse of the bit pattern the ADALINE was trained on, the value of the output value will be the same, with the opposite sign. The digital output state will be the opposite also. Randomly Selected Initial Weight Multiplier 0.25 -0.36 0.04
Weighted Input 0.25 0.36
Call for Manuscripts C IRCUIT C ELLAR INK is looking for quality manuscripts on software for embedded control, software applications, advanced algorithms, software methodology, and tutorials on tools and techniques for developing software. These manuscripts will be considered for publication in C IRCUIT C ELLAR INK, T H E COMPUTER APPLICATIONS JOUR NAL , and in a planned se-
ries of books to be published by CIRCUIT CELLAR INK.
INK offers writers and engineers a technically sophisticated audience and professional editorial guidance. CIRCUIT CELLAR
The C IRCUIT C ELLAR INK Author’s Guide is available for downloading from the Circuit Cellar BBS. Prospec-
tive authors may send mail to ‘Curt Franklin’ on the Circuit Cellar BBS, or send proposals for manuscripts and requests for Author’s Guides to: Curtis Franklin, Jr. Editor in Chief C IRCUIT C E L LAR INK 4 Park Street Vernon, CT 06066
n.no
Table 1 - rhe forward activation process assigns random values to the muitipliers which are used to process the input, The output value from this process is the average of the weighted input.
June/July 7989 31
Desired output 1 1 1
-
Weighted Input 0.25 0.36 0.04
= = =
Input Error 0.75 0.64 0.96
Table 2-lhe input error is the difference between the trained output and the output
resulting from the provided input.
This output value can be used to rate the closeness of match between the bit pattern the ADALINE was trained on and another bit pattern presented to it in this mode. This is the area where it transcends comparison to the AND gate. Simulating the ADALINE
Real neurons change their activation level over a period of time. Your ADALINE will also change over time as its random values become trained values through the iteration process. These internal change processes are analog in nature, so we will represent them by a range of numbers from +l (TRUE) to -1 (FALSE). This means that input patterns and the output
state are represented in the computer program as +l or -1. Other internal processes require an analog representation, so we will restrict them to any value between +1 and -1. The output state number and random multipliers
are two of these. The iteration includes running the
number system through several loops. Each loop can be envisioned as a frame in movie film with small but definite changes with each succeeding frame. This program will usually quit after six to ten loops. At that point the output value has changed considerably,ashavetheinitiallyrandommultipliers. This detailed look at the numbers from the computer program will provide you with a detailed understand-
ing of the ADALINE. The software for this article is written in GWBASIC, and will run on any PC-compatible computer. A companion text file with instructions for running the program is also provided. [Editor’s Note: Softwarefrom thisarticleisavailablefordownloading from the Circuit Cellar BBS and on Circuit Cellar INK Software On Disk #9. For information on downloading and disk orders, see page 78.1. Inputs are three input bits, random multiplier values, and the desired output. ADALINE’s Numbers
The steps for training our ADALINE include: 1) Forward activation 2) Test. If close enough, Exit 3) Back propagate to make small adjustment. Loop to 1. Forward Activation You start the process by inputting the desired input pattern and the output you want it to represent. The
Science, Engineering & Graphics Tools for Microsoft C, Turbo C and Turbo Pascal Science and Engineering Tools are a collection of general purpose procedures and functions which solve the most common data analysis and graphics problems encountered in science and engineering applications. All procedures and functions are supplied on disk in the source code of the target language. The procedures and functions are compatible so the graphics functions can directly display the output of a regression, curvefit, etc. All of the routines can be used royalty free in compiled form. A 150 page manual describes the form, function, and parameters of each procedure and function. The Science and Engineering Tools are available for Turbo Pascal 4.0, 5.0, Turbo C 1.5, 2.0 and Microsoft C 5.x for IBM compatibles. Ordering Information Modell Version Price IPC-TP-016 IBM Turbo Pascal $79.95 IPC-TC-006 IBM Turbo C $79.95 IPC-MC-006 IBM Microsoft C $79.95
Hardcopy support _ Epson MX, FX and LQ printers, HP plotters, HP Laserjet and Thinkjet printers, Toshiba 24 pin printers and other devices Science/Engineering charting routines - Linear, semi-log, and log graphs. Auto-scaling of axes, line, scatter, pie, and bar charts. Charting
Graphics Now Includes Contour Plotting.
‘rice includes shipping within North America. Elsewhere add $18.00 for shipping. Mastercard. Visa, Company PO’s, and personal checks wxpted. MASS. resiients add 5% sales tax
:EATURES 100% Royalty Free lurbo Pascal 4.0,5.0 Turbo C Rev. 1.5,2.0 or Microsoft C Rev. 5.x compilers ZRT Graphics Adapter Support - the graphics libraries use the graphics routines supplied with the respective compiler. (CGA, EGA, Hercules, VGA)
32
C/RCU/T CELLAR INK
Statistics - mean, mode, standard deviation, standard error, etc. Multiple Regression - With summary statistics Curve Fitting - Polynomial and cubic splines Simultaneous Equations - real and complex Fourier Analysis - Forward and inverse FFT, Rectangular, Parzen, Hanning, Welch, Hamming, and Exact Blackman Windows, 2-Dimensional FFT and Power Spectrum Matrix Math - Real and complex Complex Number Arithmetic Eigen values and vectors Integration - Simpson’s method Differential Equation - Runge-Kutta-Fehlberg Linear Programming - Simplex method Root Solving - Bisection, Newton and Brent methods Files Transfers - Lotus l-2-3 Data Smoothing Special Functions - Gamma, Beta, Bessel, error, hyperbolic trig, orthagonal polynomials RS-232 Support - the Turbo Pascal version includes an interrupt driven RS-232 driver m
3-D Plotting - translation, scaling, rotation, and perspective routines
1191 Chestnut St., Unit 2-5, Newton, MA 02164 USA Tel. (617)965-5660 FAX (617)965-7117 Circle No. 145 on Reader Service Card
programaddsrandomvaluesbetween 0 and 1 to be used as multipliers. It also assigns 1 to TRUE and -1 to FALSE. The forward activation process is shown in Table 1. The arithmetic mean of the Weighted inputs is 0.22. This average is the neuron’s output and is an analog value between -1 and +l. Note that the desired output is TRUE, so this output is positive. Had you asked for a FALSE output, the signs on the weights would be changed so that the weighted inputs and average would be negative. It’s a simple thing so far.
weights a small amount in the right direction. First you will need to calculate the input errors, which are positive for a TRUE desired output and negative for a FALSE desired output. The initial error values are shown in Table 2. Our next step is applying the “Delta Rule” which determines the amount of change we will make to the weight value. The adjustment size is: A = Step Siie x Input Error x Weighted Input Input2 Al=
0.50 x 0.75 x 0.25 = 0.09 1x1
AZ=
0.50 x 0.64 x HKl6) I -o,,2 1X1
A3=
0.50 x 0.96 x 0.04 = 0.02 1x1
Putting it to An Initial Test TheoutputneedstobelforTRUE, and instead the neuron has 0.22. You are now at the second step where you test. As you go through successive loops in the process, the initial weights which were randomly selected will be adjusted to larger and larger values. This means that the output will also become larger and approach 1. It will never quite get there, so the test needs Input 1 Input 2 Input 3 TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE
We can now adjust the weight multipliers: W, = 0.25 + 0.09 = 0.34 W, = -0.36 + (-0.12) = -0.48 w, = 0.04 + 0.02 = 0.06
Actual Output 0.85 -0.85 0.19 -0.19 0.45 0.20
The next move is to loop back to the forward activation part,using these new weight multiplier values, and calculate the next neuron output value. ADALINE’s Loops Running the actual program with these values results in nine iterations. The output values are: Iteration #
1 2 3 4 5 6 7 8 9
Wl W2 W3 Output Values 0.25 -0.36 0.04 0.22 0.34 -0.48 0.06 0.29 0.46 -0.60 0.09 0.38 0.48 0.58 -0.72 0.13 -0.57 0.70 -0.82 0.18 -0.65 0.81 -0.89 0.26 -0.73 0.88 -0.94 0.35 0.94 -0.97 0.47 -0.79 0.97 -0.98 0.59 -0.85
With the output greater than 0.80, the network is now trained with the weight values currently in place. ADALINE Pattern Comparison You can now use the trained neuron in
Digital Output TRUE FALSE indeterminate indeterminate indeterminate indeterminate
Table J-ADALINE returns a TRUE value if the input produces output within acceptable limits of the trained output. In this case, the program accepts output within 20% of the desired output.
Forward Activation mode to see the effect of various input patterns. If you go to the program and run it with some input patterns, the result might be as those shown in Table 3. You can see that inverse input patterns produce inverse outputs; the pattern it was trained on (the first) still produces the same output; and that the last two show something about the weight system that is quite inter-
Desired Output
to determine if it is within 20% of the desired value. The test is whether or not the actual output is greater than 0.80 (80% of 1). It is not, so you continue on to the third step. Note that if the output is greater than 0.80 it is TRUE,ifitisless than-O).80itisFALSE, and if it is in between it is indeterminate. This is how we digitize the “analog” output. Back Propagation-The learning Process. Now for the magic: The neuron is finally going to learn something. Back
propagation will adjust each of the
input 1 x Weight 1
input 2 x Weight 2
Input 3 x Weight 3
Figure 5-The error for each input is the dfference between the actual output and the trained output. The error for each input is processed separately. June/July 1989 33
esting. The difference between 0.97 for Wl and 0.59 for W3 means that the first and third inputs do not have the same effect on the trained neuron. Changing input 1 from TRUE to FALSE changes the actual output from 0.85 to 0.45, while changing input 3 from TRUE to FALSE changes the actual output from 0.85 to 0.20. The other inputs are not changed from the first line for this comparison. You now have a basic understanding of the ADALINE, but you’ll need to look more closely at several items, such as the delta rule, and why it is structured as it is. ADALINE’s Feedback System The error for each input is derived from subtracting the value of the individual input times its weight from the desired output value. Figure 4 shows it graphically. Your weight values are adjusted more if the error is large to speed the training process. When they are near the optimum value, the error is small. They are then adjusted in small incre-
Figure ~--AS the iteration process proceeds, the value of the multiplier increases as it moves toward the bottom of the curve. The optimum multiplier is the miflimUm value which provides an output acceptably close to the trained output. Large-value muffipliers tend to oscillate around the trained value while never coming within acceptable ,imits
’
STOCKS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .OPTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . FUTURES
Put a complete 68000 computer into your PC An exciting 68000 development platform that gets your software out! l
l
l
l
Actually runs a 68006-no simulations required to test your code. Real-time embedded multitasking applications can be developed using VRTX32 and RTscope. Familiar tools (editor, cross-assembler) can be used on the PC to write and document programs. Downloading to the system is fast: on-board monitor provides direct communication with the PC through the I/O channel.
PLUS you can develop multiprocessing techniques and programs by installing two or more boards in the PC.
Turn your PC into a
MARKET QUOTATION MONITOR New book covers complete information on financial news and market quotes for your PC from satellite and FM radio. Topics include: - Data Encryption - Password Methods - Receiver Unit Design Covers quotation processing and data broadcasting from the trading floor to the desktop, $19 plus $2 S/H (includes demo diskette).
Features of the MISTER-8 l Low cost: operates in any PC, AT, or clone. l Two or more boards can be installed to do multiprocessing. l Communicate using the PC’s serial port and your favorite modem program - or directly through the FIFO. l 128K ROM in three application sockets; 64K SRAM.
MISTER-8 with monitor EPROM . . . . . . . . . . . . , . . . . . . , . . . $495
IMmo I M*C”~ti RE%XlKES @
CALL - (303) 223-2120 (anflime)
DATArx
U
60 SOUTH EIGHTH STREET, LEWISBURG, PA 17837
Send for FREE catalog of - DATA RECEIVER KITS - QUOTE DISPLAY SOFTWARE - DESCRAMBLING UTILITIES
717-523-0777
or
717-524-7390 (recorder)
111 E. Drake Rd., Suite 7041 Fort Collins, CO 80525 Circle No. 118 on Reader Service Card
Pattern Trained on
Resulting
11111111
Output Value 0.84
Error Test Patterns 11111110 01111111 01111110
0.66 0.60 0.42
Percent Difference
Decimal
0
22 29 50
254 127 126
Table 4-A triairun ofADALINEmightproduce the resultsshown here. Youcan setthelimits of UccePtance so that any or all of the examties shown register as an acceptable input. ments to prevent the weight value fromovershootingtheoptimumvalue. You can visualize the learning process as a bowl, with the weight value changing rapidly as it comes down the side of it, then changing more slowly as it moves across the almost flat bottom of the bowl, as shown in Figure 6. Thus, the Delta Rule controls the amount of change in the weights for each iteration. It is: W new=
Wald +inaement size+ weightedinput weighted input 2
The increment size is a control on the size of each step, which affects the number of iterations needed to train your neuron. A value of 0.50 is used by this program. If it is made much smaller, it would take much more time for the neuron to train. If it is very large, training will be very rapid. However, the value found in the analog neuron simulations will oscillate back and forth around its real value andnot settleonit. Thisisparticularly true in multiple-neuron systems. The weighted input is simply the input value times its respective weight value. How ADALINE Solves the Problem You now understand how ADALINE can be used to compare each individual header byte to the value it is expecting. ADALINE will report exact matches in cases where the output values for the two bytes match perfectly. In cases where they don’t match, ADALINE will indicate how many bits are corrupted. By running the program, you can present bit patterns to ADALINE and see how much variation there is going to be for one-
and two-bit errors. The result of a trial run is shown in Table 4. Thisinformationfromrunningthe neuron can be used to devise a program which will try a strategy of accepting one bad bit in the 4-byte header coming from the radio receiver. We can accept it at any byte position by requiring that three of the four bytes have 0% error, and that the remaining byte not have more than a 35% error whencompared withitsproper value. The bit position will not significantly affect the deviation we accept. This ability to locate the header in spite of a few dropped bits allows us to locate the start 6f the data stream
and set the data pointer. The pointer can then be used to correctly pick out each data byte so it can be compared to the last two transmissions. If all three transmissions matchon this byte, we will believe its value. The end result? A mobile robot which is properly radio-linked to its host computer using low-horsepower computing engines and state-of-the-art software techniques. All in all, it’s a low-cost way toget a grip on slippery data. + Scott Farley owns Tempus Consulting, 832 Brown Thrush, Wichita, KS 67212, 316-722-3068. He has 20 years experience in appliance design, working bo th the electronicand mechanical sides. Areas in which he consults include product definition and development, product liability, code and standards, computer systems and programming, electronic and electrical hardware, instrumentation, and data acquisition.
IRS
210 Very Useful
2 11 Moderately Useful
2 12 Not Useful TM
The DA/M A Low Cost Data Acquisition System l l l
l
8-A/D Channels, O-Digital I/O Channels, l-Counter/Timer. Runs on 12 to 24 VDC. 15 Systems or 255 points per RS232iIZS485 Communications Port. Connect to Sensors that output 0-4.59V, 0-5V, 0-1OV or 4-20Ma or add optional onboard amplifiers for lower signal levels,
DA/M 100-O DA/M 100-l DA/M 100-2 DA/A4 100-3 DA/M 100-5 DA/M 100-7 DA/M 100-8 DA/M 100-9
LIIC;I~) IYU.
I
DA/M System RS232-RS485 Converter Cable ROM/RAM Piggy Back Card RS232-RS485 Converter Unit Screw Terminal Prototype Card Isolator/Relay Card Opto-22 Interface Card RAM/ROM/Real Time Clock Card
$200.00 $20.00 $50.00
$100.00 $100.00
$160.00 $140.00
$180.00
IY ori waaer wemce Lara June/July 1989
An Intelligent SCSI Data Acquisition System for the Apple Macintosh Part
by John Eng og
n the good 01’ days of personal computing, there were legen-
dary machines like the Apple II+-designed from off-the-shelf components, it had an architecture so open that you could get inside the computerwithoutusing tools. As a result, numerous plug-in peripherals became widely available for the Apple II bus, and building plug-in boards from scratch was the solution to many specific problems. For the approximate price of an early Apple II+, today’s designer can purchase a Macintosh Plus or, for a little more, a Macintosh SE. The Macintosh Plus has no slots for plugin peripherals; the SE has one slot. Neither machine can be opened without special tools. Certainly, both machines support some pretty powerful software applications, but what is a hardware designer to do? My favorite Apple II project was a plug-in board that performed &bit analog-to-digital (ADC) and digitalto-analog (DAC) conversions. With this peripheral, my Apple II could perform simple digital audio signal processing, storage,and reproduction. Given this experience with data acquisition on the Apple II, I thought it would be an interesting project to give my Macintosh Plus comparable abilities.
36
ClRCUlT CELLAR INK
A number of data acquisition products for the Macintosh have recently become available. One of the most popular is the MacRecorder, manufactured by Farallon Computing (Berkeley, CA). The MacRecorder is an audio digitizer that transmits sampled sound data through one of the Macintosh’s serial I/O ports. The maximum speed of the serial ports limits such devices to a digital resolution of 8 bits and a maximum sampling rate of 22 kHz. As demonstrated in the next section, these specifications result in a sound quality somewhat less than that of an inexpensive home stereo system. TheMacRecorder is also an input-only device, using the Macintosh’s built-in &bit audio DAC to output digitized sound samples. While devices like the MacRecorder offer an economical way to give the Macintosh decent digitization capability, I wanted to designa device with a greater digital resolution and a
1
the Ha *dwwe
faster sampling rate The result is the DAQ3000, an intelligent 12-bit data acquisition peripheral for the Macintosh Plus. The DAQ3000 is a standalone, microprocessorbased subsystem that is capable of a 2%kHz continuous sampling rate and communicates digitized data over a SCSI bus. With modifications, the DAQ3000 system can support 16bit resolution while sampling at 28 kHz. In this article, I will first explain my basic design goals and how they were implemented in the design. Then, after a more detailed description of the hardware, I will consider some future directions for the DAQ3000. Part 2 of this article will cover software design for both the DAQ3000 and the Macintosh host.
Because my old Apple II data acquisition peripheral was used almost exclusively for audio signal processing, I wanted to optimize my new Macintosh project specifically for audio signals. I also wanted my new project to have genuine audio fidelity, similar to that of an inexpensive stereo tape deck, which may have a frequency response of up to 12-14 kHz and a signal-to-noise ratio (SNR) of 60-70 dB. These two specifications parallel the two main characteristics
of any digital data acquisition system: conversion speed and digital resolution. According to the Nyquist sampling theorem, accurate digitization of a 12-14-kHz signal requires a sampling rate of twice that frequency, or 24-28 kHz. This sampling rate corresponds to an ADC conversion time of no more than 35-40 I_LS. With regard to the required SNR, we should choose an ADC with at least 12 bits of digital resolution, giving an output voltage resolution of approximately 1 part in 4096 and a corresponding SNR of 72 dB (SNR = 1010g,,[V2s,gna,/V2n~~l dB). By comparison, an &bit ADC would only provide a SNR of 48 dB. Twelve-bit data conversion creates rather strict requirements on the acceptable system error or noise. For example, to achieve the resolution of 1 part in 4096 for a typical 12-bit ADC voltage range of 10 V (*5 VI, the total system error and noise should not be greater than 1.2 mV. A sample-and-
hold(SAH)deviceiscertainlyrequired herebecauseevenwithaperfectaudio system, a potentially important source of error originates from any significant change in the input signal during the ADC’s conversion period. In the worstcaseof the 12_bitexampleabove, the audio input signal to the ADC should not vary more than 1.2 mV over the entire conversion period of 35-40 p.s. This requirement would severely limit the signal frequencies accurately measurable by the ADC without a SAH.
TheDAQ3OOO’sanalogcircuitsare based on three Harris devices. The HI-574A is a 12-bit ADC with a maximum conversion time of 25 us, giving a maximum possible sampling rate of 40 kI-Iz. The HI-5680V is a 1Zbit DAC with a maximum settling time of 1.5 p.s. The HA-5320 is a SAH chip with a
maximum voltage droop of 0.5 ~~V/JIS in the hold mode. Over the 25-us conversion time of the 574A ADC, the maximum total voltage droop of the 5320 SAH is 12.5 uV, which is well within the 1.2-mV requirement. With the exception of hard disk drives, most currently available Macintosh peripherals communicate data through one of the Macintosh’s two RS-422 serial ports. These serial ports allow a maximum 8-bit transfer rate of about 22 kHz, which is much slower than the 56kHz transfer rate needed by the DAQ3000 (28-kHz sampling rate x 2 bytes per 1Zbit sample). To accomplish the highspeed data transfer, the DAQ3OOOcommunicates instead through the SCSI bus port available on the Macintosh Plus and later models. SCSI stands for Small Computer System Interface, a standard parallel interface for high-speed intelligent peripherals such as hard disks and
+5
; powe,.
1 UCC 1 GND ;
: i
1
LIISSS
.
8
.
1
I
j
I
60 Al f92 A3 A4 A5 R6 A7
I
WCI
R/W\. /
6502 fi A8 F19 610 R/B Phase 2 out All A12 F113
T
74LS138 Y7 7 A Y6 9 6 Yso10 Y4311 y3 f$
SEL7\ ($3800) ROl’l, I _, SEL6\ ($3000) SEL5\ (EZ8@0)SCSX, , SEL4\ ($2000) D A C , sEhz\ (01800) ADC,/ t51000) I/O_/ / /
OSCILLATOR
lure 1 --The main processor section of the DAQm includes a 65U2A microprocessor and chip selects that break up the 64K address lace into eight sections.
June/July 1989 37
THE INTERCHANGE” Bi-directional DataMigration Facility for IBM PS/2, AT, PC, PORTABLE and Compatiblea
*Parallel port to parallel port. *Economical method of file transfer. *Bi-Directional file transfer easily achieved. *Supports all PS/2 systems (Models 30, 50, 60, and 80). *Supports IBM PC, XT, AT, Portable and 100% compatibles. *Supports 3 I/2 inch and 5 l/4 inch disk tranefem. ‘Supports hard disk transfers. *Supports RAMdisk file transfers. *The SMT 3 Year Warranty.
ONLY $39.95
FastTrap’”
The pointing device of here!
streaming tape drives. The SCSI standard was developed by the American National Standards Institute (ANSI) and includes standard protocols allowing asynchronous data transfers atgreater than 1 Mbyte/s over adaisychained bus. The DAQ3000 uses the NCR 5380 SCSI controller, the same SCSI chip used in the Macintosh. On With the Design UseofSCSIprotocolsrequiresthat the DAQ3000 be “intelligent.” As a result, the DAQ3000 was designed as a stand-alone microcomputer subsystem. At the system’s center is a 6502A microprocessor, running at 2 MHz, surrounded by bus drivers and address decoding logic (Figure 1). A 74LS245 bidirectionally buffers the data lines; the 6502’s address and bus control lines are buffered by 74LS244s.
The 6502’s address space is divided into eight 2K-byte areas, six of which are used by the system: RAM, System I/O, ADC, DAC, SCSI, and ROM. Because the most-significant two address bits of the 6502 are not used, the eight 2K-byte areas repeat themselves four times in the 64K-byte total address space of the 6502. This partial address decoding scheme was chosen to minimize the chip count. Address decoding is done by a 74LS138, which generates a selection signal (SELn\) corresponding to each address area. The RAM and ROM (Figure 2), and System I/O (Figure 3) sections are each designed around one major chip. The 6116P-2 2K-byte static RAM must be configured as address area 0 because the first 512 bytes of the 6502’s address space must be present for the zero-page addressing mode and the system stack. The 2816A-25 2K-byte
the future is TA BUS DPFSS BUS
*Two and three axis pointing capability. *High resolution trackball for X and Y axis input. *High resolution fmgerwheel for Z axis input. *Use with IBM@PC’s, XT’r, AT’r and compatibles. *Three input buttons. *Full hardware emulation of Microsoft @ Mouse. *Standard RS-232 serial interface. *Include6 graphics drivers and menu generator. *Easy installation. *l year warranty. *Made in U.S.A.
Figure 2-The 2K bytes of static RAM provide plenty of temporary storage and 2K bytes of EPROM make program development easier.
ONLY $149.00 LTS/C Corp. 167 North Limestone
Street Lexington, Kentucky 40507 Tel: (606) 233-4156 Orders (800) 872-7279 Data (606)252-8968 [S/12/2400 8-N-11 VISA, Mastercard, Discover Card, TeleCheck
Circle No. 132 on Reader Service Card
38
C/RCU/T c~uv? INK
tigure J-A om2 I perlpnerallnrerrace aaapterproviaes me necessary LEDs and to check the status of the analog-to-digital converter. C.
_
.
,^^^.
.
.
,.
_
.
,.
Dlrs .
To cfrwe eight
C o n n e c t each of t h e POWC~ supplv ~lno t o ground t h r o u g h one 0.luF c e r a m i c a n d one 4.7~1F t a n t a l u m CaPacitor
4 A0 int I,J,K,L,M,N,O,P; int bO,bl,b2,b3,b4,b5,b6,b7; int ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int iter; main0 int kO,kl,k2,k3,k4,k5,k6,kl; /* Preset CRC to all ones - CCITT rules */
/* Compute a number of CRCs with input data of all zeroes */ bO=bl=b2=b3=b4-b5-b6=b7=0; for(iterO; iter(l0; ++iter)crc(); /* Now feed ones complement of the CRC back into calculation; result should be FOB8 */ bO-!aO; bl-!al; b2=!a2; b3-!a3; b4-!a4; b5-!a5; b6=!a6; b7=!a7; kO=!a8; kl-!a9; k2-!alO; k3-!all; k4=-!a12; k5-!a13; k6-!a14; k7-!a15: crc(1: bO=kO; bl=kl; b2-k2: &k3; b4-k4; b5=k5; b6=k6; b7=k7; crc0; 1 /* Remember the following C language operators: & = bitwise "and"; ! = negation; 1 = bitwise "or" */ crc()
I
I=(b3 6 !a3) I (!b3 & a3); J=(b2 6r !a2) 1 (!b2 & a2); K=(bl & !a11 I (!bl & al); LE.(bO & !aO) I (!bO & a0); M= ( b7 & !a7 & !I) I (!b7 & !a7 & I) I (!b7 & a7 & !I) I ( b7 & a7 & I); N= ( b6 & !a6 & !J) I (!b6 & !a6 & J) I (!b6 h a6 h !J) I ( b6 & a6 & J); O- ( b5 & !a5 & !K) I (!b5 & !a5 h K) I (!b5 & a5 & !K) I ( b5 & a5 & K); P- ( b4 & !a4 & !L) ) (!b4 & !a4 & L) 1 (!b4 & a4 & !L) I ( b4 & a4 & L); a7-(a15 6 !P) I (!a15 & P); a6=(a14 & !I) I (!a14 & I); a5=(a13 6 !J) I (!a13 & J); a4=(a12 6 !K) I (!a12 & K); a3=( all & !L & !M) I (!a11 & !L h M) 1 (!a11 & L & !M) I ( all h L & M); a2=(alO & !N) I (!a10 C N); al-(a9 & !O) I (!a9 & 0); aO-(a8 & !P) I (!a8 & P); a15-M; a14-N; a13-0; a12=P; all-I; alO=(J & !M) I (!J & M); a9- (K & !N) I (!K & N); a8= (L & !O) I (!L & 0); printf("\nCRC== %X%X%X%X %x%x%x%x %X%X%X%X %x%x%x%x", ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ al,aO);
listing 1 -Program to compute CRC in parallel.
56
CIRCUIT CELLAR INK
CRC calculation. Why go through all of this grief for so little reward? If you don’t want to develop a new circuit, the answer is simple: Cumbersome though it is, the parallel CRC program works. If you don’t mind adding a little bit of new silicon to your design, though, you can make the solution much simpler and cleaner. The form of the C program closely resembles that of the equationsneeded to define a Programmable Logic Device PLD). In other words, there is a very close equivalence between the code and a hardware implementation of thealgorithm. Fortunately, thePLD version can operate in a single clock cycle, and is much more aesthetically appealing than its awkward software cousin. The PLD
For the uninitiated, a PLD is a sort of “super PAL.” Based on EPROM technology, the PLD is a device that can be programmed with a user’s equations. Like an EPROM, a fairly simple device programmer is used to load the formulas. PLDs are defined in terms of “macrocells.” Every macrocell is a multiple-input OR gate optionally connected to a flip-flop. Each of the OR gate inputs is an extremely wide AND gate; any or all of the PLD pins [and their inversions) can be connected :o the AND gates. You can specify the type of flipflop; typically D, T, JK, and SR versions are all available. Or, you can disable the register altogether, so the macrocell becomes a big combinatorial gate structure. A PLD is therefore a very large :ollection of AND and OR gates with some internal registers also thrownin. The connection of these components s up to the user; you write a set of >oolean equations that makes the PLD mplement the circuit you need. Intel’s 5CO90 (equivalent to Alera’s EP900) is a 40-pin PLD with 24 nacrocells. It contains enough logic o completely implement the CRC algorithm in parallel. The rest of this rticle will be based on programming he 5CO90.
EPLD: 5CO90 Comments: This file computes a CCITT-SDLC CRC in parallel OPTIONS: TURBO=ON PART: 5CO90 INPUTS: b0@2,bl@3,b2@4,b3@17,b4@18,b5@19,b6@22,b7@23,preset@38, hicrc@37,locrc@24,clkl@l,clk2@21 OUTPUTS:aO@5,al@7,a2@9,a3@ll,a4@13,a5@15,a6@25,a7@27, NETWORK: bO=INP(bO) bl=INP(bl) b2=INP(b2) b3=INP(b3) b4=INP(b4) bS=INP(bS) b6=INP(b6) b7=INP(b7) preset=INP(preset) losel=INP(locrc) hisel-INP(hicrc) clkl-INP(clk1) clk2=INP(clk2) aO,aO=RORF(aOd,clkl,gnd,gnd,lo) al,al=RORF(ald,clkl,gnd,gnd,lo) a2,a2=RORF(a2d,clkl,gnd,gnd,lo) a3,a3=RORF(a3d,clkl,gnd,gnd,lo) a4,a4=RORF(a4d,clkl,gnd,gnd,lo) a5,a5=RORF(a5d,clkl,gnd,gnd,lo) a6,aC=RORF(a6d,clk2,gnd,gnd,lo) a7,a7=RORF(a7d,clk2,gnd,gnd,lo) a8,aS=RORF(a8d,clkl,gnd,gnd,hi) a9,a9=RORF(a9d,clkl,gnd,gnd,hi) a10,alO=RORF(alOd,clkl,gnd,gnd,hi) all,all=ROR3?(alld,clkl,gnd,gnd,hi) a12,al2=RORF(a12d,clkl,gnd,gnd,hi) a13,al3=RORF(a13d,clkl,gnd,gnd,hi) a14,al4=RORF(a14d,clk2,gnd,gnd,hi) a15,al5=RORF(a15d,clk2,gnd,gnd,hi) L,L=COIF(Ld,) K,K-COIF(Kd,) J,J=COIF(Jd,) I,I=COIF(Id,) P,P-COIF(Pd,) O,O=COIF(Od,) N,N=COIF(Nd,) M,M=COIF(Md,) EQUATIONS: lo=/losel; hi=/hisel; Id=(b3 * /a3) + (/b3 * a3); Jd=(b2 * /a2) t (/b2 * a2); Kd=(bl * /al) t (/bl * al); Ld=(bO * /aO) t (/bO * a0); Md=( b7 * /a7 * /I) + (/b7 * /a7 * I) t (/b7 * a7 * /I) t ( b7 * a7 * I); Nd=( b6 * /a6 * /J) + (/b6 * /a6 * J) t (/b6 * a6 * /J) t ( b6 * a6 * J); Cd=(b5*/aS*/K)t(/b5*/a5* K) t (/b5 * a5 * /K) t ( b5 * a5 * K); Pd*( b4 * /a4 * /L) t (/b4 * /a4 * L) t (/b4 * a4 * /L) + ( b4 * a4 * L); a7d=(a15 * /P) t (/a15 * P) + /preset; a6d=(a14 * /I) t (/a14 * I) t /preset; LiSting
2- PLD source file for a parallel CRC.
58
CIRCUIT CELLAR INK
Putting the CRC in a PLD Examining the C program, it quickly becomes apparent that the intermediate I through P terms must be computed before any of the a045 outputs, but once&P are known, then all 16aO-u15 termscould becomputed simultaneously. We should therefore assign the I-P terms to combinatorial outputs in the PLD. The a0 to a75 terms (the CRC itself) are assigned to registered outputs. In this case the current CRC is needed as part of the new one; therefore the flip-flops’ outputs will be fed back into the equation matrix. It’s relatively easy to translate the Turbo-C program into PLDequations. This was my intention when writing the code; the real purpose of the C program is to provide a simulation of the CRC function as implemented in a PLD. Listing 2 shows the file that defines the PLD. For those unfamiliar with PLD design, the NETWORK section of the PLD file defines the nature of each of the device’s pins. bO to b7 are input bits. I to P are combinatorial outputs. The a0 to a25 (CRC) terms are defined as RORF (Registered Output, Registered Feedback). The termsarelatched in D flip-flops, but the current value @eforethedeviceisclocked)goesback into the equation matrix. Figure 1 shows the connection of the PLD to a computer’s data bus. Most data communication processors manipulate &bit data, so an &bit data bus is shown. The input data is a byte, but the output CRC is 16 bits. This PLDis designed to let usmultiplex the CRC onto the bus as two individual bytes. The input bits come from the same data bus. bo is thus tied to uOand ~8, bZ to al and u9, etc. LOCRC and HICRC are used to dump the upper or lower CRC byte onto the bus. Once the calculation is complete, the processor asserts these inputs low (one at a time) and reads the two bytes. These inputs are typically connected as input port selects. The PRESET input initializes the CRC before any data is transferred. The CCIIT specification requires that the CRC be initialized to all ones.
asaquickwayofverifyingdataagainst a previously computed CRC during read of a device. Be sure to transfer the low part of the CRC first, and then the high byte when making this test.
a5d=(a13 * /J) + (/a13 * J) + /preset; aad;=@ * /K) + (/a12 * K) + /preset; a3d=( all * /L * /M) + (/all * /L * M)
t (/all * L * /M) t ( all * L * M) t /preset;
a2d=(alO * IN) + (/al0 * N) + /preset; aId=(a9 * 10) + (/a9 * o) + /preset;
Software or Hardware?
aOd=WJ * /P) t (/a8 * P) t /preset;
al5d=M al4d=N a13d=O alZd=P alld-I
t + t + t alOd=( J
/preset; /preset; /preset; /preset; /preset;
* /M) + (/J * M) t /preset; a9dS W * /N) + (/K * N) t /preset; a&b= (L * /O) + (fL * 0) t /preset;
listing
2-_(continuec$
Input data preset 0 0 0 0 0 77 CF
Output CRC FFFF OF87 FOB8 3933 0321 3088 OF48 FOB8
The PLD computes a CRC in parallel using a single IC package. It can support a data rate of at least 10 MHz, even when used with relatively slow devices. Although the equations are messy and tedious, you can use the ones presented here as a “cookbook” solution. Of course, the C version will work in those situations where you simply cannot afford to add hardware to the design. Either way, the parallel CRC lets you be sure that your parallel data is transferring safely. + Jack Ganssle is the president of Softaid, a vendor of microprocessor development took When not busy pushing electrons around, he sails up and down the East Coast on his 35-foof sloop.
IRS 222 Very Useful 223 Moderately Useful 224 Not Useful
Figure
I-A 5CooO PLD makesimplement&ion of parallel CRCs in harabare easy.
Figure P-Giventhesamp/edatainthele# column, the expected CRCs are listed in the right column.
When asserted, PRESET loads a 1 into all of the a045 terms after the next clock cycle. Be warned! Your interface circuit must assert CLOCK when PRESET is low. Remeber that CLOCK is highedge triggered. To use the programmed PLD, first initialize the CRC by asserting PRESET low and driving CLOCK high. Then transfer data one byte at a time. For each byte, drive CLOCK high once the input data is stable, and after the data has been present long enough to let the I to P terms propagate (typically 100 ns). The PLD computes a new value for the CRC and loads it in thea registers when CLOCKgoes high. After a block is transferred, the
CRC is ready to be read by the computer. The CRC PLD uses a pretty complex series of equations. How can you be sure the circuit works correctly? One way is to compare the CRC to known good values after specific data is transferred. Figure 2 shows CRC values for an input data stream of successive zeros. You can check the CRC after each clockagainst this table. The CCITT polynomial has a selfchecking feature. Once a stream of data has gone through the CRC calculator, you can supply the one’s complement of the resulting CRC to the PLD and always get FOB8 as the new value. Always. This serves as a sanity check when developing hardware,and
Data communications progress was slow before the invention of wire.
June/July 1989 59
FIRMWARE FU From Fixed Point to Floating Point and Back Again Writhing Reals
by Ed Nisley
R
eal numbers seem to be a hot spot among you folks. Several readers asked for more details on converting between floating-point and fixedpoint numbers, because they‘re planning to use real numbers of one shape or another in their projects. All this started with the Mandelbrot Engine described in “Ciarcia’s Circuit Cellar” in the October, November, and December 1988 issues of BYTE. The Engine is an array of Intel 8751 single-chip microcontrollers programmed to execute the Mandelbrot Setalgorithminparallel. Wedesigned it to demonstrate the advantages of using many cheap processors to solve a problemusuallyassociated with big, fast, expensive machines. A control program called DRIVER runsonanIBMPC/ATclonetohandle keyboard inputs, distribute initial conditions to the array, and display the results on an EGA monitor. I used a special fixed-point numeric format because the Mandelbrot Set calculationsrequire exquisite precision, while 8751 processors aren’t well-suited for floating-point arithmetic. We didn’t need fixed-point numbers in DRIVER 'S calculations, however, because the increased precision is required only in the Mandelbrot algorithm’s inner loop. DRIVER uses ordinary C “double” variables and converts the values to fixed point before sending them to the arrayprocessors. At the risk of digressing into software, this column will explore how that conversion works and provide a pair of routines to convert decimal fractions to binary fixed-point numbers. Because DRIVER works with 60
ClRCUlT CELLAR INK
ordinary double-precision floatingpoint numbers, I’ll start by reviewing that format. Double Dealing Figure 1 shows the double-precision binary floating-point numeric format defined by the IEEE and used in 80x87 numeric coprocessors. Al-
baggage to indicate we are working in base 10. The trick behind scientific notation is to convert all numbers, regardless of size, to something you can count on your fingers.. .the mantissa must be between 1 and lo! While scientific notation is useful for those of us with 10 digits, computers have only two: zero and one. The first step in representing 186,000 as a
I-* Eight Bytes = 64 Bits seeeeeee
eeeemmmm
mmmmmmmm
mmmmmmmm
exponent- 11 bits Figure 1 -This is the double-precision floating-poinf format defined by the IEEE. The range ofthe format is+ 1.7x Wo8. The precision is IS- 16 decimal digits with the exponent biased by + 1023 (03FF hex). The mantissa of this format has an implied high-order . I ’ bit, and all negative numbers are represented in signed-magnitude notation.
though there are other types of floating-point numbers around, nearly all contemporary PC languages support 80x87 operations. The examples here are in Microsoft C 5.1, but the bits, bytes, and algorithms can be adapted directly to your favorite language. Each floating-point number has three fields distributed over eight bytes, as shown in Figure 1. It’s easier to understand the fields by comparing them with a format that you are more familiar with: the scientific notation used to denote very large or very small physical quantities. For example, the speed of light is about 186,000 miles per second, which is 1.86 x 105 miles/second in scientific notation. For this number, the sign is positive, the mantissa is 1.86, and the exponent is 5. The “x 10” is standard
binary floating-point number is a conversion to base two: 2D690 hex, or 0010 11010110 10010000 binary. You can imagine a “binary point” after the last bit on the right. By definition, the mantissa of a binary floating-point number is greater than or equal to 1.0 and less than 2.0 (decimal), so it must have a “1” bit just to the left of the binary point. The number of places you shift the binary point to get a suitable mantissa determines the value of the exponent. This process is called “normalization.” Then, rather than waste storage on that high-order “l”,bit, it is simply omitted. There are some cases where the range of the exponent won’t allow normalization to be done, but I’m going to ignore those issues here. The final result is a 52-bit binary value
ne
LWaa Y L
L
77
1I r
I
I?e
0 l
The Circuit Cellar SB180 Single-Board Computer Kit
Since the time it was introduced on the cover of the September ‘85 issue of BYTE, the SB180 has established itself as one of the most reliable and costeffective single-board 8-bit computer sysn the market. lncorooratina UD to 256K RAM, an 8K EPROM monitor, a floppy disk controller, two serial ports, and a parallel printer port, the SB180 has a remarkable list of features for its small 4” x 7.5”size. An optional SCSI interface adapter easily expands the SBI 80 to include a hard disk. Using the Z80-code-compatible Z180/HD64180 super chip, the SBI 80 runs the thousands of 280/8080/8085 programs faster and more efficiently than ever before. Up to three times as fast as a ~-MHZ Z80, the g-MHz SB180 can be used as a stand-alone controller, or as a complete development system running CP/M 2.2, CP/fvl Plus, Z-System, MP/M II, TurboDOS, or Oasis operating systems. The SB180 comes with a plug-and-go 24command high-performance ROM monitor which exercises and tests all its basic functions. For real computing performance, we have an extensive software collection including the Z-System enhanced disk operating system. Considerably more advanced than CP/M, ZSystem offers users utility programs and DOS features that have only recently become common to 16-bii PC users. Through a special licensing arrangement, Circuit Cellar is now able to offer a complete g-MHz SB180 kit (less DRAM) for the remarkable price of $195. Just add a bank of 64K or 256K DRAM S and you are instantly on the air. The optional Z-System O/S software has also been redesigned with computer experimenters in mind. Theoperating system checks available memory, apportioning it between TPA and RAM disk, and looks for the SCSI hard disk as well. Adding a 32-Mbyte hard disk is as easy as plugging on the SCSI adapter to what you already have running-no merging or recompiling software. Complete source code for the BIOS and ROM monitor are also included. Plug and go!
Binary
Fraction
JIecimal
0.10000
l/2
0.50000
0.01000
l/4
0.00100 0.00010
l/8 l/16
0.25000 0.12500 0.06250
0.00001
l/32
0.03125
0.11000 0.10100
l/2 + l/4
0.75000
l/2 + l/8
0.62500
Table 1 -The binary, fractional, and decimal equivalents for some common values. As with integers, the weights for each ‘I’ bit may be added to get a corresponding decimal value.
Incidentally, this conversion will fail if the floating-point number is already denormalized. In principle, this “can’t happen here” because the normal 80x87 settings force zero for values that would ordinarily underflow, but it is worth worrying about for mission-critical code.. . With the mantissa in place, the code simply shifts it left or right as dictated by the exponent. The rather complex code in the shifting loops shows what you must go through to makeaone-bit shiftacrossamultibyte quantity. The mantissa uses signed-magnitude notation, so the code converts it to two’s complement if the sign bit is one. The two notations use the same representation for positive numbers, so no change is needed in that case. The final step is to copy the first eight bytes from the work buffer into the result variable. The bytes left behind may also have bits from the floating-point number, but those bits are lost forever because there is no room
Features;
-9.21~MHz 216O/HD64180 CPU 64K or 256K bytes RAM supported - 8K monitor and boot ROM - Measures 4” x 7.5 with mounting holes l
* Floppy controller (1-4 drives, 3.5” or 5.25”, single/double density, single/double sided, 40/80 tracks) * One Centronics parallel printer port * Two RS-232C serial ports (75-19200 bps)
SBl WK-I : 9.216-MHz SB180 single-board computer kit. Includes all components except DRAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $195.00 SB180K-I-20: Same as above with Z-System hardAloppy disk operating system; BIOS and ROM sources) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . $295.00 .. COMMl80K-S: SCSI hard disk adapter board for SB180 . . . . . . . . . . . . . . . . . . . . . . $89.00
Available from: CC1 l 4 Park St. l Vernon, CT 06066 For information and orders: (203) 875-2751 l Fax: (203) 872-2204 All payments should be made in U.S. dollars by check or money order. MasterCard. or Visa. Shipping and handling: surface delivery add $31~ U.S.; Pndday delivery add $7 for U.S. Call for Canada and air freight delivery ekewhere. .-_.__I_ .I_ .1- ..__,:__ p_ urcle N O. I iu on i<eaaer *IVILW L,U
62
ClRCUlT CELLAR INK
Iecimal
Binarv
0.0100
o.OaH 1001100110011OfJ1... o.OaJO 0010 1000 11110101 . . .
0.0010
o.OOOo OCOO 0100 UOOl loo0 . . .
0.0001
0.0000OOfN000001101ooo...
0.1000
0.5000
o.1oooOOxOOOOOOOoOcOO...
0.2500
0.0100 0000 0000 oooo OOCKI
0.2ooo
0.00110011 al11 00110011 . . . 0.000111000010 1000 1111 . . .
0.1100
..,
Table 2-Binary equivalents of ‘simple’ decimal fractions. The binary fractions do not terminate.
in the floating-point format for them. Recall that the tradeoff was higher precision over a smaller dynamic range and you’ll see why this must be so. Conversions from fixed point to floating point are handled by the code in Listing 2. The process runs more or less in reverse from the previous routine: copy to the buffer, convert to signed-magnitude, shift to normalize, suppress the leading bit, copy the fraction to the mantissa, and set all the fields appropriately. If there were more fractional bits than fit into the mantissa (which is quite likely) they are simply discarded. A Blizzard of Bits
Those two conversion routines suffice to convert between doubles and fixed-point numbers. You may have an application where the decimal number exists only as a text string; for example, a keyboard input specifying a servo table position. Converting the ASCII text to a decimal fraction, then to a binary floating-point number, then to binary fixed-point number may lose more bits than you care to discard. In that case a direct conversion to fixed point is in order. Because the decimal number existsasASCI1 text thereisnobitpattern we can copy directly into the fixedpoint number. However, by treating each character of the string as a numeric digit you can extract as many bits as you need with no errors at all. The trick involves mechanizing the method you would use if you were forced to convert the number by hand (you could convert it by hand, right?). In effect, we treat the string as a binary-coded-decimal (BCD) number with each ASCII character as a digit. Figure 4 shows how this works. Each multiplication by two cooks a single bit out of the value; if the decimal product exceeds one, the corresponding binary bit is one. The multiplications must be performed on a decimal number using decimal arithmetic because the number may not have an exact binary equivalent: that’s the whole reason for this using method!
*/
/*- galactic constants #define NDMLEN 8 #define DBLPREC 16 /* /* /* /* /* /* /* /* /* /* /*
*/ /* bytes per extended precision num /* total significant digits in double */
*/ Extended precision numbers look like this: */ +OOO.OOOOlOOOOOOOO~NUMLEN-3 bytes~00000000 6 A */ binary point "1 I */ sign bit */ Negative numbers are in two's complement form The overall length is 64 bits, of which 60 are fractional Overflow occurs for positive nums >7.999 & negative 2) ( msmset(ExtAccum,'\xff',NUMGSN-1); /* force to max value ExtAccum[NUMLEN-l] = Ox3f; /* and do no shifting expshift = 0; 1 else { /* fill unused bits EZxtAccum[O] = 0; memcpy@xtAccumtl,d.bits.mantissa,6); /* trans low mant. ExtAccum[NUMLEN-11 = (unsigned char) d.bits.highmant; /* add implied ‘1" bit E%Accum[NUMLEN-l] I= 0x10; 1
*/ */ */ */ */ */
listing 1 -A program to convert Tom floating point to fixedpoint begins by denormalizing
the mantissa until the exponent is zero. Performing one-bit shifts across multiple bytes requires the complex loop shown here. June/July 1989
63
while (expehift > 0) ( /* handle left shifts */ saccum = 0; for (index = 0;index < NUMUN; index++) ( accum = (unsigned int) ExtAccum[index]; accum = (accum > a: 1 expshift--; I while (expshift < 0) { /* handle right shifts */ saccum = 0; for (index = NUMLEN-1; index > -1; index--) ( accum = (unsigned int) EktAccum[index]; accum = rotr( (accum I saccum),l); EZxtAccum&ndex] = (unsigned char) accum; saccum = (0x8000 & accum) >> 7; 1 expshifttt; if (d.bits.signbit) { NegExt (ExtAccumWUMMN,ExtAccum); /* compl. & set retn */ memcpy(extval,ExtAccumeNUMIEN,NUMLEN); ] else { /* just set retn val */ ~cpy (extval,ExtAccum,NUMLEN); I
I
I
return: f
listing
I --(continued)
Theonlyarithmeticoperationyou must perform on the string is a multiplicationby two, or, alternatively, add the number to itself. There may be a carry from the preceding digit position and the operation may produce a carry for the next position as well. Listing 3 illustrates one way to double an ASCII fraction without intricate program logic. A loop examines each character in the string right to left. At each character the code isolates the low-order four bits and adds 0x10 if there was a carry from the previous character. The result becomes an index into the Dvalue and Dcarryarrays,whichprovidethenew result digit and the carry for the next position. The ASCII string is updated in place so it is ready for the next pass. The arrays have 32 elements, of which only 20 are used. I could have used 20-element arrays, but wasting a little space made debugging easier by separating the effect of the digits and carries on the array index. The return value is simply the carry from the high-order (leftmost)
MICROMINT I After years of experience in manufacturing OEM controller boards and talking to customers, we think we have hit upon just the right combination of format and function to satisfy even the toughest case of “relay mentality.” R e a l i z i n g t h a t n o t warrantsaCrayX/MP, Micromint offers atiny8031/8052based controller board for those dedicated and cost-sensitive installations.
RTC31 and RTC52 Technical Specifications +3031 processor (RTC31) or Micromint 8OC52SASIC processor (RTC52) -11 .05-t&+2 system clock muses 8K or 32K memory chips *Up to 64K bytes of RAM or EPROM .5-volt-only operation ~11 o-1 9200 bps RS-232 and/or RS-485 serial port -Use stand-alone or networked 012 bit of parallel f/O *Vertical-stacking expansion bus Screw terminal connections Small 3JYx3.5” format -80 mA typical operating current
RTCIO Technical -Three bidirectional parallel ports &channel, b-bit A/D (0-5V); 9,000 sampleslsec +channel, &bit D/A (0-W); 2-ps response time Battery-backed clock/calendar and presettable time-interrupted capability *DC To DC conversion-5-volt-only Screw terminal connections Small 3.5”x3.5” format FfTCIO RTCIO board with paral!el I/O and AU converter ITTCIO OEM tOO&srttity Price
4 Park Street, Vernon, Connecticut 06066 Tel: (203) 87145170 l Fax: (203) 872-2204 Circle No. 139 on Reader Service Card 64
ClRCUlT CELLAR INK
XKXIT CELLAR INK’S
ADVERTISER’S INDEX Reader Service Number
Advertiser
Page Number
102 101
AlSl 2500Research AD Software
:
104 103 105 106 107 108
; 39 49
109 110 111 112 113 114 117 118 119 120 121
AVOCET Alpha Products B8B Electronics Berry Computers Binary Technologies Cabbage Cases Chrysalis Ciarcia Design Works Circuit Cellar Circuit Cellar Circuit Cellar Computerwise Contact East Cottage Resources Covox, Inc. DATArx Dycor Eng. Collaborative Environmental Optics
123 122 124 125 126
Galacticomm Express Circuits Grammar Engine GTEK, Inc. Hazelwood Computer
c63 54 7 68
128 127 129 130 115/116 .
Hogware Heath Co. lnnotec Intro1 Corp. tt! Micpsystems
;; 15 29 23
131 132 133 134 135 136 137 138 139 140 141
Logical Systems LTS/C Corp. Meredith Industries MetraByte Micro Resources Micromint Micromint Micromint Micromint Ming Eng. NOHAU Corp.
:“7 38 79 15 34 73
143 142 144 145 146 147
Programmer’s Shop Paradigm Systems PseudoCode Quinn-Curtis R&D Electronics Softaid Systronix Thinking Tools Timeline Tinney x-10
:: 51 32 68 71 79 7 4 54 9
t
l
t
148 149
.
150
/* Convert an extended fixed-point value to double floating /* Returns the double value. Some bits will get dropped. double CvtExt2Dbl(EXTNUM extval) { int index: int expshift; unsigned int accum; unsigned int saccum; DOUEGEJXTS d;
/* clear the decks memset(&d.dbl,'\O',NUMLEN); */ */ if (extval[NUMLEN-l] & 0x80) { /* get positive in act. d.bits.signbit = 1; NegExt(ExtAccum,extval); ) else { memcpy(ExtAccum,extval,NUMLEN); ] accum = 0; */ /* if zero, we're done! for (index = 0; index < NUMLEN; index++) { accum I= ExtAccum[index]; ) if (accum != 0) { expshift = 0; /* normalize first 1 bit lot*/ while (ExtAccum[NUMI.EN-11 & OxEO) ( /* right shift norm */ saccum = 0; for (index = NUMLZN-1; index > -1; index-) ( accum = (unsigned int) ExtAccum[index]; accum = rotr((accum I saccum), 1); ExtAccumTindex] = (unsigned char) accum; saccum = (Ox8000 & accum) >> 7; ) expshifttt; ) while (!(ExtAccum[NUMLEN-1] & 0x10)) ( /* lft shift norm*/ saccum = 0; for (index = 0;index < NWLEN; index++) { accum = (unsigned int) ExtAccum[index]; accum = (accum > 8; 1 expshift-; 1 d.bits.exponent-expshift + 1023; /* get excess 1023 exp */ d.bits.highnant=OxOOOf&(unsigned int) RxtAccum[NUMIZN-11; memcpy(d.bits.mantissa,ExtAccum+l,6); /*xfer useful bits*/ ] return d.dbl;
z 79 79 17 62 17 47 ;: 73 34 35 46 70
z: 64 76 66
IRS
NK Rating Service
iow useful is this article? 4t the end of each article and ;ome features there are three 3Jigit numbers by which you can ate the article or feature. Tease take the time to let us, at Circuit Cellar INK, know how you eel our material rates with you. lust circle the numbers on the Ittached card.
*/ */
1 Listing 2-Converting from fixedpoint to floatingpoinfis roughly the reverse of the process shown in Listing 1. Excess fractional bits in the mantissa are simply discarded by this program. I
Decimal
x2
0.54321 00 .. 01 87 62 48 24
1.08642 0.17284 0.34568
0.34568 0 .. 7 36 85 24 74 2 0
0.69136
0.69136 1.38272 0.76544 1.53088
0.53088 0.06176 0.12352
1.06176 0.12352 0.24704
Figure 4-Converting an ASCII representat/on to u numeric format requires treating the string as a binary-coded decimal (BCD) number where each ASCII character is a single digit.
I,,,,,,,," 0.10000101100 binary June/July 1989
65
character which would become the integer part of the number if you were doing this by hand. Because the string does not include the integer position, it does not need to be modified for the next pass. The program CONVDEC illustrates how to use this routine. Simply type "CONVDEC 0 . 1” to get the 60-bit binary equivalent of 0.1 decimal. CONVDEC is limited to positive values between 0.0 and 7.9999... because I didn’t want to implement negation and general integer conversions for ASCII strings.
/* The original dec. number is stored as ASCII text string as */ /* +d.dddddddd...ddddd */ up to 60 fractional digits /* III */ /* ((actual decimal point (Ox2e) */ /* linteger part of number (less than 8) */ /* sign (+ is Ox2b, - is Ox2d) */ /* */ /* Double the decimal value represented in the ASCII string */ /* Returns ‘carry" from highest character (either 0 or 1) */ /* The string must not contain anything other than dec. digits*/ /" (so strip out things like decimal points and signs first) */ int TimesTwo(char *Value,int NumDigits) { static char *Dvalue = "0246802468......" "1357913579......"; static int Dcarry[32] = (00,00,00,00,00,16,16,16,16,16,99,99, 99,99,99,99,00,00,00,00,00,16,16,16,16,16,99,99,99,99,99,99); int Binary; char *Digit; int Counter; int CarryIn,CarqOut;
Bits from Thin Air
Digit = Value + NumDigits - 1; /* point to low-order digit*/ CarryIn = CarryOut = 0; for (Counter = NumDigits; Counter > 0; Counter--) { Binary = OxOf & *Digit; CarryOut = Dcarry[BinarytCarryIn]; *Digit = Dvalue[Binary+CarryIn]; CarryIn = CarryOut; Digit--; ) return (CarryIn != 0); )
Listing J-This program uses array indexes to double an ASCll fraction without resotiing to complicated logic. The program begins by isolating the low-order four bits of each ASCII digit and ends by returning the carry from the high-order character.
So now we have two methods to convert decimal fractions into binary fixed-point numbers. One starts with a double-precision floating-point number, but is therefore limited to the 53 bits available in the mantissa. The other starts with an ASCII text string, but can produce as many binary bits as you need with complete accuracy. Wouldn’t it be nice to be able to combine the two methods and get _ an infi-
“ The Best 8051 Emulator”
5 ft cable
A rugged CABBAGE CASEY lined with plenty of foam for your equipment can
TAKE A LOAD OFF YOUR MIND when you’ve goI to travel. PC based emulators for the 8051 family (8051/51FA/52/31132/4ll521451~452/5351552 + C M O S + m o r e . PC plug I” boards or M-232 box * Program Performance analyzer * Pull-down menus combined wdh l POwwful Macros wlh IF-ELSE, REPEATCommand-Drwen User Interface. WHILE strwt~res Gmtexl sensntiw help and l Source Level debug for PUM-51 and C51 On-Screen Edibng of data - Symbolic debuggmg with ln-lme assembler * 20 MHz real time emulabon and disassembler l 128K emulal~on memory l Execution time counter l 48 bd wde. 16K deep trace buffer l Trace can be viewed during emulai~on~ wllh loop counter l
TAKE A LOAD OFF YOUR BACK with our exclusive tilt-wheels and extenston handle optton.
mvi
PRICES: 32K Emulator for 8031 $1790: 4K Trace $1495’
CALL OR WRITE FOR FREE DEMO DISK! Ask about our demo VIDEO! ‘U.S. only notgau
,&$$g~
CORPORATION
(408) 888-1820
Circle No. 14 1 on Reader Service Card
UNLOAD ON US! Call or wnte to tell us about your shipping or carrying problems
WE HAVE SOLUTIONS! < , L CABBAGE CASES, INC. 3 m ,?‘a
1166-C STEELWOOD ROAD COLUMBUS, OHIO 43212-I 356 (614) 486-2495 (800) 888-2495
Circle No. 108 on Reader Service Card
66
ClRCUlT CELLAR INK
nite number of bits from a floatingpoint number? Decimal Binary Well, it would be nice to have 1.00000 = 10 00 00 00 00 00 00 00 perpetual motion, too. 0.10000 = 01 99 99 99 99 99 99 99 It turns out you can wring more 0.01000 = 00 28 F5 C2 8F 5C 28 F5 bits from the floating-point number 0.00100 = 00 04 18 93 74 BC 6A 7E 0.00010 = 00 00 68 DB 8B AC 71 OC than are present, at least for some 0.00001 = 00 00 OA 7C 5A C4 71 B4 numbers. The method is similar to that used in Listing 3: cook decimal Binary point _I digits out of the floating-point repre0.54321 = 5 X 0.10000 = 07 FF FF FF FF FF FF FD sentation, then convert them to binary 4 X 0.01000 = 00 A3 D7 OA 3D 70 A3 D4 fractionswithasmanybitsasyoulike. 3 X 0.00100 = 00 OC 49 BA 5E 35 3F 7A 2 X 0.00010 = 00 00 Dl B7 17 58 E2 18 This will work as long as you don’t try 1 X 0.00001 = 00 00 OA 7C 5A C4 71 B4 to cook more decimals out than the floating-point number encodes. Exact value = 08 BO FC F8 OD C3 37 17 Figure 5 shows how this works. I First, you need a table of the binary Figure Sin some cases. you can wring more bits out of a number than were originally equivalents of each decimal place, present. Adding the positions in the table allows you to get a reasonable approximation taken to as many bits as appropriate. of the equivalent. V’s important that you not try to cook out more decimals than the floating-point number can encode. Next, you break the floating-point number into separate decimal places, extract the equivalent of each place /* */ from the table, and multiply them by */ /* Extended precision equivalents for decimal fractions the respective digits. Finally, when /* Each entry is the ext-precision equiv. of the corresponding*/ */ /* decimal fraction 1.0, 0.1, 0.01, 0.001, and so forth you add all the products together, the */ /* Stored high-or&r byte first and flipped in Setupt&th result is a reasonable approximation */ /* ---because flipping during transcription is hard to do of the exact binary value, even if the */ /* and they're easy to mistype if transcribing by hand floating-point number didn’t have that many bits! Listing 4 illustrates the code required for this conversion. The accuracy of the result could be improved by adding a few more bits to each table entry and rounding after the final summation. Evenbetter results would come from expanding the table to include equivalents for all ten possible digits in each of 15 decimal places; this entirely eliminates the multiplications, at the cost of much more storage for the table entries. You don’t get something for nothing, of course. The magic conversion method doesn’t know what bits were /* */ discarded when you (or the C library */ 1" Convert a double-precision value to extended fixed pint routines) created the floating-point */ 1" Catches overflows into sign bit, sticks at sax value number,soitcannotrecreatetheorigi*/ /* Converts at NW.imUm precision in the extended buffer, /* using decimal equivalent of each digit in double value... */ nal value from thin air. In effect, it is somewhat increasing the precision of void CvtDbl2FullExt(unsigned char *extval, double dblval) ( the equivalent number by assuming that the decimal values are exactly int digit; int reps: correct. This is not always so, but int dblsign; sometimes it’s useful. DOUBLEBITS d; The EXTMATH routine converts a double dblint,dblfract; decimal number to fixed point (and back again) using both methods and 1 displays all of the bit patterns so you listing &This is the program equivalent of Figure 5. The program increases the precision cansee whatgoeson. T~~~"ExT~TH by assuming that the decimal values are precisely correct. If this assumption is wrong, your 0 .I” to see what happens. results could begin deviating from correct by an ever-wider margin. June/July 1989
67
d.dbl = dblval;
/* set up union with double value */
dblsign = d.bits.signbit; d.bits.signbit = 0;
/* force double to positive */
if (d.dbl >= 8.0) { /* catch overflow memset(ExtAccum,'\xff',NUNLEN-1); /* force to tnax value ExtAccum[NUNLEN-l] = Ox3f; ] else { /* zap accumulator memset(ExtAccum, '\O',NUMTSN); for (digit = 0; digit < DBLPR!X; digit++) f dblfract = modf(d.dbl,&dblint); for (reps = 0; reps < (int) dblint; reps++) { AddExt(binfracts[digit]); ] d.dbl = 10.0 * dblfract; /* extract next digit ] ] if (dblsign) { NegExt(ExtAc~~m+NUNLEN,ExtAccum); /* compl & set retn memcpy(extval,ExtAccumtNUMIEN,NUMUN); I else { /* set return value memcpy(extval,ExtAccum,NUMLEN); ] return;
*/ */ */
*/
*/
*/
I’ve pu t together a pair of test programs using the routines shown in this article so you can experiment with the different conversion methods. [Editor’s Note: Soffware for this article is available for downloading from the Circuit Cellar BBS and on Circuit Cellar INK Soffware On Disk #9. For information on downloading and ordering soffware,seepage 78.1 If you spend enough time with them, you’ll see where they work, where they fail, and ways to improve them for your projects. . . which is, after all, what this column is all about. + Ed Nisley is a member of the CIRCUIT CELLAR INK engineering staff and enjoys making gizmos do strange and wondrous things. He is, by turns, a beekeeper, bicyclist, Registered Professional Engineer, and amateur raconteur.
1
listing
225 Very Useful 226 Moderately Useful 227 Not Useful
4-_(continueci) .
Now there fs a bus that makes I easy to use the entire family of 66CC6 components. Utilizingnative660Wsignals,theK-Eusmakesitpossioletocreate bwcost66OOOsystems in a straightlorward manner. The simplicity inherent the K-System concept allows the sys rem designer the ability to concentrate on meeting the demands of the applications. This same simplicfty combined wkh its low cost makes the K-System ideal for applications ranging from personal use through educational and laboratory applications up to industrfal control and systems devekpment. All of this is accomplished at no sacriii in performance or reliabilfhy. The Convenient size (4 x 5 114inch) of the K-Busboardspermitsth optimal division 01 system functions thus simplifying system configuration. The motherboard incorporates integral card guides and compalafe power connectors which minimizes packagirvg requirements. Both SKDGS and OS-9/66OOO are fully supported allowing efficient system utilization in both single and muhCuser appikatbns. Boards currently in production: $199.96 K-BUS 12 Slots, .8’ cemers, PC type power connectors $159.96 1OMHz 66000 CPU, 2 ROM sockets (12 or 16MHz) K-CP&66K K-MEM 256K static RAM or 27256 type EPROMs (OK installed) $ 99.00 $129.95 K-AC1 2 serfal ports with full modem coMmk (66661) $129.96 K-FDC Fbppy disk COMrOfler (up to four 5 114 drives) $149.96 K-SCSI Full SCSI implemenration using 5360 chip 2 channel DMA controller using 66446 chip $199.96 K-DMA f 59.95 K-PROTO General purposelwirewrap board K-xxx-BB t 44.95 Bare board with documentation for above Software: SKDOS OS-9/66000
$150.00 Single user, editor, assembler, utilities, BASIC Multi-user, editor, assembler, SCRED, utilities BASIC, $300.00 C, PASCAL FORTRAN are available
R &D ELECTRONIC SURPLUS, INC.
Has been in business since 1946 selling NEW surplus electronics and electromechanical parts.
Send for our FREE 40 page catalogue detailing: Batteries Cables Capacitors Clocks Connectors Digital Timer/Controllers Diodes Displays Enclosures Fans Filters Heat-Shrinkable tubing Heatsinks Integrated Circuits Lamps & Lights
LEDs Lugs MOVS Ni-Cads Power Devices many Power Supplies Relays SemiConductors galore Stepper Motors 8 Driver ICs Speakers Many Switches Telephones and components Transformers Zeners etc.
Inquire about our UniOuad line of 66xxx Single Board Computera Quantify and pckag discounts available
1224 Prospect Avenue Playhouse Square Cleveland,OH44115
Terms: Check, Money Order, Visa, MasterCar&Prices include UPS ground shipment in continental U.S.
Hazelwood Computer Systems Highway94atBluffton Rhmeland,MO65069
UniQuadTM l
(314)236-4372
Circle No. 126 on Reader Service Card
68
ClRCUlT CELLAR INK
K-Kits’”
Telephone:(216)621-1121
l
Fax:(216)621-6628
Circle No. 146 on Reader Service Card
UPDATE:
Build an 87xx Programming Adapter by Jeff
Bachiochi
P
1 rogrammable microcontrollers require less board space than nonprogrammable microcontrollers because they don’t need external address latches and EPROMs. The problem is, not only do programmable microcontrollers cost two or three times asmuch as the nonprogrammable versions, they don’t fit into a normal EPROM programmer. Steve Ciarcia presented an article describing a Serial EPROM Programmer (SEP) in the October 1986 issue of BYTE. The design gives the user complete control over the parameters of the ZIF programming socket through its use of DATA statements within the part of the operating system written in BASIC. These programmable parameter statements make it possible to create a simple, low-cost adapter for programming 87xx microcontrollers. Projects are often created out of necessity. For example, the Mandelbrot Engine required up to 256 8751 microcontrollers to be programmed. (Editor’s Note: See the October, November, and December 1988 issues of BYTE for details of this project.) Before the Mandelbrot Engine, we had no need for an EPROM programmer that would also program microcontrollers. When work started on the Engine, we quickly reached a point where we could not continue without a way to program the EPROM on an 8751: We looked around for a programmer that we could either
TOP VIEW
S IDE VIE H
c .JI
‘28
[ -
L-
-
C
WI
EC /
Figure l--The ten components required for the adapter lay out very compactly on a piece of vector board.
Figure 2-The schematic for the modification shows a 4.9152-MHz crystal in place. Note that any crystal between 4 and 6 MHz may be used for the project.
buy or modify, and found that the SEP seemed perfect for the job. We began the process by building a small pluginadapter toadapta40-pinZIFsocket to the 2%pin programming ZIF socket of the SEP. The 8751 programming adapter is made on a 1” x 4” piece of vector board. Cut the centers out of a 28-pin wire-wrap and a40-pin socket to make individual strips. Alternately mount the sections on 0300-inch centers as shown in Figure 1 (pins l-14,0.300” space, pins l-20, 0.300” space, pins 15-28,0.300” space, pins 2140). A 28 pin wire-wrap socket’s long leads extend through the vector board to make the connection to the SEE’s ZIF socket. (A second socket may be stacked downward if additional clearance between the programming adapter and the SEP is required.) A 40-pinZIFsocket maybepluggedinto the standard 40-pin socket strips later to make insertion and removal of the microcontroller easier. The microcontroller needs an external oscillator to transfer data internally. Any crystal from 4 to 6 MHz and two 27-pF capacitors are all the components necessary to drive the oscillator. In addition, 87xx programmable micros have various forms of protection against code theft. A set of rocker switches and some pull-up resistors comprise the circuitry required to allow access to all such protection features. Place thepartson thevectorboard as shown in Figure 1. Figure 2 is the June/July 1989
69
DROE GE D ESIGN
R O B O T FOG
THEORIGINQTION 01 EXRCTING GRF~PHI~
E NGINEERING
IFI MRNUFIL PRINTED CIRC~$~T~;D/CRM
WLTI-LEVEL SYMBOL
CONCEPT 4EMORY LRYOUT WOVE I S R 3YMBOL MFlOE F R O M T W O C H I P SYMBOLS WITH RODEO BUS WIRE =HIP SYMeOLS QRE MROE F R O M AULTIPLE PFw3 S Y M B O L S . 3F16IC oSiO.OO POSTPRIO : CGm 3 COLORS 12 LRYERS 64 B Y 6 4 I N C H WORKSPFICE RNY GRID T O 0 . 0 0 1 I N C H RUNS ON RNY PC COMPRTIBLI 15 LINE WIDTHS DOT MFlTRIX OUTPUT 200KB ~Cl~Uhl4~~TION ON 16 WORK FIRERS SFIVEFIBLE S T I T C H B E T W E E N LFIYERS ZOOM Qt.-D PRN TO RNY SCFlLE JOVANCEO 6100.00 POSTPRIO
:
RBOVE FEFITURES E6f7 RESOLUTION 15 COLORS LFIRGER J O B S MOUSE FIOVF)NCEO E D I T I N G P R I N T E D MFINUFlL
In BASIC: 170 DATA 000O1,000H,OO,OOOH,OOOH,OOOH,OOOH,OOOH,O,OO,O,OO,~
In tokenized form in RAM: (24COH) start hext 24COH OOH AAH 9CH 24CBH 2CH 30H 30H 24DOH 2CH 30H 30H 24D8H 30H 48H 2CH 24EOH 30H 30H 30H 24E8H 48H 2CH 30H
start ASCII* 30H 30H 30H 30H 31H - . . . 0 0 0 0 1 30H 48H 2CH 30H 30H - , 0 0 0 H , 0 0 30H 48H 2CH 30H 30H - , 0 0 0 H , 0 0 30H 30H 30H 48H 2CH - 0 H , 0 0 0 H , 4BH 2CH 30H 30H 30H - 0 0 0 H , 0 0 0 2CH 30H 30H 2CH 30H - H , 0 , 0 0 , 0 (24FSH) end hex* end ASCII l 24FOH 2CH 30H 30H 2CH 30H ODH 37H OOH - , 0 0 , 0 . 7 .
schematic. A spot of super glue will hold things in place before you do any soldering, but be careful: the thinner versions of this glue like to wick up into IC sockets, gluing their contacts shut. Use small insulated wire (e.g., wire-wrap wire) to make all the interconnections on the bottom of the vector board. WARNING: The SEP can damage any microcontroller left in the ZIF socket uponinitialpower-uporsystem reset. Do not insert a microcontroller into the adapter ZZF socket until the system is initialized with the proper TYPE selection. Do not turn the SEP ofi until you have removed uny microcontroller from the adapter ZIF socket.
Programming 87xx microcontrollers on the SEP with the adapter Turn on the SEP and make the proper TYPE selection. Insert the programming adapter into the SEP making sure p&t 1 &aligned properly. The green light should be on. Insert the
microcontroller (again, align pin 1). All programming should be done at Normal programming speed, not Intelligent or Fast modes. To program code into a microcontroller: Move the code to be programmed into the SEP Set the adapter switches to CODE Select the Program function To verify code in a microcontroller: Move the code to be verified into the SEP Set the adapter switches to CODE Select the Verify function To read code from a microcontroller: Set the adapter switches to CODE Select the Read function To program the security table: Move the mask code to be programmed into the SEP Set the adapter switches to P. Table Select the Pr ram function (program first 32 rtes.1
In BASIC: 260
DATA
S(lO)="USER 1 ":$(ll)="USER 2 ":S(12)="LJSER 3
In tokenized fonn in RAM:
26COH 26CBH 26DOH 26DBH 26EOH 26E8H 26FOH 26FEH
32H 04H 20H 20H 31H 52H 20H EAH
Circle No. 121 on Reader Service Card 2700H 20H
70
ClRCUlT CELLAR INK
FigureS- When you begin modifying yoursystem EPROM, look for the starting addresses in the setup data shown here.
(26C6H) start hex+ start ASCII + 2EH 35H 56H 22H ODH 42H 01H - 2 . 5 V u . B . 24H EOH 31H 30H 29H EAH 22H - . S . 1 0 ) . m 55H 53H 45H 52H 20H 31H 20H U S E R 1 I8 :S. 20H 20H 20H 22H 3AH 24H EOH 31H 29H EAH 22H 55H 53H 45H - 1 1 ) . " U S E 20H 32H 20H 20H 20H 20H 20H - R 2 22H 3AH 24H EOH 31H 32H 29H " : $ . 1 2 ) 22H 55H 53H 45H 52H 20H 33H - . oa U S E R 3 (2707H) end hex & end ASCII + II 20H 20H 20H 20H 20H 22H ODH -
Figurel--Thebeginning addresses for the display data to be altered should appear as in this frame.
ORIGILJAL cHANc;ETO ADDRH?ixAscxxExAsc 24COH OOH 24ClH AAH 24C2H 9CH 24C3H 30H 24C4H 30H 24C5H 30H 24C6H 30H 24C7H 31H 24C8H 2CH 24C9H 30H 24CAH 30H 24CBH 30H 24CCH 48H 24CDH 2CH 24CEH 30H 24CFH 30H 24DOH 2CH 24DlH 30H 24D2H 30H 24D3H 48H 24D4H 2 C H 24D5H 30H 24D6H 30H 24D7H 48H 24D8H 2CH 24D9H 30H 24DAH 30H 24DBH 30H 24DCH 48H 24DDH 2CH 24DEH 30H 24DFH 30H 24EOH 30H 24ElH 48H 24E2H 2 C H 24E3H 30H 24E4H 30H 24E5H 30H 24E6H 48H 24E7H 2CH 24E8H 30H 24E9H 2CH 24FAH 30H 24EBH 30H 24ECH 2CH 24EDH 30H 24EEH 2CH 24FZ'H 30H 24FOH 30H 24FlH 2 C H 24F2H 30H 24F3H ODH
. . 0 0 0 1 il 0 0 H il 0 ;, 0 H il 0 H ' 0 0 0 H b 0 0 H ; 0 0 H ; il 0 il ; 0 il .
+ + + + 38 31 35 31 + 30 31 30 + + 32 38 + 37 38 + + 32 36 + + 30 43 45 + + 30 43 45 + + 30 32 33 + + 30 + 35 30 + 30 + 30 30 + 30 +
To program lock bit 1 or 2: Set the adapter switches to Lock 1 or Lock 2 Select the Program function (program first byte) Altering your system EPROMVersion 2.0
8 I 5 1 ; 1 0 H ; 8 ; 8 H ; 6 H ;, c E H ;, c E H il 2 3 H LJ ; 0 Ll ;, 0 ;
Figure S-These changes are made to the setup data shown starting in Figure 3.
If you want to program an 8752 or an 87C252 @7C51FA), nothing special must be done since these devices program like 2764As. However, if you want to program 8751s, 8751BHs, or 87C51s then you must change a TYPE SELECTION (SEP ROM version 1.0-1.6) or add a new USER ENTRY (SEP ROM version 2.0). [Editor’s Note: There are signifycant diflerences between version 1 .x and version 2.0 of the SEP system EPROM. If you have version 2.x and would like more specificinstructions on how to modify 2.x for use with the programming adapter, send a self-addressed stamped envelope fo: 87xx Programming Adapter Circuit Cellar INK 4 Park St. Vernon, CT 060661 To alter the system EPROM you must first get the system EPROM’s code into the buffer. Version 2.0 has a selection in the main menu for accomplishing this. This version also has six reserved entries, USER l-USER 6, for adding new device types. In this example, USER 1 will be eliminated to make an entry for 8751s. Two areas of the system EPROM will be affected: Setup data and Display data. First locate the Setup data using the SEP’s DUMP function and write down the starting and ending addresses as shown in Figure 3. Similarly, use the DUMP function to find the starting and ending addresses for the Display data area as shown in Figure 4. Next, select the CHANGE function and enter the starting and ending addresses for theSetupdata you found above. Then enter the changes that are shown in Figure 5. Likewise, change the Display data as shown in Figure 6.
MORE GOOD CODE... FAST! softaid’s In-Circuit Emulators givI IOU all the power and speed yo leed to develop microprocesso )ased products in realtime ncreasing your productivity ant ;aving you time and money.
Emulators available for: i4180, 280, Z180, 808818086 10188/80186,
8085, v4o/v50 Priced from $595 to $2995
FULL SCREEN DEBUGGING! Vith the optional source leve ‘ebugger, you get a real time, ful creen debugging environmen lith pop-up windows and symbolic isplays. Your source code ant omments are displayed in z {indow that is automatically linkec I the debugging session. This lakes embedded systerr ebugging FAST and EASY!
TIMELY TECHNICAL SUPPORT! Iur technical staff is ready tc nswer your questions. Give us 2 all to discuss your microprocessor evelopment needs! iomplete information is alsc vailable on our BBS from 5 p.m. tc a.m. EST -- 301-964-8456. (-1 8930 ROUTE 108 COLUMBIA, MD 21045 . : (301) 964-8455 (800) 433-8812 -0 Circle No. 147 on Reader Service Card
June/July 1989
71
ADDR
GRIGIMIL - HEXASC -
CHANQE M WC Asc-
Must add USER ENTRY
8751
m!
26C6H 26C7H 26C8H 26C9H 26CAH 26CBH 26CCH 2 6CDH
42H OlH 04H 24H EOH 31H 30H
B . . $ . 1 0
29H EAH 22H 20H
)
2 6CEH 2 6CFH 2 6DOH
26DlH
55H
26D2H 2 6D3H 26D4H 2 6D5H 26D6H 26D7H 26D8H 26D9H 2 6DAH 2 6DBH 2 6DCH
53H 45H 52H 20H 31H 20H 20H 20H 20H 20H 22H
t t t t t t t
USER ENTRY for 8751: setup data DATA 8751,010H,28,78H,26H,OCEH,OCEH,O23H,O,5O,O,OO,O Display data v 8751 21V"
t t t 20
. ”
U S E R 1
38
8
37 35 31 20 20 20
I 5
32 31 56
1
2 1 V 20 t
”
(all+) 2706H 27078
22H ODH
” .
+ t
Figure 6-Change the display data shown starting in Figure 4 as indicated in this table. Circuit Board 1 l”x4” piece of vector board (preferably with holes predrilled on O.lOO-inch centersand individual pads on each hole) IC Sockets 2 28-pin wire-wrap sockets (one cut into two U-pin strips JlA &JIB, the second used as an extension for more height if necessary) 1 @pin ZIF (Zero Insertion Force) socket 1 40-pin IC socket (must allow the ZIF to plug into it) (cut into two 20-pin strips J2A & J2B) Discretes 2 27 pF capacitors 1 10 nF tantalum capacitor 1 4.9152-MHz crystal (anything from 4 to 6 MHz) 1 4.7k ohm pull-up SIP (or individual resistors) 1 B-position slide or rocker switch (only three positions are used) Miscellaneous Wirewrap wire for interconnections Cyanoacrylate glue for tacking down parts
Figure8-7hepartsrequiredfortheadapter are simple, and will require a minimal cash outlay by most builders.
72
c//?CU/T CELLAR INK
For: For: For: For:
8752BH 87C252BH 8751BH 87C51
Lock 2
(87C51FA)
ON
ON
Program as 2764~ Program as 2764~ Must add USER ENTRY Must add USER ENTRY
OFF
USER ENTRY for 8751BH and 87C51: Setup Data DATA 8751,010H,28,78H,26H,OCEH,OCEH,O25H,0.50,O,OO,O Display data 11 87C51 12.5V"
Figure 7--The 87xxProgramming Adapter can be made to work with a variety of devices by changing the switch settings shown here.
This completes the changes. Use the DUMP funtion to check that all changes were made correctly. Select the 27C128 (27128) EPROM type and insert a blank 27C128 (27128) in the SEPs programming socket. Program the whole EPROM and your new system EPROM should be ready to use. Remember to remove the EPROM from the ZIF socket before turning off the power to replace the system EPROM with the new one. The adapter can also be used with other EPROM programmers to program 8752BHs and 87C252BHs (87C51FAs) by setting the programmer up for 2764As. The other processor types discussed requirealterations which we’ve accomplished through the flexiblity of the SEP, and not through the complexity of the hardware for the adapter. A list of programadapter switch settings for working with other devices is given in Figure 7. Figure 8 shows the programming adapter’s parts list. Cost for the parts should be minimal.
It is possible, of course, to buy completely hardware-based adapters for programming programmable microcontrollers. Most such adapters will cost at least $100 and will be limited in their application to one family of micros. I like the fact that, in this case, hardware and software complement each other quite nicely. Neither is more important than the other, with thelowest-cost solutionbeing a 50/50 mix of both. 4+
IRS
228 Very Useful 229 Moderately Useful 230 Not Useful
CONNECTIME
Excerpts from the Circuit Cellar BBS
THE CIRCUIT CELLAR BBS 300/l 200/2400 bps 24 hours/7 days a week (203) 87 1- 1988 - 4 incoming lines Vernon, Connecticut
With the upgrade to version 2.1Mof TBBS (The Bread Board System), oneof the most obvious improvements was to thefile system. I mentioned a few issues ago that I’d be implementing the new file system features, and have been quite successful at doing so since then. Using the old software, the only way to group related files into separate file areas was to define individual menus for each of those areas. Finding a certain file involved coursing through menus in an attempt to find the correct subarea. Plus, checking for new files involved a good memory (yours). The new software solves these problems as well as some others not mentioned. You start offat the main menu and select the iles area. At the next menu you tell the system you want to ownload a file. Once you’re into the download section, you arepresented with a list of 14file areas. Areas include files for articles which have appeared in CIRCUIT CELLAR INK, files related to Electrical Engineering, cross-development tools, and newly uploaded files which don’t have a home yet. Upon selecting one of the subareas, you aregiven a list of commands available. Commands include cL>ist the available files, ownload a file, show a list of ew files, <E>xamine the contents of an ARC file, and go to a new cA>rea. The ist command allows you to include a partial or a complete file name to restrict the files shown. For example, type “L *.ARC” to list just the ARC files available in the selected subarea. The ew command will actually show you all files uploaded after a certain date in all subareas. Used without any parameters, the