+ All Categories
Home > Documents > Circuit.cellar.111.Oct.1999

Circuit.cellar.111.Oct.1999

Date post: 04-Jun-2018
Category:
Upload: sarah-kaya
View: 224 times
Download: 0 times
Share this document with a friend
68
8/13/2019 Circuit.cellar.111.Oct.1999 http://slidepdf.com/reader/full/circuitcellar111oct1999 1/68 THE MAGAZINE FOR COMPUTER APPLICATIONS ® # 111 O C T O B E R 1999 Open-Source Home Automation Program Downloadable Web Server Software How Does Windows CE Stack Up? The Roots of Java
Transcript
Page 1: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 1/68

T H E M A G A Z I N E FO R C O M P U T E R A P PL I C AT I O N S

®

# 1 1 1 O C T O B E R 1 9 9 9

Open-Source Home Automation Program

Downloadable Web Server Software

How Does Windows CE Stack Up?

The Roots of Java

Page 2: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 2/682 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

— COLUMNS —Considering the DetailsI/O for Embedded Controllers—Part 1: Digital I/OBob Perri n I/O, I/O, so off t o w ork… . D esigning generic cont rollersw ith only guesstim ation s of wha t t he end-product I/Oneeds might be keeps Bob busy. Save yourself some w orkand look at the circuits covered in Part 1 of this series.

Lessons from the TrenchesPowering Your MemoryGe o rge M a r t in Far too often, especially in programm ing, you can get aw ay

w ith w hat’s less than best . H aving personally tr ied allthe less-than-best meth ods to w rite memory m anagementroutines, G eorge invites you t o listen in as he shares thebest way to accomplish the task.

Silicon Update OnlineWire WarsTom Cantrel l The action’s getting lively on the USB–versus–IEEE 1394 front as bothsides fortify their legaldefenses and

rally

the troops.C atch Tom’s latest

report from th e front lines (andthe 1394 Developers Conference).

Double your technical pleasure each month. After you read Circuit Cellar magazine, get asecond shot of engineering adrenaline with Circuit Cellar Online , hosted by ChipCenter.

— FEATURES —PIC Remote Control with a TwistBrian Mi l l i er When he got his TV satellit e dish, Brian discovered thefreedoms of sat ellite netw ork program min g—and th elimitations of the standard remote control. His ’16F84-based IR remote puts him back in control.

Self-Help for Bugs in the Field: A Device-Initiated Upgrade SolutionPet er G rav est ock U pgrading firmw are after a product is in the field canbe challenging, especially when traditional methodscan’t be used. With a device-initiated architecture, Petershows us how easy remot e and automat ic f ixes can be

Testing 1, 2Part 3—Standards: Prepping Your PrototypeG eorge N ovacek Coping wit h environmental challenges is a w alk in thepark in comparison to getting th e pow er right. G eorgeexplains the t esting requirements as w ell as the changesyou’ll need to make for your product to succeed.

Ethernet Networking: Desktop to DeviceWi ll iam Peisel and Di ck Caro Afraid to venture into the gloomy tangle ofEthernet? William and Dick aren’t tellingtales when they say low costs andInternet integration capa-bil i t ies w ill lead toEthernet

networks atall levels of industry

in the near future.

Resource Links•CAN–Controller Area Network • Digital Signal ProcessingBenjami n D ay •Printed Circuit Board Software and Manufacturers•Pointers to NanotechBob Paddock

Test Your EQ

8 Additional Questions

T a b l e o f C o

n t e n t s f o r S

e p t e m b e r 1 9 9 9

W W W. C I R C U I T C E

L LA R. C O M / O N L I N E

Page 3: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 3/68CIRCUIT CELLAR ® Issue 111 October 1999 3www.circuitcellar.com

38 Nouveau PCedit ed by H arv Weiner

40 What’s in a Name?Window s C E vs. a Ha rd RTOSM al Raddalgoda

45 RPC Real-Time PCWhere in th e World...Part 3: Fighting the Wind w ith G PSIngo Cyl iax

50 APC Applied PCsG oAhead for N othin g—G ettin g the Server Start edFred Eady

I S S U E I N S I D E

MisterHouse— An Open-Source Hom e Autom at ion P rogramBruce Wi nt er

The Java Virtual MachineD ave Lyons

A Versatile Timer/SynchronizerBrian M il l ier

Calling on the Standards— Making Sure Your Modem C an C omm unicateA rt hur J. Carlson

Hands-On PIC Trainer— Programming in AssemblyJon V art eresian

IrDA Technology— Part 1: An O verview H ari Ramachandran

I MicroSeriesRolling Your Ow n M icroprocessorPart 2: D esign Application w ith t he Rabbit-80M onte D al rymple

I From the BenchG et SmartMedia—Part 2: Hands OnJeff Bachi ochi

I Silicon Update‘Net-in-a-ChipTom Cantrel l

6

8

11

83

95

96

1220

2430566066

72

78

1 1 11 1 1

Task ManagerElizabeth LaurençotOpen for Business

New Product Newsedited by Harv Weiner

Reader I/O

Test Your EQ

Advertiser’s IndexNovember Preview

Priority InterruptSteve Ciarcia

Spreading the Wealthof Knowledge

Page 4: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 4/686 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

TH E M A G A Z I N E FO R C O M P U TE R A P P L IC ATI O N S

TASK MANAGER

EDITORIAL DIRECTOR/PUBLISHERSteve Ciarcia

MANAGING EDITORElizabeth Laurençot

TECHNICAL EDITORSMichael PalumboRob Walker

WEST COAST EDITORTom Cantrell

CONTRIBUTING EDITORSMike Baptiste George MartinIngo Cyliax Bob PerrinFred Eady

NEW PRODUCTS EDITORHarv Weiner

PROJECT EDITORJanice Hughes

ASSOCIATE PUBLISHERSue Skolnick

CIRCULATION MANAGERRose Mansella

CHIEF FINANCIAL OFFICERJeannette Ciarcia

CUSTOMER SERVICEElaine Johnston

ART DIRECTORKC Zienka

GRAPHIC DESIGNERJessica Nutt

ENGINEERING STAFFJeff BachiochiKen Davidson

John Gorsky

Cover photograph Ron Meadows—Meadows MarketingPRINTED IN THE UNITED STATES

For information on authorized reprints of articles,contact Jeannette Ciarcia (860) 875-2199 or e-mail [email protected].

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

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

CONTACTING CIRCUIT CELLARSUBSCRIPTIONS:

INFORMATION: www.circuitcellar.com or [email protected] SUBSCRIBE: (800) 269-6301 or via our editorial offices: (860) 875-2199

GENERAL INFORMATION:TELEPHONE: (860) 875-2199 FAX: (860) 871-0411INTERNET: [email protected], [email protected], or www.circuitcellar.comEDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066

AUTHOR CONTACT:E-MAIL: Author addresses (when available) included at the end of each article.ARTICLE FILES: ftp.circuitcellar.com

CIRCUIT CELLAR ® , THE COMPUTER APPLICATIONS JOURNAL (ISSN 0896-8985) is published monthly by Circuit CellarIncorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at Vernon, CT and additional offices.One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico $31.95, all other countries $49.95.Two-year (24 issues) subscription rate USA and possessions $39, Canada/Mexico $55, all other countries $85. Allsubscription orders payable in U.S. funds only via VISA, MasterCard, international postal money order, or check drawn on U.S. bank.Direct subscription orders and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 698, Holmes, PA19043-9613 or call (800) 269-6301.Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 698, Holmes, PA 19043-9613.

ADVERTISINGADVERTISING SALES MANAGER

Bobbi Yush Fax: (860) 871-0411(860) 872-3064 E-mail: [email protected]

ADVERTISING COORDINATORValerie Luster Fax: (860) 871-0411(860) 875-2199 E-mail: [email protected]

ADVERTISING CLERK Sally Collins

[email protected]

EDITORIAL ADVISORY BOARDIngo Cyliax Norman Jackson David Prutchi

Open for Business

w hen people are asked what they want to beremembered for, a common response is that

they want to be remembered for havingcontributed something. There are countless ways this can happen.

Although you may be a philanthropist who donates a million dollars to auniversity so less-advantaged students can obtain a good education, or youmay be a scientist who develops a vaccine that saves thousands of lives,most of us are going to be remembered for smaller gestures. I’m sure you’veheard it said before, but let me repeat it here: it’s the little things that count.

The small kindnesses and efforts in day-to-day life are what truly matters.It doesn’t have to be entirely altruistic; you can benefit from your effortsnow, whether it’s on a financial or personal-satisfaction scale. And you don’thave to contribute to everything everywhere. It’s a good idea to choose yourcauses wisely and pick something that interests you. This month, I want tomention a couple options that may appeal to embedded software engineers.

In this issue, Bruce Winter presents an open-source home-automationprogram he developed. This Perl-based program can be accessed online,and Bruce encourages everyone to add to it (one programmer has alreadyput together a GPS-based module that tracks car location from home) andto share the results. So, if you’re interested in programming for home auto-mation, check out www.misterhouse.net.

Speaking of open-source software, we’ve received a lot of great feedbackabout Ingo’s Real-Time PC series on RT-Linux. There’s so much interestthese days in this POSIX-based OS! Linux operates under the GNU PublicLicense, which means that the source code must be made available. Whywould anyone want to give their source code away? Consider what RichardStallman wrote in the GNU Manifesto (www.fsf.org/gnu/manifesto.html):

“I consider that the golden rule requires that if I like a program I mustshare it with other people who like it. … GNU serves as an example toinspire and a banner to rally others to join us in sharing. This can give us afeeling of harmony which is impossible if we use software that is not free.For about half the programmers I talk to, this is an important happiness thatmoney cannot replace.”

You may object, “Don’t programmers deserve a reward for their creativ-ity?” Richard’s response: “If anything deserves a reward, it is social contri-bution. Creativity can be a social contribution, but only in so far as societyis free to use the results.” So, don’t say, “Oh, that GNU stuff is none of mybusiness.” Make it your business; find out how you can contribute!

Finally, if you enjoy playing with web technologies, consider helping outat Linux Online (www.linux.org/about/assist.html). You’ll even earn a coffeemug for your work! Perhaps you’ll just get a coffee mug out of theexperience, but I bet you’ll get a whole lot more.

Page 5: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 5/688 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

NEW PRODUCT NEWSEdited by Harv Weiner

PICmicro EXPERIMENTER/LAB BOARDThe PIC-X1 is a testbed containing a prototyping

area and m ost of the circuitry comm only used withPIC micros, including a 5-V power supply, crysta l-con-trolled oscillator (adjustable from 4 to 20 MH z), andreset circuit. Application circuits include a switchmatrix, potentiometers, LEDs, LCD module, serialEEPRO M, real-tim e clock, t emperature sensors, servoconn ecto rs, RS-232/-485 and IR i nt erfaces, a nd spea ker.

All of th e I/O pins a re brought out to headers nextto a 40-pin ZIF socket. This allow s connection tooffboard circuits as w ell as allow ing onboard circuits tobe connected to other P ICm icro pins, if desired. ThePIC -X1 is designed to w ork w ith 40-pin PIC m icros, butmay be jumpered to work with smaller devices.

Projects such as calculators, LCD clocks, digital

thermometers, LCD backpacks, tone dialers, TV re-mote controls, and so forth may be created using thePIC -X1. It includes in-circuit programm ing connectorsso the resident PICmicro may be reprogrammed on-the-fly (requires flash device) using programmers that sup-port this feature, like the EPIC PICmicro Programmer.

The P IC-X1 is priced at $199.95 for an assembled unit,$139.95 unassembled, or $49.95 for a bare PC B. A partslist, schemat ic, and exam ple programs a re also included.

microEngineering Labs, Inc.(719) 520-5323 • Fax: (719) 520-1867

www.melabs.com

EMBEDDED CONTROLLER MODULEUni-Micro is a compact , 8051-compat ible embedded

controller module featuring a combination of memory,digit al I/O, an d ana log I/O t hat is perfect for inst ru-mentation, monitoring, and control applications. Itprovides enhanced JTAG -based serial program m ingthat is six times faster than parallel programming. Themodule features 128 KB of flash memory, 32-KB boot/data flash, 256 bytes of RAM, 2-KB batt ery back-upscratchpad SRAM, 3000 gat es programm able logic, and54 program m able I/O pin s.

The eight I/O ports on t he U ni-Micro can functionas m icrocont roller I/O, C PLD I/O, address out , addressin, latched address out, latched address in, data port,

special function out, alternate function in, peripheralI/O, o r open-drain out put s. Each I/O port is easil yconfigurable by programm ing tw o sets of 8-bit regis-ters, each bit controlling a single pin in the I/O port.

Serial programmability is required for first-time, in-system programming. Without it, first-time flashprogramming can only be accomplished using a con-ventional external EPROM programmer or boot codestored in t he MC U ROM. Serial programm ing of theUni-Micro module can be accomplished using a PCequipped w ith a JTAG board.

By integrating all the programmable logic, concurrent

f l a s h me m ory, da ta f l a s h m e mory, SR AM , a nd I /O M C Ucore, the U ni-Micro Modu le has a power consumpt ionof only 57 mA at 16 MHz.

Uni-Micro sells for $59 .

OS Systems Inc.(908) 979-1885Fax: (908) 979-3414www.ossystems.net

Page 6: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 6/68CIRCUIT CELLAR ® Issue 111 October 1999 9www.circuitcellar.com

NEW PRODUCT NEWSFIBER-OPTIC MODEM

The Model 232FLST Fiber-Optic Modem providesthe EMI/RFI and t ransient im mu nity of fiber optics ina transparent cable connection betw een PC s or otherdevices. It is ideal for data acquisition and other com-munication applications that are employed in electri-cally noisy environments.

A pair of the devices will enable any t w opieces of asy nchronous RS-232 equipment tocomm unicate full or half duplex over tw ofibers up to 2.5 mi. RS-232 data signals at upto 115.2 kbps and R TS/C TS han dshak e linesare supported. Port pow ering allows operationw ithout external pow er in most P C applications.

Low -powered ports such a s laptops may require anoptio nal 12-V pow er supply.

The RS-232 connector is DB-25 female and thefiber cable connectors are ST sty le. The m odem isonly 4.3 ″ × 2.3″ × 1″.

The modem sells for $154.95 (tw o are required toconnect two components). An optional power supply isavailable for an additional $14.95 .

B&B Electronics(515) 433-5100Fax: (815) 433-5105www.bb-elec.com

Page 7: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 7/6810 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

NEW PRODUCT NEWSPHONE LINE SIMULATOR KIT

Ring-It! is a m icroprocessor-cont rolled t elephone-linesimulat or that acts like a phone company central officeand is used to test anddemonstrate telephones,answering machines, faxunits, voicemail systems,or modems. It supports E-911 training and caller-ID.An external audio jack isincluded for call-monitor-ing applications.

The simulat or emulatesan analog telephone line.

For example, a connectedtelephone produces anauthentic-sounding dial tone. Dialing a seven- oreleven-digit phone number with a touch-tone phonerings the device plugged into the test line. Busy signalsand reorder tones can a lso be heard.

The caller-ID feature provides number-only or name/number messages. Five different test modes offer stan-

dard telephone-line emulation or special repetitive-cycle

testing, including automatic ring-up. An LED readoutdisplays the DTMF digitsthat are dialed to v erify useof touch-tone phones.

Ring-It! can be purchasedassembled or as a kit t hatincludes a PCB, electroniccomponents, and a t echni-cal manual.

The factory -assembledunit (RI-001F) sells for $325 .The delux e kit (RI-001D ) is

$205 and includes thecaller-ID option and cus-

tom enclosure. N on-call er-ID kit versions (RI-001) areavailable star t ing at $149 .

Digital Products Co.(916) 985-7219 • Fax: (916) 985-8460www.digitalproductsco.com

Page 8: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 8/68CIRCUIT CELLAR ® Issue 111 October 1999 11www.circuitcellar.com

READER I/OKEEPING UP TO DATE

John Luo’s article in the June issue (107) “ C ompactOptica l Image Scanner” discussed a design built a roundthe Texas Instruments TSL1401 linear photodiode array.

TI no longer supports this device, but Texas Ad-vanced Optoelectronic Solutions (TAOS) has licensedthe opt oelectronic sensor product portfolio (w hichinclu des the TSL1401) from TI. Inform at ion can befound at www.taosinc .com or by calling (972) 673-0759.

Carl [email protected]

FINDING THE WAY AROUND SAI enjoyed the G PS art icle by Ingo C yliax in th e

August issue (109) and the earlier series by Do-WhileJones (Circu i t C el l a r 77–78). Both did a great job ofgett ing r ight to the meat of the matter. However, botharticles may give readers a misu nderstanding w ithregards to Selective Availability (SA) and position error.

The DoD implemented SA by diddling w ith t hetiming of the signals, among other things. This trans-lates into a different range error for each satellite.These range errors, once crunched th rough the m ath ,give the position errors noted in the articles.

Both articles gave the impression that the SA errorscan be “ subtracted out” by know ing the posit ion errorof a know n fixed site. Here’s the rub—th e fixed site’serror in position w ill only be th e same as t he observer ’sif both posit ions w ere computed from the sam e set ofsatell i tes. In the real w orld, any t w o G PS receivers mayuse different satellites if one particular satellite islocally obscured. In that case, the position errors arelargely uncorrelated, and fixing the problem, as out-

l ined in the ar t icles, can actually m ake mat ters worse!To fix SA, broadcast the range errors, not the position

error, so the corrections can be made before the data iscrunched. That’s w hat t he Coast G uard and otherD G PS providers do. I hope this clarifies things.

John WilsonAnnandale, VA

Page 9: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 9/6812 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

MisterHouse

FEATUREARTICLE

Bruce Winter

lIf you thought thattalking houses onlyexisted in cartoons,it’s time for you tomeet MisterHouse.This Perl-basedprogram can tell youwho’s on the phone,what room your kidsare in, the latestweather forecast,and more.

e t ’s s ta rt w i tha quiz. Which of

th e follow ing bestmatches your philosophy

in home au tomat ion?

• C omputers are too ornery and difficultto m anage to be meddling in dailyaffairs of the house.

• Automat ing daily house chores wit ha computer is a fun an d useful th ingto do, but it can only reliably be donew ith a dedicated and specializedmicroprocessor.

• PC s are destined for more than justsending e-mail and playing golf;soon they w ill rule the w orld (or atleast part s of you r house)!

If you subscribe to the first philoso-phy, you’re probably reading the w rong

magazine. I bet a good number of youare mem bers of group tw o. I used to bea m ember of this group w hen I sta rtedworking with home automation (HA)with Steve’s f irst Home Run HA sys-tem from the BYTE ma gazine days.

Over the years, as PCs got fasterand cheaper, I’ve migrated to the thirdgroup. The nice thing about doing HAon a PC is that you have a much w iderchoice of programs and ha rdw are tointegrate. Every day it seems like thereis some neat new program or deviceyou can hook into a PC.

At m y da y job (designing chips atIBM), I’ve found great productivity ina programming language called Perl.About a y ear ago, I decided to w rite aPerl-based, open-source multiplatformHA program. I call it MisterHouse—w hich is easier than call ing i t a P erl-based, open-source multiplatform HAprogram.

This article gives a litt le backgroundon MisterHouse and show s how I useit t o log phone calls and announce whois calling over our house PA system.

WHY OPEN SOURCEI t used to be that w hen someone

w rote a program and then m ade i tavaila ble for free, it w as called “ freesoftw are.” Often, only the binary forthe program w ould be distributed.

Recently, the t erm “ open source”has been promot ed. There’s an officialdefinition at w w w .opensource.org/osd.htm l, but t he basic idea is thatthe source of the software is posted onthe Internet so t hat anyone can helpw ork on i t .

With new hardware becomingavailable daily and the amount ofinformat ion on the Internet grow ingexponentially, the num ber of H Apossibilities is grow ing faster than

any one person can possibly keep upw ith. U sing the open-source idea, ifthe program doesn’t do w hat you needdone, you can extend i t a nd then shareit for others to use.

In the few months that I have hadMist erHouse (MH ) posted online, Ihave reaped not only lots of good ideasfrom other users, but also bug fixes,code extensions, and completely new applications.

THE OS DECISIONHere’s another quiz: Which is thebetter OS to do HA on? Window s andthe great wealth of fun software avail-able on i t , or a Unix OS with i ts im-proved reliability and multitasking?

Can’t decide? With Perl you canrun on either OS! In fact, Perl is avail-able on several different OSs, but I’veonly tested MisterHouse on Windows95, 98, NT 4.0, Linux, and AIX.

By using the same underlying inter-face subroutines, you can keep thehigher-level user event code platform -

An Open-Source Home AutomationProgram

Page 10: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 10/68 CIRCUIT CELLAR ® Issue 111 October 1999 13www.circuitcellar.com

independent. For example, on Window s,a serial port it em w ill use the

module to read and w rite serialdata using Win32 API calls to a serialport DLL. On a POSIX-compatible Unixsystem (Linux and most others), thatcall is translated by themodule to use POSIX calls.

Here’s another example. When you

ask MH to run a background processon Window s, the Perl

module is used; on Unix, the forkfunct ion is used. The user code is thesame, regardless of the platform.

VOICE IN, VOICE OUTMuch of the fun in HA comes when

your computer talks and listens. Perldoesn’t come w ith built -in voice soft-ware, but i t talks to programs that do.

On Unix, you can implement text

to speech (TTS) w ith t he Festiva l speechsynthesis system. Festival provides aserver that MH can t alk to via TCP /IP

sockets, and you can plug in differentvoices and languages.

On Window s, you can do bot h TTSand voice recognition (VR) using freelydow nloadable engines from Microsoft.These engines provide access via OLEmet hods, wh ich Perl also supports.Several different v oices are availa ble,including some digitized voices that

sound amazingly humanlike.The VR is in a com ma nd-and-con-

trol m ode (i.e., it w ill not recognizeany arbitrary set of w ords; only theones from a set of phrases you specifyusing the MH object).This mode improves reliability overw hat you migh t get w i th a d ic ta t ionmode, where any word can be expected.

PICK YOUR INTERFACESAll of the voice command objects

you specify w ill be available wit h VR,as w ell as from the comm and l ine, aG U I Tk interface, and a w eb int erface.

The Tk interface is built using P erlTk w idgets. These w idgets enable usto create G UI objects w ith just a few lines of code. Phot o 1 show s the de-fault Tk interface.

The w eb interface can be used fromany Internet browser, w hether i t’s inyour hou se or not. The interface usesa w eb-aut henticat ion passw ord to allow remote control (e.g., go to misterhouse.net and you can t ake a look at the oneon my house).

U sing HTML tem plates, the w ebint erface can be easily cha nged. Thedefault w eb interface is show n inPhoto 2.

Other programs communicate withMH through TCP /IP sockets or viacomm ands in a f ile . The “ Hardw areInterfaces” sidebar show s t he various

interfaces that MH currently supports.

A QUICK LESSON IN PERLAll HA programs have some sort of

programming language built in forevent programming. Instead of imple-ment ing a new event-control language,I used Perl.

Perl is a powerful language and itcan take quite a w hile to learn all ofits tricks. But , by u sing object-ori-ented programming and extending it

w ith H A-related functions, MH hidesmuch of the complexity. Listing 1 isan event for turning on an X-10-con-trolled light half an hour after sunset.

Before I go on, I w ant to cov er afew ba sic Perl synt ax rules. All vari-ables star t with a . Strings are quotedw ith eith er single or double quot es. Usedouble quotes if you w ant v ariableswithin the str ing to be substi tuted.

Com mands beg in w i th and com-mands end with a semicolon. Do loops

and condit ional blocks star t and endw i t h . There are tw o w ays to do statements—

and .tests are (or ) for num eric dataand (or ) for string dat a.

Local variables are declared w iththe function called . Object methods(e.g., ) can be specified in tw o w ays:

Listing 1—This code will turn on an X-10 module set to address O5 and speak the time 30 min. after sunset.Note how the function can handle time offsets and the variable will get substi- tuted on-the-fly.

Listing 2—This code shows how incoming caller-ID data and outgoing phone numbers are spoken and logged.

Page 11: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 11/6814 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

By looking at the examples suppliedw ith t he MH package, you can learnwhat you need to know about Perl forits use in MH. Another good startingpoint is w w w .perl.com. The referencebook of choice is Program m in g Perl . Ifyou want to know how to do somethingin particular, Th e Perl C ookb ook isexcellent.

THE TALKING PHONEEnough background, it’s time for

an example! If you’re going to haveyour house talk to you effectively,you can either give it a really loudvoice or you can use a house PA sys-tem w ith a speaker in key rooms.

But what i f you want to have aconversation w ith your house in theliving room while your spouse is try-ing to sleep in th e bedroom? You caneith er get h im /her a nic e set of earplugsor you can in sert a com puter-controlledrelay card betw een the PA amplifier andth e speakers, as show n in Figure 1.

The digit al I/O ca rd is an i nexpen-sive ($30) PIC -based ca rd av aila blefrom Weeder Technologies. The relaycard is a Universal Relay Card fromJameco ($100). By modifying

, you can define w hich roomis controlled by w hich relay.

Now you can direct speech to t heroom of your choice, using either ofthe following formats:

The other t w o Weeder cards show nin Figure 1 let you monitor outgoing andincoming phone numbers. The DTMFcard detects a ny pressed phone keys,and t he caller-ID card decodes the nam eand number of incoming calls. If youhave a caller-ID-capable modem, you

can use it instead. By sensing w hen themodem is not in use, MH can sharethis m odem w ith other programs.

The code in Listing 2 monitors thedata com ing from t hese tw o cards.

The Weeder kits have a simple proto-col that uses the first character of astr ing to indicate w hich card is send-ing data: “ I” is for the caller-ID cardand “ O” is for the D TMF card. The MHcode detects these codes and stores theincoming data in the and

objects.The string is

parsed by the function, w hich changes

the phonebook-formatted name into amore pronounceable name. For example,it changes “ WINTER BRU C E LA” into“ Bruce Winter” by sw apping fields anddropping initials and abbreviations.

If the caller’s area code differs fromyours, this code uses a lookup table toadd the city or state that the call isfrom. Optionally, it w ill use a u ser-

defined rule to replace the receivedname with a more phonetically correctname or a prerecorded file.

and are logged into monthly log

files that can be retrieved and displayedby . The Tk interfacefor this feature is shown in Phot o 3.

The caller-ID signal is sent bet w eenthe first and second rings. In order togive MH a chance to decode and speakthe caller-ID information before the

phones start ringing, a ring morpher isinserted betw een the external phoneline and the other phones in the house.

The ring m orpher has the sideeffect of delaying the ring by one

Figure 1—The computer’s sound card drives the house PA speakers through a relay card controlled by a digital I/O interface. The phone line is monitored with DTMF and caller-ID cards.

Serialport

Soundcard

Computerspeakers

DTMFdecoder

Phoneline

Caller ID PA

amplifier

Digital I/O Relay

card

Speaker1

Speaker...

Speaker8

+12 V

Hardware InterfacesCM11— The Activ eHom e kit ($50) includes a t w o-

w ay X-10 C M11 interface, lamp m odule, and acouple of remote controllers.

Weeder kits— Weeder Technologies offers t he follow -

ing PIC kits, priced from $30 to $50 each:• tw o-w ay X-10 interface• 12-bit digital I /O (can be input or output, sw itch

or bu t ton)• 8-port an alog I/O, 10-bit resolution• ca l ler ID : name and number• ou tgo ing DTMF phone moni to r

These kits are good for PCs with a l imited numberof serial ports because they can all share th e sameserial port.

JDS— Currently, only the two-way X-10 interface hasbeen tested.

WX200/198 weather stations— These w eather stat ions areavailable from Radio Shack a nd m ail-order cata logs,ranging in price from $200 to $300. They monitorindoor/outdoor t emperatu re, hum idity, barometr ic

pressure, w ind speed and direction, w ind chil l , andra in fa l l am ounts .Modem— Using the method, a caller-ID-

capable modem can be shared w ith other program s. I tcan also be used to send messages to pagers.

Ham radio TNC modem— Using a ham receiver at tachedto a radio modem (terminal node controller), MH canmonitor packet radio traffic. This information includeslocations and speed of cars equipped wit h G PS devicesand w eather in fo rmat ion f rom home w eather sta t ions .

Other serial devices— The object can readand write to any ser ial ly connect device, such as an IRcontroller or robotic interface.

Page 12: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 12/6816 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

cycle. This delay allows us tohear the caller-ID announce-m ent (e.g., “ phone call from BillCl in ton” ) a t t he same t im e thephones start to ring.

OTHER EXAMPLE EVENTSHere are a few of the events

w e use to cont rol our house.You can find them online (seeth e Softw are section).

I have window quil t curtainshooked up to pulleys attachedto 24-V DC motors and a set ofrelays. Each curtain has t w orelays—on/off an d up/dow n.These relays are driven eitherby local sw itches or by WeederDIO outputs.monit ors the outside tempera-

ture and sunlight levels using aWeeder analog kit, and opens orcloses the south-facing curtainsto m aximize solar heat gain inthe w in ter months.

The m odules display and/or speak fun fa ctsfrom various databases. It certainlymakes breakfast entertaining!

monitors dooropenings and closings using magneticreed relay s connect ed to Weeder D IO

inputs. Do your kids leave outside doorsopen? This code issues a friendly re-minder to close the door using theoutside PA speaker. It w ill also closethe garage door at night, but only afterit senses no movement in the garage.

I t also monitors movements inhallw ays and st airway s using X-10

Photo 2—This mirrors the Tk interface, but includes an authorization password to allow secure access over the Internet.

Photo 1—The bottom two frames are logs of what has been spoken and logged. The upper left frame is a searchable list of commands.

movement sensors. When doorsopen and close or people aresensed in key areas, I have MHplay short, unobtrusive soundsso I can t ell w here people aregoing—sort of like a high-techsqueaky door!

retrievesand processes pages off the w eb(e.g., Letterman’s top 10 list, localw eather conditions). It also setsthe clock according to an Inter-net-connected atomic clock.

Theevent uses a background processto call the script,w hich checks w ho has sent youma il in specified e-ma il boxes.After the process has finished,MH announces what new e-mail

you received and from w hom.U sing a u ser-specified IP

socket port, lets youuse a telnet program to log in,

specify an optional password, and issuecommands.

Like a kitchen timer,

periodically tells how m any seconds,minutes, and hours are left on yourt imer.

A ham-radio enthusiast w rote the

code . Using a GP S unit ,a pair of radios, and TNCs (terminalnode controllers), this code tracks andannounces his car’s position and speed.Using an optional position file, itannounces posit ion w ith respect tovarious landm arks (e.g., “ D ad’s carhas just lef t t he IBM parking lot” or“ Junior’s car is parked at lover’s lane” ).

This code does other nifty thingsw ith packet radio (e.g., m onitor currentw eather conditions from t he nearest

packet radio–connected weat her stat ion.Using the script in abackground process,collects customized TV programmingfrom the Internet to local files. It addsa “ program the VCR” bu t ton to theTV grid entry, so y ou can not only seewhat’s on but also instruct MH to createan event to star t and stop the VC R ata certain t ime for th e specified channel.

reads data from a WX200

or WM918 w eather stat ion. It th en logs,displays, and optionally speaks the data.

Page 13: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 13/68 CIRCUIT CELLAR ® Issue 111 October 1999 19www.circuitcellar.com

SOFTWARESoftw are for the Mist erHouse appli-cation is available via the Circu i t

Cel lar w eb site, m isterhouse.net,and misterhouse.w ebjum p.com.

Bruce Win ter designs int egrated cir- cuit s as a seni or engin eer at I BM in Rochester, MN . Thi s has nothi ng to do wi t h home au tom at ion , bu t i t sound s im pressiv e in a bi o. You m ay reach h im at bru ce@m isterhouse.net.

Photo 3—The function shows incoming calls, outgoing calls, a list of all past callers, and a pick list of the logs for each month.

JOIN THE FUN!Even if you don’t ha ve any of the

hardw are currently supported, you can

sti l l run MH and play around with thew eb, Tk, VR, and TTS int erfaces.

The f i le has theinstallation instructions. ha sdocumentation on the various objects,methods, and functions, and

contains a l ist of updates. has all the source

code, support files, and documentation.If you don’t have Perl installed, you’llneed or

, which have the platform-

dependent compiled versions of MH.D epending on how many events you

load and if you have the Tk interfaceturned on or not, MH w ill use from 5to 15 MB of memory. At ten passes persecond, it uses about 30% of the CPUcycles of a 100-MH z Pentium C PU .

So, dust off that old PC , give yourhouse a little personality, and comejoin the open-source movement andmake t he w orld a bett er place! Or atleast have your house train your kids

to keep the back door closed.I

RESOURCEST. Christiansen and N. Torkington,

Th e Perl C ookb ook , O’Reilly,Sebastopol, CA, 1998.MH events for author ’s house,

m ist erhous e.net /m h/code/BruceMailing l ist , www.onel is t .com/

subscribe.cgi/m isterhouse, w w w .onelist .com /archiv es.cgi/misterhouse

L. Wall, T. Christiansen, and R.Schwartz, Program m in g Perl ,O’Reilly, Sebastopol, CA, 1996.

SOURCESDigital I/O cardWeeder Technologies(850) 863-5723www.we e d te c h .c o m

Universal Relay CardJameco(800) 536-4316(415) 592-8097Fax: (415) 592-2503www. ja m e c o .c o m

TTS and VR engines

w w w .microsoft .com/ii t /dow nload/ speechengines.htm

Text-to-speech with Festivalw w w .cstr.ed.ac .uk/projects/festiv al

ActiveHome kitX10 (U SA), In c.(800) 675-3044www.x 1 0 .c o m

InterfacesJDS Techno logies(858) 486-8787

Fax: (858) 486-8789w w w .jdstechnologies.com

Page 14: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 14/68

20 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

The Java Virtual Machine

FEATUREARTICLE

Dave Lyons

iIs dependability morevaluable than speed?When James Gosling

created Java, hethought so. Daveagrees and wants toshow us the JavaVirtual Machine andhow easy and howconvenient workingwith Java can be.

n 1991, JamesG osling w as develop-

ing a new programminglanguage for use in intelli-

gent consumer devices. He started w ithC+ + but realized that no num ber ofextensions to t he language w ould meetthe requirements. Because intelligentdevices need a w ide variety of OSs and

processor fam ilies, the new languageneeded to be machine independent.

G osling designed a language wh erethe source code w as compiled intoma chine code targeted at an abstractprocessor. Applications w ouldn’t ha veto be recoded or even recompiled. Onlythe code that implemented the abstractprocessor wou ld hav e to be ported.G osling named his new language Oakafter the tree outside his window .

Oak w as object oriented and pro-

grams were composed of classes andinterfaces. An interface defines a setof methods that a class can implement.This approach allow s much of thefunctionali ty of C++’s multiple inher-i tance without the runtime overhead.

The Oak syntax w as similar to Cand C + + . A handful of basic typesw ere provided including , ,

, , (an unsigned 16-bitvalue), , , and .

The sizes of these basic t ypes w ereexplicitly defined so that Oak applica-tions w ould behave consistently a cross

various platforms. Floating-pointfuncti onalit y w as based on the IEEE-754 standard and w as explicitly de-fined so programmers could preciselypredict behavior.

In developing Oak, G osling deter-mined that rel iabil i ty was more im-portant than speed. Consumers expectappliances such as VCRs, telephones,and toasters to w ork. They w ouldn’ttolerate a product that needed to berebooted. Several aspects of O ak’sdesign reflected the reliability issue.

Objects in Oak w ere allocat edusing the operator but w ere onlyreturned to the heap w hen the garbagecollector determ ined that t here w ereno longer any references to th e object.

Oak also avoided the problem ofusing variables before they w ere ini-

tialized by rigorously checking to besure that all variables inside an Oakmet hod w ere set beforehand. A used-before-set condition resulted in a fatalcompiler error. And, perhaps the m ostsignificant reliability-related change—there w ere no pointers in Oak.

OAK BECOMES JAVAAs tim e passed, Sun’s G reen

project (later spun off as FirstPerson,Inc.) w as shut dow n w hen no market

could be found for the technology. Ata group meeting, G osling, along w ithother Sun notables such as Bill Joyand John G age, recognized that theInternet had recently been made moreaccessible by w ay of w eb brow sersand that i t w as a good f i t for the tech-nology embodied by Oak.

The Internet moved media such astext, audio, and graphics to variousplatforms. With Oak, application codecould be moved in the same w ay.

The goals Gosling had set out t oaccomplish f i t perfectly with the wayapplications w ere being w ritt en, de-livered, and used on the Internet.Although the discovery w as quiteaccidental , i t appeared tha t t he Oak/Internet combinat ion had potential .

Oak w as eventually renamed Javaand a web browser called HotJava wasw ritt en in the language. This browser,besides being able to display standardw eb pages conta ining text an d graph-ics, also permitted small applications(applets) to be embedded in pages.

Page 15: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 15/68

CIRCUIT CELLAR ® Issue 111 October 1999 21www.circuitcellar.com

Userprogram

class files

Java APIclass files

Class loader

The JavaVirtual Machine

Internal class representation(includes bytecodes)

Execution engine

Java API native methods

Host operating system

Sun decided to make Java and H ot-Java freely a vailable and in doing so, setin motion a new style of computingthat seems to be gaining momentum.

ABSTRACT PROCESSORFrom the beginning, a number of

companies licensed the source to Javaand began porting it to their plat-forms. This effort involved more thansimply porting the abstract processor,know n as the Java Vir tual Machine(JVM). Although the term JVM de-scribes the Java interpreter, it alsodescribes the entire platform.

The comprehensive set of APIsdefined as part of Java al so needed tobe ported to t he new platform. TheseAPIs defined standard mechanisms forgraphics and w indow ing, file storage,

and netw ork access.Figure 1 illustrates the Java run-

tim e environment. U ser programs andthe bulk of the Java API reside in classfiles wh ich t he class loader checks forcorrectness before use. The executionengine (also called the JVM) interpretsthe code loaded from the class files.

The JVM is stack-based and definesfour 32-bit -w ide registers—the programcounter, top of stack, current stackframe, and local variables pointer. In-

structions for the JVM consist of a one-byte opcode follow ed by zero or moreoperands. The instructions vary incomplexity from simply pushing aconstant onto the stack t o allocating amultidimensional array of objects.

The JVM is also able t o m ake callsto native methods, which are imple-mented in a na tive system language,typ ica l ly C or C+ + . Nat ive methodsare used to interface to the underlyingOS, but t hey can be used in other

situations as well .For example, native code might beused by an application for computa-tionally intense code such as decodingmotion video. Native methods canalso be used to create a Java w rapperfor large, existing code bases.

Although a certain number of nativemethods are needed for almost all Javaimplementations, they should be usedwith discretion. A Java application thatrelies directly on the native methodscan no longer be run on all Java plat-forms without porting the native code.

This portabilit y (or as Suncalls it, “ Write once, run any-w here” ) is key to Java’s ap-peal, so Sun created a programcalled 100% Pure Java. To becertified 100% Pure, an appli-cation can be m ade up ofonly Java bytecodes.

THE PERFORMANCE KEYIt’s not hard to imagine that

the key t o executing Java codequickly lies in the bytecodeinterpreter. There’s a good dealof supporting code involved inthings like garbage collection,class loading, and interfacingwith the underlying operatingsystem, but m ost of the t im eis spent interpreting the byte-

codes. Because of this, mostefforts to improve Java per-formance have focused onspeeding up the interpreting process.

The simplest w ay of speeding upthe bytecode interpreter is to hand-code the interpreter loop in nativeassembly language. This approachoften results in a smaller interpreter,w hich takes advantage of modernmicroprocessor cache as w ell as in-struction pipelining. Writing the

bytecode interpreter in assembly lan-guage can increase the speed tw ofold.

A larger performa nce gain ca n beachieved by using a just-in-time com-piler (JIT). A JIT converts the Javabytecodes to native m achine code atruntime, resulting in speed increaseson the order of 10 ×, w hich is helpfulfor computationally intense code.

However, a JIT can result in aspeed decrease w hen t here’s a la rgeamount of code that isn’t executed

frequently. This setback is because ofthe overhead of converting the Javabytecodes to native code.

A refinement on the JIT approach isSun’s HotSpot t echnology. The Hot -Spot int erpreter identifies areas ofcode that are frequently used andfocuses its attention there.

Methods tha t are frequently calledcan be inlined and the code insidemethods can be optimized becausemuch m ore informat ion about a pro-gram is available at runtime than atcompile t im e, which is w here optim i-

zations ha ve tradit ionally been done.Although no concrete performancenumbers have been published, Sunhopes HotSpot w ill enable Java perfor-mance to approach tha t o f C+ + .

HARDWARE CONSIDERATIONSThe byt ecode interpreter plays a large

role in determining the performance of

Java on a part icular platform, but theunderlying hardw are also plays a sig-nifica nt role. A processor wit h a highclock rate m ay not perform as w ell as aslow er processor w ith a la rger cache.

Although t rue in general, executingJava code magnifies the difference be-cause so much t ime is spent in t herelatively small bytecode interpreter.The effect w ould not be as pronouncedif a JIT or HotSpot-based interpreterw as used. A byt ecode int erpreter that

f i ts entirely int o cache could drama ti-cally affect Java performance.Floating-point support can also be

significant in determining Java perfor-ma nce on a platform. Processors wit h-out float ing-point hardw are process theJava floating-point instructions up to10 × slow er th an sim ilar processorsw ith hardw are floatin g-point support.

The problem is compounded by thefact that processors lacking floating-point support a re typically low er horse-pow er chips aimed at consum er devices.Application programmers should take

Figure 1— The class loader converts Java code files into a form usable by the execution engine. The underlying operating system services such as networking and graphics are accessed through native methods in the Java API.

Page 16: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 16/68

CIRCUIT CELLAR ® Issue 111 October 1999 23www.circuitcellar.com

note of this situation. If a piece ofcode is targeted at consumer devicessuch as th ose based on the new Per-sonalJava platform, floating-pointusage should be kept t o a m inimum .

ULTIMATE JAVA PLATFORM?I t may seem that the obvious an-

sw er to t he Java perform ance questionis to build a JVM in hardw are. Sun hasdone just that with their picoJava ar-chitecture, w hich uses Java bytecodesas its na tive language.

The architecture is also designed tooptimize access to the Java stack. Eventhough these Java chips may seem likethe obvious choice, m any consumerelectronics manufacturers that arebuilding Java into their devices arechoosing other microprocessor families.

In the consumer electronics busi-ness, a difference of a few dollars inthe price of a m icroprocessor canmake a hu ge impact on t he economicviability of a consumer product. If oneprocessor includes built-in peripheraldevices such as serial ports or an LCDdriver at a low er price than a com pet-ing chip, a difference in executionspeed may become inconsequential incomparison to the difference in price.

Java chips may offer the best per-

formance, but w hen a t echnology l ikeHot Spot narrow s the gap betw een hard-ware and software implementations,choosing a microprocessor for a Java-based device becomes complicated. Inthe end, the success of Java-based de-vices may be determined by factorsbesides just the technical aspects. I

D ave Lyon s is a softw are archit ect at M icroware System s. D urin g his 12 years there, he has w orked w it h f i le

system s, bootin g m echani sms, and developm ent tools . Current l y, D ave is focused on th e com pany’s port of PersonalJava for O S-9. You m ay reach hi m at d avel@m icrow are.com

SOURCE Java Virtual MachineSun Microsystems(800) 786-7638(408) 276-5200

Fax: (408) 276-0633www. ja v a . su n .c o m

Page 17: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 17/6824 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

A Versatile Timer/ Synchronizer

FEATUREARTICLE

Brian Millier

sYou may not be able

to teach an old dognew tricks, but youcan use Visual Basicto train a group ofcounter/timer devices.Brian shows us how

to make a freestand-ing device that canread, write, load, andeven learn new tricks.

ince the ’50s,science fiction has

featured robots thatlook human or exhibit

human traits. Such devices rarely

existed outside of Disneyland but arenow becoming commonplace on thefactory floor. These specialized robotscan be trained by human operators todo assigned tasks w ith l i t t le outsideintervention.

This project follow s the sam e phi-losophy as the indust rial robot, just ona smaller scale. At its heart is a groupof count er/tim er devices controlled bya PIC16F84. Training the device (i.e.,setting the configuration and timing

parameters of all the timermodules) is done w ith aWindow s-based programrunning on a PC .

After you choose a con-f iguration, you dow nloadthe data via a ser ial port tothe PIC16F84. The deviceis now a freestanding unit ,producing all the t im ingsignals, synchronized trig-gers, and everything elseneeded for the application.Only if you needed to

change the tim ing parameters or con-figuration must the device be recon-nected to the PC .

The C TS9513 w as designed t oprovide a master timing synchronizerand pulse generator for a laser-basedresearch instrument. Like most cus-tom research equipment, t he actualrequirements w eren’t w ell-know n inadvance. In t he past , similar si tua-tions have led to time-consumingredesigns. This t im e, I built a generaldevice using tw o C TS9513 count er/timer devices (see Figure 1).

Each CTS9513 contains a five-stagescaler and five 16-bit timing modulesthat can be programm ed to handledivide-by- n , delay, or PWM functions.Many of the clocking and gating int er-connections among the t iming mod-

ules can be configured in softw are andmany addit ional interconnection per-mutations can be handled by jumpers.

In addit ion to the two scalablequartz oscillator clock sources is apow er-line zero-crossing trigger (60 or120 Hz), as w ell as provision for anexternal clock source. Eight of th e 10timing modules are buffered and rout-ed to BNC outputs that can be set toproduce eith er active-high or act ive-low output s (see Photo 1).

Although the CTS9513 is rated at amaximum count rate of 20 MHz, Ichose a 16-MHz quartz oscillator,providing 0.0625-µs resolution (ad-equate for my application). By substi-tut ing an AMD AM9513, you can usea qua rtz crystal instead of an oscil la-tor module, but the maximum clockfrequency is 7 MHz.

In Circu i t C el l a r 78, I described aportable pulse generator based on a nAM9513 tha t generated v arious user-

Photo 1—

Without all the connectors along the rear panel, the circuit would fit into something smaller than a 19 ″ 1U rack cabinet.

Page 18: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 18/68www.circuitcellar.com CIRCUIT CELLAR ® Issue 111 October 1999 25

defined pulse trains, but thetimer configuration wasfixed in firmw are.

This time, I used the’16F84 as the controller chip.This $5 mi cro ha s enou gh I/Olines to control tw o C TS-9513 timers, a serial link tothe host PC, and a status LED.

The P IC’s biggest sellingpoint has to be its flashmemory, which lets i t holdall t he configuration andtiming parameters for twoCTS9513s in nonvolatilememory. So once pro-grammed, the unit works asa freestanding device. Flash memorylets parameter changes be made quickly.

D eveloping the program code went

quicker because I didn’t have to wait fora U V erasure of the device w ith eachcode modification. Although the ’16F84doesn’t contain a U ART function, i t’sfast enough t o im plement a 9600-bpsserial input funct ion in softw are.

The C TS9513s go for aroun d $30and th e total chip cost for the circuitis about $80—quit e reasonable consid-ering the unit’s capabilities.

HARDWARE DESCRIPTIONI broke up the circuit diagram into

tw o parts. Figure 2 show s the control-ler, tim er IC s, power supply, serialport, and everything else needed. Notetha t I used one AM9513 and one C TS-9513 to show the different clock cir-cuit needed for each device. Apartfrom that, programming the devices isthe same. U se what ever device youhave available.

Figure 3 shows the in put clock/gateselection circuitry as w ell as the out-

put buffering and polarity selectioncircuits. Depending on your applica-tion, t he circuitry show n in Figure 3could be different . For exam ple, theoptocoupled inputs and 50- Ω outputdrivers (necessary in the noisy envi -ronment m y unit encounters) may notbe necessary in your application.

Q1 and the associated parts convertthe R S-232 serial dat a from th e hostint o TTL levels, wh ich is fed intoRA0 of th e ’16F84. Softw are routinesin t he micro convert the ser ial data -stream into parallel form. N otice that

there’s no hardw are handshaking. Thehost application paces its t ransmissionof parameters to match the ’16F84’s

response tim e, which is lim ited bythe f lash-mem ory w rite cycle t ime.

I tied th e Rx and Tx pins of theDE-9 socket together so all incomingcharacters are echoed back to the PC.This setup made it easier to trouble-shoot early in t he design, w hen I wasusing a terminal program to send thecomm ands and parameters. My prob-lem w as remem bering to send theupper-case command mnemonics thePIC f irmw are expects!

Port pins RA1–RA3 provide t hecontrol signals for the ’9513 devices.The CTS9513 uses a data-pointerarchitect ure to access its 30+ regis-ters, so only a *WR line is n eeded foreach device (along with a shared com-m and /*da ta line). This design nev erreads the ’9513’s registers, so the *RDline is tied high and the RA4 linedrives a status LED, w hich is de-scribed la ter.

Port B is programmed as an output

port to provide the 8-bit data bus forthe ’9513s. Notice that these devicesactu ally have a 16-bit bus. The uppereight bits mu st be t ied high and acomm and sent to t he device to enableit to operate in the 8-bit mode.

The pow er supply is convent ionalexcept that the bridge rectifier acts asboth t he full-w ave rectifier for thepow er supply and provides 120-Hzunfiltered DC to optocoupler U3 forthe zero-crossing detector circuit. Aseparat e diode, D 2, is used if 60-H zzero-crossing is needed.

The zero-crossing detectoris a simple MOC5009 optodevice wit h a Schmit t t r iggeron the detection side to re-ject AC line noise. As config-ured, this circuit provides atrigger wh ose rising edgeleads th e AC zero-crossingby about 0.4 ms (slightlydependent on the AC lineamplitude). Although a high-gain comparator can be usedto sense the true AC linezero-crossing, it w ould besusceptible to line noise,which this circuit isn’t .

By feeding the PIC’s*MCLR from the *RESET output of aLM2925T, I delayed the PIC’s startupby 0.5 s after pow erup. This setup

ensures stabilit y w hen the C TS9513sare loaded, w hich is important be-cause they are only loaded at pow er-up. I used the LM 2925T, but you canuse a conventional ’7805 and put acapacitor to ground on the *M C LRline instead.

The gating and output circuitry inFigure 3 is prett y straight forw ard. Ichose ’74128 50- Ω driver devices be-cause they provide TTL-level signalsw ith lots of drive for opto-couplers

and are more robust w hen drivinglong cables that pick up inductivenoise. The 74LS86 XOR gat e allow sfor output polarity selection, as w ellas taking care of the inversion thatoccurs in the ’74128 buffers.

THE PIC FIRMWAREThe PIC16F84’s sparse instruction

set, although adequate for my project,makes programming in assemblyquite tedious. I just can’t force myself

to use C with small micros contain-ing only a few kilobytes of memory

Clock

Clock

PIC16F84RS-232

C T S 9 5 1 3 # 1

C T S 9 5 1 3 # 2

B u

f f e r s

B u

f f e r s

Outputs1–5

Outputs6–8

Figure 1— It doesn’t seem fair that a modest little PIC chip is telling those two counter/timer chips what to do.

Photo 2— Configuring each timer section is accomplished from the main screen of the Visual Basic host program.

Page 19: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 19/68www.circuitcellar.com CIRCUIT CELLAR ® Issue 111 October 1999 27

Figure 2— In my prototype, one each of the CTS9513 and AM9513 chips were used to demon- strate their compatibility (translation: I had one of each in my parts cabinet).

for apps involvingtime-cri t ical bit ma-nipulation of ports.

The firmw are con-sists of:

• 9600-bps serial da tainput routine, using asoftware UART

• s imple commandmnem onic parsingroutine

• d a t a EEPROM w ri t -ing/reading rout ines

• ’9513 setup and reg-ister-loading routine

When writing codefor a small device w ithfew debugging facili-

ties, it makes sense todevelop general soft-w are routines to assistin debugging. So, alongw ith t he necessaryprogram code, thefirmw are also containsroutines to write to any dataEEPROM location, read any EEPROMlocation by sending i t out t o Port B,and m anually load any of the ’9513register(s) via serial port.

Because of limited RAM space inthe ’16F84, the 58 parameter bytes inthe ’9513 tha t are down loaded to thePIC must be stored immediately tothe PIC’s 64-byte EEPROM data mem-ory. The EEPROM write cycle isaround 10 ms, so the host PC applica-t ion must “ pace” t he download toallow for this condit ion. I w anted a9600-bps routine for other projects,w hich explains m y choice of 9600 bpsrather than a much slower rate, which

w ouldn’t hav e needed any pacing.The correct operation of the ’9513timer modules depends on their re-ceiving the correct parameters atpow erup, so I w ant ed to incorporatesome checks to ensure that theEEPROM data had not been corrupted.

The PIC16F84 has a number offeatures built in to prevent EEPROMdata corruption, but I’m a skeptic.Therefore, the 58 bytes of dat a t hatm ake up th e ’9513’s param eter/con-figuration data are supplemented by asingle checksum byte, w hich is calcu-

lated by the host application programand sent along w ith t he rest of thedownloaded data.

Immediately af t er a dow nload (andat each pow erup), a checksum ca lcula-

t ion is done on the data EEPROMarray. If an error is found, t he check-sum LED remains lit (it’s turned onduring a dow nload and flickers duringthe checksum t esting at pow erup).

USER INTERFACEI’m a big fan of Visual Basic and still

find that the professional V.3 handlesmy needs w ithout generating hugeprogram files and loading too manysupport files into the end user’s Win-

dows directory like the new versions do.Photo 2 show s the program in ac-tion. The first t ime t he program runs, aprompt appears to specify which COMport the project is connected to. That’sabout the extent of setup requirements.

When configuring a ’9513, I recom-mend that you thoroughly study thedatasheet (available on the Celeritousw eb site). Although you ca n still getthe AM9513, it has been discontinuedso its databook is no longer available.How ever, th e AM9513 is similar t othe C TS part so the C TS datasheet can

be used for configura-tion purposes.

The first stage ofsetup is to init ial ize thedevice by putt ing i t in to8-bit mode and to preparethe five count er/tim ersfor loading. Becausethis process is done bythe PIC f irmware, youneedn’t be concernedw it h i t. If you’re using a’9513 and are unfamiliarwith the part, you mightwant to look over myPIC code listing.

Second, configurethe Master Mode regis-ter (using th e frame atthe right in Photo 2) to

select binary/BCD divi-sion ratios for the scaler,select an Fout source,and so on. Becauseth ere are tw o ’9513devices in this project,there are buttons to

swi tch be tw een the tw o Master Moderegisters. Press the “ save MM configu-ration” button w hen you are f inished.

C ertain bits of t he Master Moderegister must be set properly for the PIC

firmware to work. The host PC pro-gram doesn’t allow access to t hese bits.

Last , configure as many of the ninecount er/tim er modules a s necessary.Even though there are 10 modu les inth e tw o ’9513 devices, there’s onlyenough room in t he ’16F84’s dataEEPROM for nine module’s w orth ofparameters.

The output buffers are in a quadconfiguration, but I only w ired eightof the timers to output buffers. Mod-

ule nine can only be used to feed an-other t imer m odule.To com plete a coun ter/tim er con-

figuration, select a m odule from thepull-down menu. Notice that all of theselections are grayed out until theselected m odule’s configurat ion issaved by pressing the “ save currentconfiguration” button.

When the proper module is dis-played, choose the desired mode. Thereare 24 modes, but many of themaren’t applicable in a circuit such asthe one used in this project.

Page 20: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 20/6828 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Modes that perform a divide-by -n , generat e a delayed pulse, orperform PWM functions areapplicable. When selected, amessage box describing thatmode appears. Pick a mode, thenchoose the clock source andactive edge for the clock.

If the selected m ode requiresgating, a gate frame appears. Notall gating options apply to allmodes, so only the applicableones are enabled.

For all of the modes, a countmust be entered into the LoadRegister win dow . The range is0–9999 in BC D and 65536 inBinary mode. C ertain modes alsorequire you to place a count inthe Hold Register window.

Next, choose the output m ode.Only High TC pulse and TC-toggledare useful in this design. High TCproduces a pulse (w idth = clock) ateach terminal count. The TC-toggledmode changes the state of the out putpin at each terminal count, whichproduces either a squa re wa ve or a

PWM w aveform, depending on them ode you have chosen. At pow erup,all ou tput flip-flops are reset, so t hesense of the PWM w aveforms is con-sistent at each powerup.

The two crystal or oscillator mod-ules you choose for each ’9513 device,are entered as the master clock fre-

quency. Setting these is only neces-sary if you plan on using the figuredisplayed in the “ Tim e per singlecount” w indow for t iming ca lcu la-t ions .

After the Master Mode registers areset up, and all n ecessary coun ter/tim ermodules configured, th e data can be

Figure 3— To work in a noisy environment with long inter- connecting cables, I used a fancier I/O scheme than just TTL-compatible gates.

Gate 1Gate 2Gate 3Gate 4Gate 5

Out 1Out 2Out 3Out 4Out 560/120 HzEXT Gate 1EXT Gate 2

Gate 6

Gate 7Gate 8Gate 9

Out 6Out 7Out 8Out 9

60/120 HzEXT Gate 1EXT Gate 2

Gate jumper array

Page 21: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 21/68

Page 22: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 22/6830 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Calling on the Standards

FEATUREARTICLE

Arthur J. Carlson

mModem testing maybe about as excitingas putting up high-

way mile markers inNevada, but in thelong run it will beworth your time. Getin on this hand asArthur deals out infor-

mation on modemtesting standards.

odem testingcan be bewildering

to O EMs w hose pri-mary business doesn’t

include designing modems. Fortu-nately, modem test standards TSB 37-A and TSB 38 provide consistent a nduniform criteria to compare the per-forman ce of modems. Draft digital

standa rds PN 3857 and PN 3856 ex-tend these concepts to PCM modems.

In this article, I describe variousfacets of performance testing andreview the role of testing in the mo-dem design process. I also give infor-mat ion on the stat ist ics of the TSB37-A/PN 3857 netw ork m odels and anout line of th e role of TSB 38/PN 3856.The article includes examples of typi-cal modem performance curves anddescribes how they can be interpreted.

Standards tell part of the story, butad hoc testing and customer feedbackare important components of a w ell-designed modem product. OEMs shouldexpect their modem vendors to follow a comprehensive testing program thatincludes all three types of testing.

FOR EXAMPLE,Your latest a ssignment is to add an

embedded voiceband modem to yourcompany’s nifty hand-held PersonalPeppy Pu ppy (PP P) product in order toleap ahead of the competition.

You study brochures from everymodem vendor in the Thomas Registerlooking for the right fit for your uniquerequirements. Each vendor heraldstheir modem’s advanced technology,reliable operation, unsurpassed perfor-mance, low cost , instant availabil i ty,att ractive color scheme, and easy pay-ment plan. They all sound good.

All the demo boards behave aboutthe same. The so-called 56-kbps mo-dems conn ect at speeds betw een 38,666and 46,666 bps at different times of theday, probably depending on unknow-able random phenomena in the tele-phone netw ork and your ISP. Besides,modem speed isn’t important becausethe Internet is pretty slow anyway.

You recomm end tw o vendors, pur-chasing negotiates a deal, and you

start your design. The advertising slo-gan, “ Put more bark in your PeppyPuppy,” becomes the company’s rally-ing cry. You enter the beta phase tw ow eeks ahead of schedule. You’re a hero.

That ’s w hen all hell breaks loose.Every beta site north of the Rio Alphaand w est of the C happanoes reportsconnection failure rates exceeding25%. The CEO w ants t o talk t o you.How did you select those modemvendors, anyw ay?

You w ake up in a cold sweat. I t’sthat same old nightmare.

ROLE OF MODEM TESTINGModem testing is the activity every-

one loves to hate. But if you’re goingto av oid the Peppy Puppy nightmares,you’d better do your homew ork.

Modems are complicated and thenetw orks they run on have complica-t ions of their own. Even Murphy hasno idea of how many things can go

w rong, but your customers will f indout soon enough if you’re not diligent.You have no choice but to design

your products as w ell as you can andthen test the heck out of them.

Boring standards such as V.90 andV.34 dictate the basic requirements ofa m odem design. But conforming t othose standards is only the first rungof the product design ladder. Design-ers must subject new V.90 modemmodules to a variety of tests beforethey can confirm t hat the design isw orthy of production.

M aking Sure Your Modem C anC ommunic a t e

Page 23: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 23/68 CIRCUIT CELLAR ® Issue 111 October 1999 31www.circuitcellar.com

Several levels of re-quirements m ust be met.Your modem must prop-erly interwork with everymodem already on themarket. Performancemu st be as good as theexisting m odems. And,your modem m ust beable to operate in various telephonenetwork environments that can in-clude PBXs, digital links, analog links,satellite hops, undersea cables, and hotcoffee spilled on the operator’s lap.

Indeed, the task of testing can bequite formidable. Additionally, ifCompany X tests i ts modems usingtest procedure A and if Company Ytests its modems using test procedureB, how will the OEM judge whether

modem X is better than m odem Y?

TESTING STANDARDSEnter testing standards. The Tele-

comm unications Industry Association(TIA) has w orked for several y ears t oevolve a rational set of modem testprocedures. The lat est official testdocum ents w ere published in 1994,and an update is in the w orks.

These documents introduced theconcept of netw ork coverage. When

engineers use th e m odels and proce-dures defined in these documents, theresults are straight-up comparisons ofa given modem against an y oth ers.

After the testing in simulated envi-ronments is finished, there are stillthose pesky si tuat ions that come upw hen a new product ventures into thefield. Of course, there are no standardsfor testing at this level, but an OEMw ould do w ell to have assurance fromthe vendor that t he modem has been

successful in a w ide range of real-w orld environments.Once reports of field-related prob-

lems begin to come in, the modemvendor must have the know-how tounderstand t hem and make t he appro-priate changes in the modem design.Interesting wrinkles sometimes pop

up. After all not all design decisionsare made for good technical reasons.

Some modems produced by largemodem manufacturers don’t conformto the mandated standards. When thathappens, smaller vendors have to comeup with workarounds to successfullyinterw ork w ith th e big-nam e modems.

I recall the t im e my com pany’sV.32bis m odems experienced problemsat a certain ISP. The ISP w as using

modem s supplied by a Well-Know nModem C ompany (WKMC ). Our call-mode modems couldn’t connect withthe answer-mode WKMC modems andI wa s assigned to solve the problem.

I discovered that WKMC’s modemhad a subtle but definite mistake inits training sequence. Usually t heerror wou ldn’t cause difficulty, butone of the design choices in our mo-dem stepped right into the little crackexposed by WKMC’s error.

I called a senior engineer friend ofmine at WKMC who confirmed thattheir modem had a l i t t le mistake inthe training sequence. He referred meto a junior engineer who had w rit tentha t section of code. The junior engi-neer and I agreed that there was a prob-lem, and i t was my understandingtha t he w ould w ork on i t .

This w as too simple for m anage-ment t o comprehend though, and myVP soon called me in to ask what was

going on. He ha d received a phone callfrom the VP of engineering at WKMC.To bett er explain the situat ion, w escheduled a conference call involvingmy VP, WKMC ’s VP, and m yself.

To no one’s surprise, WKMC’s VPwas not impressed and he refused toacknowledge that there was anything

wrong with his modems.C ertainly he w asn’t anx-ious to upgrade the thou-sands of modems t hatWKMC had in the field.

After the call, my VPsuggested that I modifyour training sequence tow ork around WKMC ’s

error. It seemed like a good designdecision under the circumstances.

INTEROPERABILITYA w alk down the aisles of your

favorite electronics superstore w illillustrate that a large number of par-ticipants have entered the supply sideof the voiceband m odem market.

If you design a new m odem, one ofyour steps in qualifyin g the design is t o

take your company’s credit card, visitsaid electronics superstore, an d buy oneof every modem on the shelf. Then, setup interoperability tests of your modemw ith each of the competing modems.

Don’t forget to set up connections inall available modes (V.90, V.34, V.32bis,V.22bis, Bell 212, Bell 103, V.23, V.21).And, oh yes, don’t forget the fax modes(V.34, V.17, V.29, V.27ter, V.21).

PERFORMANCEThe definition of performance has

evolved along wit h m odem technol-ogy. Traditionally, modem perfor-m ance w as expressed as a curveshow ing error rate as a funct ion ofreceived signal-to-noise ratio.

Modem A was better than modemB if modem A achieved a given errorrate w ith a low er signal-to-noise ratiothan that required by M odem B. Be-cause error control has come to be anintegral part of their design, virtually

all m odems now perform error free.So m uch for error-rate com parison.Current standards define several

m easures of performa nce, one of w hichis throughput. Throughput is the rateat w hich user data flow s from t he inter-face of the transmitt ing modem to theinterface of the receiving modem.

Figure 2—There are two stages of D/A conversion between the server and the

client, which means that PCM connection is not possible.

Digitalnetwork

Digitalnetwork

Analogswitch

C O D E C

Hybrid Localloop

Clientmodem

Servermodem

C O D E C

Hybrid C O D E C

Hybrid

Digitalnetwork

Digitalnetwork

Digitalswitch

C O D E C

Hybrid Localloop

Analogimpairments

Digitalimpairments

Clientmodem

Servermodem

Figure 1—Only one D/A conversion exists between the server and the client. Each digital stage may add digital impairments such as RBS or a digital pad.

Page 24: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 24/6832 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Modems achieve error-free data

transmission by gathering user dataint o blocks encoded so an erroredblock can be detected by the receivingmodem. The receiving modem thenrequests a retransmission.

The detection and retransmissioneliminates m ost errors, but only bytrading off throughput. All other th ings

being equal, m odem A is better than

modem B if it has higher throughput.

CONNECTIVITYThe meaning of connectivity has

also evolved with advances in modemtechnology. Today’s modems nearlyalw ays connect, thanks to their multi-mode structu re. Typical m odems can

sw itch personalit ies to become V.90,V.34, or even V.32 or V.22 modems.

Most connections today are overchannels capable of supporting PCMoperation (e.g., V.90) at speeds beyond40 kbps. The connection bet w een theserver modem at an ISP and a clientmodem can go through several stagesof digital netw orks and sw itches.

Sometimes, a D LC even extendsthe digital network partway from thecentral office to the subscriber ’sneighborhood. If the w hole conglom-eration, star t ing w ith t he server mo-dem, is digital up t o a single COD ECw ith a nalog thereafter to t he clientmodem, then a PCM connection ispossible. Figure 1 illustrates a PCM-capable connection.

Some netw ork configurations con-

ta in m ore than one D /A–A/D stage, asshow n in Figure 2. When t his occurs,the condit ions that permit PCM op-erations are lost , and the modemsmust fall back to V.34 mode.

D uring their handshake, modemsdetermine whether a PCM connectionis possible. If it is possible, t he m o-

Table 1—Voice-band modem technology has advanced from 300 bps in the 1960s to modems that approach 56 kbps today (during which time the North American telephone network has evolved from 100% analog to nearly 100% digital). Here you can see how testing standards have kept up with these advances.

Standard title

Interface between data circuit-terminatingequipment (DCE) and the public switchtelephone network (PSTN)

Public switched telephone network trans-mission simulation for evaluating modemperformance

Telephone network transmission model forevaluating modem performance

Testing procedure for evaluation of two-wire 4-kHz voiceband duplex modems

North American telephone network trans-mission model for evaluating analog clientto digitally connected server modems

[Extension to TSB 38 to cover PCM modems]

Date Standard number

November 1989 EIA/TIA-496-A

February 1992 EIA/TIA TSB-37

October 1994 TIA/EIA TSB37-A

December 1994 TIA/EIA TSB38

February 1999 TIA PN 3857, Draft 10

Currently TIA PN 3856 (Draft)

Page 25: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 25/68 CIRCUIT CELLAR ® Issue 111 October 1999 33www.circuitcellar.com

dem determines how to cope with any

RBS and digital/analog pads that m aybe present. When in doubt, the mo-dem falls back to V.34.

Modems that take full advantage ofa PCM link are clearly superior tothose that fal l back to V.34 wit h i tsattendant reduction in speed.

HISTORY OF STANDARDSThe TIA/EIA devel oped s evera l

North American test ing standards tohelp compare modems. Table 1 pre-

sents a chronology of North Americanmodem test standards, and the “ G los-sary” sidebar conta ins TIA definitionsfor some key terms.

Modem testing began to be standard-ized i n 1989 w hen th e EIA/TIA pub-lished the 496-A standard. This standarddefined a sim ple telephone netw orkmodel that included a set of six testchann els representat ive of end office–to–end office telephone connections.

This connection model included

the effects of amplitude, delay distor-t ion, as well as white noise, and wasadequate for test ing modems withspeeds up to 2400 bps and modemssuch as V.22bis. Equipm ent ba sed onthe sta ndard w as used for testing V.32modems, but users were often con-fronted w ith apples-to-oranges com-parisons w hen comparing test result sbecause there w as no standard fortesting echo-canceled modems.

The deficiencies in EIA/TIA-496w ere addressed in TSB 37-A, w hichw as publ ished in 1992. TSB 37-A built

on EIA/TIA-496-A but au gm ent ed th e

number of test channels from 6 to 16and added a laundry l ist of simulatedadditional impairments. These im-pairments included phase jitter, im-pulse noise, intermodulation distortion,near-end echo, and far-end echo.

The model also included the effectsof local loops (i.e., the tw o-w ire pat hs

that connect t he user to t he telephonecompany’s central office) and theeffect of the input impedance of localloops. This m odel w as good for evalu-ating the performance of modemsfrom an error-rate standpoint.

Meanwhile, more and more mo-dems began to include error control,so th e TSB 37-A m odel w as only use-ful w hen error control w as disabled.Disabling error control lightened theload on the processors that imple-mented the modem, which reducedthe uti l i ty of the test . I t was t ime foranother upgrade in testing standards.

The TIA int roduced a new ap-proach to modem t esting in 1994 wit hthe TSB 37-A and TSB 38 standards.TSB 37-A defined various telephone-network subsystems that could be

combined with LOOs to simulatemodem operation over a w ide varietyof typical connections.

TSB 37-A brought the recipe for thetelephone netw ork model to the t est-ing party , but TSB 38 provided thebaking instructions. TSB 38, “ … pro-vides a consistent set of repeatable

100% 90% 80% 70% 60% 50% 40% 30% 20% 10% 0%

7000

6500

6000

5500

5000

4500

4000

3500

30002500

2000

1500

1000

500

0

Modem AModem LModem 3

Figure 3—From a network standpoint, Modem A performs at 4700 cps over 70% of the network model whereas Modem L performs at about 3300 cps, and Modem 3 at a throughput of less than 3000 cps. Thus the chart gives the customer an objective means to compare the throughput of these three modems.

Page 26: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 26/6834 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

test procedures designed to cha racter-ize the performance of modems. Thisis achieved by stating the preciseconfiguration of all the required testequipment, then giving step-by-stepinstructions for performing each test.This document also suggests someformats for analyzing, interpreting,and presenti ng th e result s” [1].

TSB 37-A and TSB 38 defined net-w ork coverage. Test results now indi-cate the percentage of the telephonenetw ork over w hich a given level ofperformance can be expected. Thesestandards provide a basis for testinganalog modems up to 33.6 kbps (V.34).

The latest (and maybe final) innova-tion in voiceband modems came when56-kbps PC M m odems w ere intro-duced. Besides creating an upheaval in

the national and international stan-

dards bodies, these modems createdanot her test ing dilem ma —TSB 37-Asaid nothing about digital net w orks. Itw as tim e for yet anoth er upgrade.

DRAFT PN 3857 AND PN 3856The simulation model defined in

TSB 37-A and in its update, PN 3857,employs the concept of netw ork cov-erage. Defining a model that coversall possible situations is impossible,so the model sets up a large numberof possible combinations along w ithan approximate likelihood of eachcombination. The details get prettyhairy, but the concept is simple.

PN 5857 is 92 pages long and over80% of the document contains tablesand appendices of details of the model.The PN 5857 model defines suites of

combinat ions of digital/analog netw ork

GlossaryDLC —A digital loop carrier is a system that provides access via a digital

carrier link to a central office for a cluster of subscribers. Individual sub-scribers are serviced off the remot e DLC termin al w ith higher qualit yindividual t w o-w ire analog loops.

Digital pad —attenuation introduced into a PCM link by means of digitalcode translation

Hybrid —a three-port analog device that connects one duplex port to sepa-rate transmit and receive ports

LOO —likelihood of occurrence, a w eighting factor applied to com ponents

in the P N 5837 netw ork modelPCM— Pulse-coded modulat ion is a modula tion/coding schem e used w ithin

netw orks for digital t ransmission of voiceband signals. All PC M systemsin the U .S. today digitally encode a 4-kHz –w ide analog signal int o a64-kbps digital bit stream using a sam pling rate of 8 kHz . A/D and D /Aconverters are comm only im plemented in pairs in a CO D EC (C Oder-DECoder). These CODECs use µ-law com pandin g (com pression/expan-sion) in N orth Am erica as specified in ITU-T Recomm endation G .711 toeffectively provide a dynamic range equivalent to that of a linear 12-bitcoding system, but using a sam ple w ord size of only 8 bits, w hich resultsin 256 possible signal levels

PCM link— a digital l ink employing PCM or ADPCM encoding that termi-

nat es in a four-w ire analog interfacePCM modem— a modem, as specified in the ITU-T V.90 Recommendation,w hose line signal at the sam ple rate is one of the levels generated by aP C M C O D E C

RBS —Robbed-bit signaling is a technique that expropriates PCM bits nor-mally used to carry voice-signal information to convey supervisory andcall control information. RBS is a form of in-band signaling that uses theleast significant bit from every sixth frame of one 64-kbps PCM channel.The end result is th at w hen t he least significant bit is u sed (i.e., robbed),the signal is effectively a seven-bit valu e for that sam ple, w ith t he leastsignificant eighth bit effectively becoming a random value. The resultingoutput appears as the original signal w ith a low -level impulse noise hit.RBS may be used in D LC system s.

Page 27: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 27/6836 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

components and the impairments thatoften accompany each com ponent.

Digital impairments include digitalpads and various forms of RBS. Analogimpairments include analog pads, theeffects of various lengths of 22-, 24-,and 26-AWG tw isted w ire pairs,bridged taps, loading coils, Ga ussiannoise, echo, pow er-line indu ced noise,and nonlinear distortion. The modelassigns an LOO to each component.

PN 3856 defines many tests thatapply to the PN 3857 model. A typicaltest com putes the throughput for agiven configuration along w ith t heLOO for that test case.

Performing tests in a suite yields alist of throughput values and correspond-ing LOOs. D isplaying throughput as afunction of cumulat ive LOO defines a

netw ork coverage curve that character-izes a given modem. The goal is toachieve the largest throughput over themaxim um percentage of the netw ork.

REPORTING THE RESULTSThroughput test results are often

presented as a curve displaying the

throughput achieved as a function ofthe percentage of cov erage given bythe reference netw ork. Figure 3 show sthroughput in characters per second(cps) for three different modems.

For about 5% of the netw ork, mo-dems A and 3 achieve throughput inexcess of 5500 cps and modem Lachieves less than 4500 cps. Around the52% coverage point, modems 3 and Lboth operate at about 3750 cps andmodem A operates at about 5400 cps.

At 97%, modem 3 no longer passesdata and modems L and A achieveabout 2800 cps and 3500 cps, respec-tively. This curve demonstrates thatmodem A provides higher throughputthan m odems L and 3 in this test .

HANGING UPD esigning voiceband m odems has

become qu ite a process. The sophisti-cated DSP algorithms coupled withthe pow er of today’s embedded pro-cessors can lead t o softw are-baseddesigns. Testing is a key com ponentof the design process although testingitself can never improve a bad design.

A rthu r J Carlson holds a Ph.D. i n Elect r ical Engineering from th e U ni- versi t y of I owa. H e spent the f i rs t 12 years of hi s career on t he facult y of the U niversi t y of M issouri , Columb ia.H e th en relocated to Sil icon Val ley w here he has work ed i n h igh-speed m odem d esign for 20 years. Art is a sen io r sci en t i st a t A l t oCom i n M oun- t a in Vi ew , CA. You may reach h im a t ajc@alt ocom.com.

Standardized testing provides OEMsw ith consistent and uniform cri teriafor comparing modem performancelevels and for avoidin g those peskyPeppy Puppy problems. I

REFERENCE[1] TIA/EIA TSB38, “ Testin g P roce-

dure for Eval uat ion of Two-Wire4-Kilohertz Voiceband D uplexModems,” Introduction.

RESOURCETIA standa rds info,www. t i a o n l in e .o rg

Page 28: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 28/68

CIRCUIT CELLAR OCTOBER 199938

N P C

www.circuitcellar.comPCNouveauedited by Harv Weiner

UNIVERSAL PC/ 104BOARD MOUNTSA family of components for mounting PC/ 104

and PC/ 104 -plus boards has been announced byparvus. Collectively called SnapStik components, the

family consists of a series of snap-together board separa-tors and other components that create a robust, low-cost,

incremental card cage for PC/ 104. SnapStik is designed forembedded applications ranging from industrial equipment panelinstallation to high-vibration, high-shock environments.

Basic to the SnapStik PC/ 104 component family is the Snap-Slot . SnapSlots are hollow polypropylene card-cage rail seg-ments with length equal to the spacing required for one PC/ 104board. SnapSlots attach to the corners of PC/ 104 boards usinga threaded 4-40 insert and machine screw. Multiple PC/ 104boards with SnapSlots attached to each corner snap together toform an incremental card cage called a SnapStak .

A SnapGuide is similar to a SnapSlot , except that a SnapGuidehas an extension formed to fit the inside of an extruded enclosure.A SnapShok is a SnapSlot fitted with a silicone rubber shock-

absorbing tire, designed to fit inside an extruded enclosure.Other SnapStik components include a selection of specializedside and end mounts, bolts, nuts, spacers, and disk drive- and fan-mounting options.

CompactPCI CPU BOARD The C2P3 CPU board is targeted at compute-intensive

applications such as telecommunications, aerospace, and imag-ing. It features two Pentium III processors running at 550 MHz,1 GB of main memory, and 1 MB of L2 cache. It incorporatesIntel’s 82443BX chip set, the Intel 740 Advanced Graphics

Processor (AGP), and is the first CPU board to provide a 100-MHzimplementation of Intel’s FSB (Front Side Bus). The DEC 21554Draw Bridge Chip is also included to enable multiprocessing.

Networking and I/ O features include dual Ethernet interfaces(twisted pair) operating at either 10 or 100 Mbps, a 40-MBpsultra-wide SCSI, and a 64-bit AGP graphics engine with 4 MB of video RAM optimized for 3D rendering. Also available are twoUltra-DMA 33 IDE interfaces, a pair of USB ports, dual serial I/ O

with optional RS-422 drivers, and a parallel port. The board can support hot swap I/ O modules on the Compact-PCI bus and can accommodate a 2.5 ″, 9-GB IDE drive. Forapplications that must be deployed without a rotating hard disk,the board also provides up to 340-MB SanDisk 1.5 ″ flash IDE onthe rear panel. The C2P3 runs a variety of popular desktop andreal-time operating systems and comes equipped with AMI’sBIOS and onboard diagnostics software and status LEDs.

Pricing for the C2P3 starts at $1995 , less processor andmemory. For high performance at low cost, the C2P3 canaccommodate two Celeron PPG370s.

General Micro Systems, Inc.(909) 980-4863Fax: (909) 987-4863www.gms4vme.com

For a limited time, PC/ 104 developers can order a SnapStikStarter Set, a $55 value, for an introductory price of $24.95(limit two per customer).

parvus Corp.(801) 483-1533Fax: (801) 483-1523www.parvus.com

Page 29: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 29/68

OCTOBER 1999 EMBEDDED PC 39

N P C

www.circuitcellar.com PCNouveau

SINGLE-BOARD COMPUTER The CoreModule/ P5e uses the new Intel

BGA-packaged Mobile Pentium processor withMMX technology to offer up to 266-MHz perfor-mance in a PC/ 104 form factor.

The card contains all the functions of a fully configuredPCI-based PC-compatible system, including disk controllers,two FIFO-buffered serial ports, an enhanced-capabilities parallelport, PS/ 2 keyboard/ mouse interfaces, two USB ports, an IrDAport, and a built-in DiskOnChip2000 solid-state disk drive. Anefficient DC/ DC converter, to supply the special voltage require-ments (3.3 and 1.9 VDC) of the processor and core logic, is builtdirectly into the CoreModule/ P5e, resulting in single-supply(+5 VDC) system operation and minimal power consumption.

An extended temperature version of the SBC supports –40°Cto +85°C and operation with or without a fan is supported. TheCoreModule/ P5e can withstand 50-G shock and 12-G vibration,under MIL-STD-202F. EMI, EMC, and ESD compliance is inaccordance with the European CE mark standards (EN 55022Class B and IEC 801-2, -3, and -4). Additional reliability enhance-

ments include a watchdog timer and a power-fail NMI generator.In addition to DOS and Windows 98, N T, and CE, support for

most leading RTOSs is also available.Pricing for the CoreModule/ P5e starts at $729 in OEM

quantities of 100.

Ampro Computers, Inc. (408) 360-0200www.ampro.com Fax: (408) 360-0220

HIGH-SPEED PARALLEL DSP MODULE The CRT-1260 is a high-speed DSP module in a PC/ 104 form

factor. Designed around the NeuriCam NC3001 Parallel DSPchip, the module features 32 fixed-point multiply-and-accumulateprocessors operating in parallel with a three-stage pipeline. Thisdesign enables the module to achieve 1000 MOPS, making itideal for embedded applications such as real-time vision, opticalcharacter recognition, pattern matching, high-speed digital fil-ters, and speech recognition.

The NC3001 pDSP is specifically designed with artificialneural networks for fast learning and recognition. Its architectureis optimized for the implementation of the Reactive Tabu Searchlearning algorithm, a competitive alternative to back-propaga-tion which leads to a very compact implementation. Internal

resources can be assigned either to a single neuron or be partitionedamong several neurons to implement multilayer networks. The CTR-1260 is available in PC/ 104 form factor with a 16-bit

interface. It features a 512-KB frame memory and an auxiliary EPPparallel port for direct connection to digital cameras and otherperipherals. It also includes an intuitive Windows-based softwareinterface and is available as a 3U CompactPCI with two pDSPprocessors.

The CTR-1260 is priced at $995 .

EuroTech+39433-486258Fax: +39433-486263www.eurotech.it

Page 30: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 30/68

E P C

CIRCUIT CELLAR OCTOBER1999 40 www.circuitcellar.com

Mal Raddalgoda

Name recognition is important in today’s software market, but it’s no substitute for product performance. So, how does Windows CE stack up against some of the established RTOS technologies? Mal checks it out.

W ith the Windows cachet (in appear-ance if not reality) and the Microsoft market-ing machine, Windows CE has done for theembedded-systems industry in a few shortmonths what established RTOS compa-nies have labored for years to provide—recognition by the general public.

In this sense, it means that much of thepublicity generated around Windows CEalso benefits the industry through a higherlevel of awareness of the underlying soft-ware platform of new and innovativeembedded devices.

But when the hoopla has died down,and embedded designers have to producea product, they look beyond the hype tothe RTOS details to ask if W indows CEmeets the technical requirements of theproject. N o doubt many embedded sys-tems designers are asking that questionright now. And Microsoft would certainlyhave them believe it does.

But to be honest, design engineers don’tcare whether or not a design uses Win-dows CE. In all likelihood, they’re promot-

ing a network router, a cellular telephone,a set-top box, or a data-acquisition device.

They’re not out to promote Windows CE,unless they got an unbeatable deal fromMicrosoft, or unless their product needs allthe help it can get.

Microsoft presents Windows CE asthough it were breaking new ground inembedded systems. But RTOSs and thedevices they control have existed for years.

When it comes down to choosing asoftware platform, there are several alter-natives that were available many yearsbefore Microsoft ever conceived of Win-dows CE. Comparing W indows CE tech-nologies with the established RTOSs shows

just how far Microsoft has gone to providea serious product for embedded markets.

THE BUSINESS MODELFor designers looking for a platform

capable of supporting a unique design,the ability to work with the platform vendorto devise the optimum RTOS configuration,performance, and footprint is one of the

most important selection criteria (see Fig-ure 1). Out of the box, no OS meets mostembedded developers’ needs, so the abil-ity to develop a close relationship betweenplatform vendor and customer is critical.

This is a fundamentally different modelthan the one Microsoft used to build its PCoperating-system business. O n the desk-top, the platform is a mass-market productthat’s distributed in an identical version tohundreds of PC vendors, who then buildthe hardware around it. Is it any wonderthat all PCs are practically the same?

Microsoft is trying to use a similarbusiness model for distributing WindowsCE. Rather than selling it directly to designengineers and working with them to incor-porate it into a product, Microsoft licensesa single version to a handful of O EMdistributors who are responsible for imple-menting board-support packages andproviding software utilities and consultingservices to embedded designers.

Industry analysts have lauded Microsoftfor bringing in experienced embedded-

W hat’s in a Name? Windows CE vs. a Hard RTOS

Page 31: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 31/68

OCTOBER1999 EMBEDDEDPC

E P C

41www.circuitcellar.com

performance but results in a relativelylarge memory footprint).

Rather than using a messaging systemto communicate between user and kernelobjects and between kernel objects, CEuses an event model that converts interruptevents to messages, which are then queuedin priority order. The message queue ispolled, so it’s possible for a message to besitting in the queue for a relatively longtime before it’s acknowledged and pro-

cessed. Although this is an acceptabledesign for a desktop windowing system,it’s not a real-time activity.

Much of the software available withWindows CE (e.g., TCP/ IP and remoteaccess, web browser, e-mail) are versionsof the same software found in desktopWindows. Although this can provide fa-miliarity to end users, it also means thatthe software wasn’t designed for embed-ded use. The result is software that islarger and slower than it should be for a

typical embedded system.On the other hand, traditional RTOSswere designed for systems where memory

and processing power were limited. Takethe QNX RTOS, for example. The originalQNX microkernel was about 12 KB,whereas the QNX/ Neutrino microkernelis 34 KB. W ithin this 34 KB is enoughmemory for interprocess communications,interrupt handling, and thread scheduling—all the fundamental facilities needed for abasic OS in a limited-memory environment.

Since its inception, Windows CE hashad broad processor support that includes

MIPS, Hitachi, ARM, Intel, and others. It’simportant to realize, however, that it’s notMicrosoft that provides this support, atleast not directly. Microsoft provides asingle code base to distributors and pro-cessor vendors, who work together toproduce the port.

The process was designed to put CE onseveral different processors in a short periodof time, and it succeeded. But embedded-systems designers had no input into theprocess, so the processors that are sup-

ported may not be the most useful ones.Other RTOS vendors have long recog-nized the value of supporting multiple

system vendors as distribution partnersrather than trying to go at an unfamiliarmarket alone. Their plan works well, up toa point.

In general, these OEM distributors doa credible job of providing tools, samplecode, and consulting services to help geta design working with CE. Designers mayeven consider the distributor a businessand technology partner in their efforts.

But Microsoft is not in this loop. They doprovide some telephone technical supportfor W indows CE, although this same sup-port covers all manner of embedded sys-tems, handheld PCs, Windows terminals,and any other market that CE penetrates.

The support covers OS issues like buildinga customized platform, scheduling processes,and setting up networking utilities, but itdoesn’t go far in providing detailed tech-

nical assistance to a specific design.In contrast, almost all traditional RTOS

vendors sell directly to vendors or engi-neers engaged in development projectsand provide direct system software andsupport services for their customers. W henengineers call for technical support, toreport a problem, or to discuss whatfeatures they’d like to see in future re-leases, they’re talking directly to the com-pany (and often the individuals) thatdesigned and implemented the OS. There’s

no better way to get feedback directly intothe hands of those who can use it.

ARCHITECTUREAND PROCESSORSUPPORT

The architecture of theOS by itself doesn’t ex-plain any advantages of the software, but it helpsdefine the ability to imple-ment characteristics likescalability, performance,and reliability (see Figure2). And, it often sayssomething more accurateabout the intended mar-ket of the OS than anyposition paper.

Windows CE was de-signed by Windows sys-tem architects and itshows. It’s designed as alarge group of OS files,most running in kernelspace (which improves

Figure 2—As the complexity of embedded systemsincreases, the ability to deliver highly reliable prod-ucts that meet the time-to-market pressures be-comes a major business imperative. Here you see three different architectures. The important thing to keep in mind is that overall system reliability depends on OS architecture—the less code runningin the kernel, the better.

Hardware

Real-timeexecutive

kernel

Fi le sys tems I /O managers

Application Application

Other...Devicedrivers

Networkdrivers

Graphicsdrivers

Graphicssubsystems

Traditional RTOS architecture

Hardware

Monolithickernel

Fi le sys tems I /O managers

Application Application

Other...Devicedrivers

Networkdrivers

Graphicsdrivers

Graphicssubsystems

Windows CE architectureMemory

protected

Hardware

Microkernel

GUImanagers

I/O managers

Application Application

Devicedrivers

Filesystems

Networkdrivers

Graphicsdrivers

Other...

Microkernel RTOS architecture

Memoryprotected

Memoryprotected

a) b)

c)

21.90%

30.70%

0% 20% 40% 60% 80%

Familiar API

Small footprint

Availability andquality of tools

Real-timecapabilities

49.50%

76.50%

Figure 1—What are the key criteria for se-lecting an RTOS? Develop-ers are looking at real-time capabilities, development-tool quality, and footprint size. A fa-miliar API was considerably lessimportant (source: Venture Develop-ment Corp.).

Page 32: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 32/68

CIRCUIT CELLAR OCTOBER1999 42 www.circuitcellar.com

and the popular Visual Developer StudioIDE. Microsoft would have you believethat you can apply the same APIs anddevelopment techniques to write CE appli-cations that you would use on the desktop.

The reality is more complicated. Thefull Windows CE supports only about athird of the APIs found in Windows 95 andNT. And they aren’t exactly the same calls.Microsoft refers to them as being “in compli-ance” with Win32. In fact, it’s differentenough that Microsoft refers to it as Win32for Windows CE API and gave it its ownprogramming references.

For a programming interface, manyestablished RTOSs use the only platform-neutral programming standard availabletoday—POSIX (or some variation thereof).For the most part, programs are devel-oped specifically for embedded systems

rather than ported to an embedded de-vice from a desktop application.

Microsoft’s use of the Win32 API, aproprietary programming interface specifi-cally for Windows systems, encouragesprogrammers to use desktop code andprogramming practices for embeddeddevelopment, perpetuating slow and bulkyprograms that are inappropriate for em-bedded systems.

POSIX is a true standard with interna-tional recognition and steering commit-

tees representing broad industry segments. This arrangement ensures that embeddedcode won’t be broken by arbitrary orunannounced changes made to benefitone vendor.

Microsoft notes that you can use VisualBasic or Visual J++ (its own brand of

Java), in addition to Visual C++, to writeWindows CE applications. This soundslike an impressive array of languages, butfew, if any designers are going to useVisual Basic for an embedded applicationbecause its run-time support alone re-quires well over 1 MB. N ot to mention thatpure Java development tools for produc-ing truly portable code are available fromdozens of independent software vendors,without the confusion generated by Micro-soft’s own extensions to the language.

But thanks to the extensible nature of Visual Developer Studio and Visual C++,it’s possible to use this fine environmentwith virtually any other RTOS. In fact,several embedded vendors use the VisualStudio with plug-in modules for softwaredevelopment with their own RTOSs.

processor families. By providing a choiceof processors, RTOSs such as QNX,Microware’s OS-9, and ISI’s pSOS enabledesigners to choose processors by cost,performance, or other technical consider-ation, while keeping the same system soft-ware characteristics and programming tools.

GRAPHICS AND WINDOWINGOne of the major misconceptions of

Windows CE is that it is related to thedesktop Windows. Microsoft gives a per-ception of a strong relationship, both withthe product name and through its offeringof limited versions of traditional desktopapplications (e.g., Excel, Internet Explorer).

In reality, the only feature shared be-tween Windows CE and desktop Windowsis the Windows API—the programminginterface for Windows platforms. The un-

derlying OS is almost entirely new, but itborrows technologies from other Win-dows OSs.

A separate but related issue is that (atleast for embedded systems) most peoplebelieve there is a W indows-like graphicaluser shell, like the ones found on CE-based handheld PC units. But, Microsoftdoesn’t provide a user shell for the embed-ded version of the OS.

Embedded developers have to buildtheir own shell or buy a commercially

available one. The supposed advantageof the Windows-like graphical desktopsimply doesn’t exist.

Embedded-system developers have thesame requirements for a GUI as they dofor the RTOS itself. They don’t care if theprogram can be ported from the desktopbecause applications on handheld andembedded devices have different fea-tures and uses. What is important is sizeand performance, both characteristics thatare far better represented by the likes of QNX’s Photon and Microware’s MAUI.

For example, Photon is small (under200 KB for a complete implementation),fast, and easy to use. Also, its memoryfootprint is small, so engineers can in-clude more user features into the sameamount of space required by Windows CE.

DEVELOPMENT TOOLS The availability of rich and compre-

hensive application development envi-ronments is supposedly the true strength of Windows CE. This includes both the Win32API (the de facto standard on the desktop)

Page 33: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 33/68

OCTOBER1999 EMBEDDEDPC

E P C

43www.circuitcellar.com

At least one other programming prod-uct is a strong competitor to the Microsoftdevelopment tools hegemony. Metro-werks’ Codewarrior is the same compilerand IDE that dominated the Macintoshsoftware industry and is now making itsmark in embedded-systems programming.

Codewarrior is available on manyprocessors and RTOSs, and it offers awide range of programming languages.In other words, it’s possible for an embed-ded system to have a first-class set of toolswithout depending on Microsoft.

FUTURE SUPPORT, OR LEFTHANGING?

Technical comparisons are all welland good because they compare thecharacteristics of RTOSs at a particularpoint in time, but you also have to con-

sider how these characteristics changeover time. W indows CE is a new RTOSthat has little history in supporting prod-ucts over a period of time. If history is anyguide, Microsoft has little compunction inchanging software architectures and in-terfaces every few years and requiringcomputer designers, programmers, andusers to change everything to keep up.

Traditional RTOS suppliers are muchmore cognizant of how dramatically evenminor changes affect system designers.

Changes that affect how the RTOS is usedin an embedded design are embarked onquite infrequently and in consultation withcustomers on implications to their products.

For example, Q NX changed programarchitecture only when it became a 32-bitOS, over ten years ago. Even QNX/Neutrino, a kernel introduced in 1996,uses the same basic microkernel structureas the older implementation (with supportfor symmetric multiprocessing and differentprocessor families). Its strict adherence tothe POSIX interface means that programsdeveloped years ago still run today.

Microsoft has a canned answer to all of the technical deficiencies of WindowsCE—wait until the next version. And theypromise that the next version will be acomplete rewrite that improves real-timecharacteristics, but at the expense of back-ward compatibility.

To get real-time response for applica-tions, Microsoft is supplementing the Win32API with a new real-time API, negatingone of its biggest selling points—the familiarprogramming interface.

Mal Raddalgoda is the senior technology analyst for QNX Software Systems Ltd.,concentrating on the North American mar-ket. Mal has over 10 years of experience

SOURCESWindow s CE, Visual Basic, Visual J ++, Visual C++Microsoft Corp.(206) 882-8080Fax: (206) 936-7329www.microsoft.com

QNX/ Neutrino, PhotonQNX Software Systems, Ltd.(613) 591-0931Fax: (613) 591-3579www.qnx.com

OS-9, MAUIMicroware Systems Corp.(515) 223-8000Fax: (515) 224-1352www.microware.com

pSOSIntegrated Systems, Inc.(408) 542-1500Fax: (408) 542- 1956www.isi.com

CodewarriorMetrowerks, Inc.(800) 377-5416(512) 873-4700Fax: (512) 873-4901www.metrowerks.com

in the computer and telecommunications indus-try and has held positions inproduct development, product management, and marketing. He is also a member of the Embedded Soft-ware Association (ESOFTA). You may reach him at [email protected].

Such practices may work on the desktop,where Microsoft’s dominant market shareand application base mean that usershave little alternative but to wait. But, timeto market has a different meaning in embed-ded systems. Embedded designers needspecific technical characteristics to imple-ment their products’ features. They can’twait until Microsoft decides that what theyneed is worth including in a future version.

Granted, W indows CE has advantagesthat traditional RTOSs don’t: automaticrecognition, of course, and Microsoft’sability to improve CE over time by allocat-ing immense resources to the effort.

The question is not whether the Microsoftdevelopers can improve CE, but whetherthey have an architecture that can scaledown from the handheld PC over to moretraditional embedded applications. O r, will

engineers suffer through countless versionsof OS incompatibilities, forced to con-stantly change their code because Micro-soft couldn’t get it right the first time? EPC

Page 34: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 34/68OCTOBER1999 EMBEDDEDPC

R P C

45www.circuitcellar.com

Figure 1—Here’s what an airplane that isfighting crosswind looks like. The official term

for this is “crabbing” because, in its extreme form, it looks like a crab walking sideways.

R eal-TimePC

Ingo Cyliax

W here in the World...Part 3: Fighting the Wind with GPS

For the last two months I’ve writtenabout GPS and some of its applications.Last time, I wrote about a prototype systemthat I developed for Near Earth Observa-tion Systems (NEOS), a company special-izing in airborne remote sensing.

This system is a GPS-aided data-acqui-sition device that also uses GPS to aid innavigation. The annotated data is inte-grated in geophysical information systems.

One application for this type of systemis to take infrared imagery and use spec-tral analysis to determine the quantity andtype of ground cover that exists. Gather-ing this data is important for land man-agement such as agriculture and forestry.

The prototype was successful, but Ineeded to add more features. In this finalarticle of this series, I’ll describe one of thefeatures that we’re adding to the system.

As I described in Part 2, a small aircraftflies a preplanned grid and takes picturesof the ground using a downward-facingcamera. Following the grid, the plane

flies north and south tracks covering theground in swaths. The width of the swathdepends on the field of view of the cameraand the altitude above ground level.

The north-south tracks make it easy tointegrate the data with existing maps anddata. NEOS primarily uses ultralight air-craft to fly these missions. If there’s anysignificant crosswind, the pilot has to turnthe aircraft into the wind to keep on course

(see Figure 1).Here’s the clincher. As the aircraftturns into the wind, the photos it takes will

Even the best GPS technology can’t control the elements of nature, so Ingo had to compensate his data-acquisition system for the effects of crosswinds to make sure the ground-mapping camera shoots straight.

be angled with respect to the ground trackthe flight was intended to cover. W ithsevere crosswinds, the angle of adjust-ment can be quite significant.

Figure 2 shows what a track of thecrosswind pictures looks like. As you cansee, the pictures are not squared up withthe north-south meridian and you have torotate them to use the data. Also, becausethe edge of the swath is ragged, we have

to overlap the swaths to make sure wecover all the little nooks. This adjustmentcauses us to burn more fuel because theeffective swath width is reduced and wehave to fly more swaths for the same area.

The solution is to mount the camera ona camera pod that can be turned relativeto the aircraft. This way, the camera canbe pointed to compensate for the cross-wind. However, it’s yet another thing forthe pilot to manage while flying.

One of the objectives for this system isto reduce the pilot workload. Less workmakes for less mistakes. A mistake usually

Crosswind

Apparent heading

Course over ground

Page 35: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 35/68

R P C

CIRCUIT CELLAR OCTOBER1999 46 www.circuitcellar.com

means reflying theswath or even the entire

mission. Also, less workloadlets the pilot focus on flying.Camera-pod rotation is an

obvious thing to automate. W e havethe heading the plane is flying over the

ground (north-south track) and also thedirection we want the camera alignedwith. If we can figure out how far off theplane’s apparent heading is, we candrive a small actuator to turn the camera.

Of course, there’s already a GPS re-ceiver in the system as a pilot-navigation

aid and to annotate the data, but it onlygives us the heading over the ground (i.e.,the heading of the course we are trackingover the ground). It obtains this informa-tion by taking position samples and com-puting the direction between the positionfixes it has made. It doesn’t know whichway the aircraft is turned. Incidentally, theGPS receiver can’t compute an accurateheading when it’s not moving.

But we need to figure out what directionthe aircraft is pointed because the camerais attached to the aircraft’s frame. O ncewe know this heading, it’s easy to com-pute the difference and adjust the angle.

Getting the direction of the aircraft isactually pretty easy. Often we get caughtup in new technologies and miss obvioussolutions—like using a magnetic compass.

The magnetic compass always gives

the direction of the airframe relative to theearth’s magnetic flux lines. Before GPS,this behavior was a nuisance becauseyou had to know the crosswind error tocalculate the true course heading. For ourpurposes, the preadjusted heading is justwhat we want. There’s one small gotcha.

Compass headings are magnetic. Themagnetic headings are based on themagnetic north pole, which is somewherein North Canada and nowhere near thetrue North Pole used for map datums,

which means there’s a magnetic declina-tion to consider.

The declination value is usually indi-cated on maps, to show how much themagnetic heading differs for the true head-ing. The GPS receiver finds this informationby computing the heading to the magenticnorth pole from our current position.

The angle we have to adjust the cam-era compared to the airframe is shown by:

ang_camera = (0 – (ang_maghead +

ang_magdecl) mod 180)

The ang_maghead and ang_magdeclvariables are provided by the compassand GPS receiver, respectively.

PROJ ECT This project entails building a heading

compensator that rotates the camper plat-form to compensate for the crosswindheading error. For this, we need a com-pass, a GPS receiver, and an actuator.

We have a GPS receiver in our systemand we’ve looked at the NMEA message

Figure 2—When we try to take pictures as we are turning into the wind, the pictures are no longer aligned to the north-south meridian,which is what we would like to see.

Crosswind Course over ground

Image frames

Page 36: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 36/68OCTOBER1999 EMBEDDEDPC

R P C

47www.circuitcellar.com

formats in previous articles. If you remem-ber, the sentence most GPS receiv-ers generate contains a field that de-scribes the magnetic declination.

The declination is usually a small anglethat describes the difference between themagnetic and true heading. W here I live,this difference is about 2.9° west. That is,the magnetic north pole is 2.9° west of truenorth. Or, a 0° magnetic heading wouldbe equal to a true heading of 2.9° east.

There are various compass schemes.Mechanical compasses use a magneticneedle. To measure the position of theneedle, you need a rotational encoder.

These compasses are easy to build, butthey contain movements that are subject tovibration damage and oil that can leak.

Electronic compasses use a magneticflux sensor to measure the magnetic field

directly. This setup is preferred becauseno moving parts means the compassesare robust. Flux sensors are either solid-state HAL-effect sensors or coil-based.

There are several techniques used withcoil-based sensors. The trick is to makethem sensitive and small, yet immune fromvarious noise sources. Electronic com-passes used to be rather exotic and ex-pensive, but with advances in micropro-cessors, it’s possible to implement signalprocessing in software, which makes these

compasses less expensive now.I wrote about Precision N avigation’s

Vector 2D module in “Robot NavigationSchemes” ( Circuit Cellar 81). This moduleis inexpensive and available from mail-order sources such as Jameco.

One of the drawbacks of this module isthat it only uses two coils and can thus onlybe used when it is level. A gimbaledversion allows it to be used in nonlevelapplications. However, this module usesa serial bus interface, which would make

it hard to interface with our system.Precision Navigation also makes aNMEA-based compass module—the

TCM2. This module is flexible, has atemperate sensor, and in addition to theheading, can measure roll and pitch.

The TCM2 comes in several differentversions, mostly based on how muchinclination they can handle. The low-endversion can handle ±20° and the top-endversion handles ±80°. The TCM2 has low-power modes, is robust, and was de-signed to be used in mobile applicationslike ours (see Photo 1).

The most important feature for us is thatthe modules can speak NMEA protocolvia an RS-232 link. A three-wire interface(Tx/ Rx/ ground) is all that’s needed tointerface it to a PC-based system like ours.

Like all NMEA devices, this deviceuses a two-letter prefix to indicate whatkind of device it is. In our case, is theprefix for a magnetic compass.

Magnetic compasses only have onesentence type, the (heading mag-netic) sentence. has two fields— isthe magnetic heading value and indi-cates that the heading is magnetic.

An example of anNMEA message from thismodule is:

This message indicates a heading of 182.3° west. The module can also be pro-grammed to send nonstandard NMEAmessages with more than just the head-ing. Also, by making our application usestandard messages, it’s possible to simplydrop in another compass module, pro-vided it speaks NMEA.

Page 37: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 37/68

R P C

CIRCUIT CELLAR OCTOBER1999 48 www.circuitcellar.com

Photo 2—The serial servo controller is used to interface radio control (RC) servos to any computer with a serial port.

Placement of thecompass module is an

exercise in compromises.We can place the compass

module on the camera pod itself or on the aircraft. If we put the

module on the camera pod, we can usea module with lower inclination tolerance(cheaper) because the camera pod isgimbaled and always level. Also, calibra-tion is simpler because the compass mod-ule is coupled to the camera platform.

Mounting the compass on the airframehas the advantage that we can mount itaway from most of the metal and electricalwiring by putting it at the tip of the wing.It’s easy to change in the software, so wecan leave this issue open and experiment.

For the actuator, I’ll use radio control(RC) servos. These servos are simple tocontrol and come in various sizes withdifferent torque performances. High-endservos have metal gears and ball bear-ings for long life and can withstand quitea lot of abuse. Also, because they aremass-manufactured for the RC model in-dustry, you can’t beat the cost.

The control signal to an RC servoconsists of a single signal that carries apulse-width signal. The pulse width variesfrom 1 to 2 ms, with 1.5 ms being a centerposition. The pulse is repeated between

10 and 20 ms. Most servos have about±45° of travel, which lets us compensateto crosswinds of up to:

cross_wind = 80 mph cos(45)

or 56 mph (far more then we’ll beconcerned about).

Interfacing a servo to aPC-based system couldbe tricky becausewe would need apulse-width generatorthat can generate 1- to2-ms pulses with a step size of about (1 ms/ 256) = 4 µs. But luck-ily, this is a common enough problemthat several servo adapters are available.

One such adapter is the serial servocontroller (SSC) module made by ScottEdwards Electronics (see Photo 2). ThisPIC-based controller receives commandsfrom an RS-232-based serial interface andcan control up to eight servos per module.

By adding an address jumper on oneof the modules, two modules can bebused together to expand it up to 16servos. W e only need one servo for now.

The transfer rate is adjusted on themodule with another jumper and can beset for 2400 or 9600 bps. The wordformat is eight bits with no parity and twostop bits. The protocol is simple andconsists of three bytes—sync, servo num-ber, and position.

The sync byte is an all ones byte (0xff).

So, to set servo number five to the mid-point, you would send 0xff 0x05 0x80.

That’s all there is to it. Take a look at Listing 1 and

you’ll see that the code (Tcl) tomake this subsystem work ispretty simple. The loop in List-ing 1 waits for messages on afile description .

This is a serial port, on whichthe magnetic compass sits.

The compass outputs

NMEA messages. NMEA mes-sages are line oriented so wecan use the Tcl function.In its default behavior, thisfunction reads from the inputchannel until it encounters anend of line, in our case

. The line is returnedin the variable .

The next function is. This function

checks to make sure that each

sentence has a start and anend delimiter and it also

checks the checksum of the message.Remember that an NMEA checksum issimply the XOR of all the characters,excluding the delimiters.

If the NMEA message is valid, weparse the message into its fields. Tcl hasa function called for this parsingprocess. You specify the separation char-acter ( ) and it returns a list of all the fields.

Now we check the first field to makesure it’s the message we’re interested in,

. Because a is special to Tcl, ittells it that this is a variable expansion, sowe have to escape it with a backslash ( )

character. The heading is the first fieldafter the sentence-identifier field.

Next, we can compute the true head-ing by subtracting the magnetic declina-tion and converting it to the servo code.

The servo will go from 0 to 90° in 256steps, so we scale the result.

By taking the modulus, we make surethe servo will stay within 45° of the north/south meridian. If we mount the compassmodule on the camera pod, we need toreverse the direction. In this mode, this

loop behaves like a closed-loop system.After we compute the servo position,

we send it the servo controller. Tcl nor-mally deals with strings and characters,so we have to use the binary conversionroutine to convert integer values to arepresentation suitable for sending overthe output routing ( ). Here again, thefile descriptor is used for theserial port that has the servo controllerattached to it. Once this is done, we dothe whole thing again.

Integrating this code into the final sys-tem is straightforward. Get rid of the loop,

Photo 1—The TCM2 compass

module from PrecisionNavigation has it all, in-

cluding NMEA interface and more interface options than

you’ll ever use.

Page 38: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 38/68OCTOBER1999 EMBEDDEDPC

R P C

49www.circuitcellar.com

Listing 1—This simple code to implement the heading compensator is w ritten in Tcl, whichmost of the project is based on.

Ingo Cyliax has written for Circuit Cellaron topics such as embedded systems,FPGA design, and robotics. He is a re-search engineer at Derivation Systems Inc.,a San Diego–based formal synthesis com-pany, where he works on formal-method design tools for high-assurance systems and develops embedded-system products. Youmay reach him at [email protected].

SOURCESCompass modulesPrecision Navigation(707) 566-2260Fax: (707) 566-2261www.precisionnav.com

Servo controllerParallax, Inc.(916) 624-8333Fax: (916) 624-8003www.parallaxinc.com

Remote sensorsNEOS, Ltd.(909) 694-4096Fax: (909) 677-7081www.neosltd.com

and make the code segment part of anevent handler that gets called wheneverthere is activity on the serial port for themagnetic compass. Except for simple pro-grams, using event-driven programmingis the best programming style to use in Tcl.

WHERE I’M HEADEDWell, this article concludes my series

on GPS. But, because I’m knee deep inthis project, GPS is bound to pop up again.Next month, however, in response to sev-eral readers’ requests, I want to cover serial

port interfacing and pro-gramming. Almost everycomputing device has a serialport, making it one of the mostcommonly used interfaces. RPC.EPC

Page 39: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 39/68

A P C

CIRCUIT CELLAR OCTOBER199950 www.circuitcellar.com

A pplied PCs

Fred Eady

If the words “Free Internet download” make you somewhat skeptical, you’re not alone. Fred took a magnifying glass to GoAhead’s web server software and found enough evidence to satisfy even his Internet-freebie skepticism.

Nothing, absolutely nothing, is free.N o free lunch. N o free pass. Andespecially, no free software.

So, why is this GoAhead WebServerstuff I found on the Internet given away forfree? There’s tons of “free” stuff on theInternet and frankly, I’m scared of a lot of it. What’s the catch? Is this another scam?

As it turns out, there is a “catch.” Youcan download the latest version of Go-Ahead W ebServer V.2.0 for absolutelynothing. But in return, you must grace itwith your application code and share yournew-found knowledge (and modified webserver) with other GoAhead users. Toogood to be true? Let’s go to the phones.

I spoke with the top folks at GoAheadand, after a nice discussion that coveredautomating recreational beverage deliveryfrom the kitchen fridge as well as somereally deep web-server queuing theory, Iwas convinced that the idea behind givingaway the web-server code was sound.

Seems that GoAhead wants to establisha presence in the embedded control-my-

widget-over-the-web market. They figurethe best way to do that is to provide anoperational embedded web-serverplatform that’s easy to port and modify.

Once the “free” web-server code isported to an embedded platform, the nextlogical step is to incorporate it into anembedded web product. The more themerrier. These guys and gals may begiving away the store, but so far, so good.

The GoAhead WebServer runs out of the box with various flavors of Unix, QNX,VxWorks 5.3.1, Windows NT, Windows95 with Service Pack 2, W indows 98,Windows CE, LynxOS, and the up andcoming under-penguin, Linux.

GOAHEAD, FRED, TELL ME MOREGoAhead WebServer is a standards-

based full-featured C-based web-serverapplication. You can download theapplication from www.goahead.com/ web-server/ wsregister.htm. GoAhead requiresthat you fill in some personal data first. Ifigure they want to be the first to say they

knew you before you got famous by usingtheir web-server code in your device.

Once the code is “yours,” the down-loaded file should be unzipped into adirectory called . There arenumerous directories under ,including a subdirectory for each of thepublicly ported GoAhead W ebServeroperating environments.

A is included in theindividual OS directories for each OScompiler. In addition to the ,there’s also a main program that invokesand initializes the server.

I pick on Bill, but I also use Bill’s stuff abunch, too. This time around I’ll use thewell-known-but-not-so-embedded-orientedWindows NT. One reason for using NT isthat it’s already running on the Circuit Cellar Florida Room network.

Windows NT isn’t usually thought of asembeddable, but it’s on the GoAheadalready-ported list. Thus, Windows NTworkstation 4.0 is a perfect springboard forembedding the server on another platform.

GoAhead for NothingGetting the Server Started

Page 40: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 40/68

A P C

OCTOBER1999 EMBEDDEDPC 51www.circuitcellar.com

Photo 1—This whole GoAhead web server thing is a sleeper until you get to this point. You can dig through the HTML files for answers until you’re blue. The answ er is to just install it!

The current scripting engine isspecified by thespecifier at the beginning of theASP script. The language lastspecified remains the default untila new keyword isencountered at the start of anotherASP script. If no language is

specified, the default language is JavaScript.

It’s recommended that the languagebe specified in thesection of your page, as in:

JavaScript is easy to learn, and itssyntax resembles models you are alreadyused to. To create an ASP script field in aGoAhead WebServer ASP document, usethe and ASP delimiters. For example:

will output “Circuit Cellar APC” in place of the ASP-delimited field.I won’t write a dissertation on ASP in

this column, but here’s a quickie on justhow the ASP process executes. W hen auser’s browser requests an ASP document,

the default URL handlerdetermines if the page isan ASP document byexamining the file extension. If

is the extension, then ASPprocessing is invoked.

The document is read from the filesystem or ROM store in a one-passoperation. ROM store? Yep. Along withthe new Embedded JavaScript parser,V.2.0 supports another new feature calledwebcomp. W ebcomp is a web-pagecompiler that generates ROMable webpages and source code for systems thatdon’t have a file system.

Getting back to the process followingthe one-pass read, text before the ASPdelimiters is copied directly to therequesting browser. Any text foundbetween ASP delimiters is passed to the

relevant scripting engine (JavaScript here)for execution. The postscripted text isimmediately passed back to the browserand the line-by-line process continues untilthe end of the document.

If you’re familiar with ASP, you’veprobably noticed that the process Idescribed is a bit different from other ASPimplementations you may have encoun-tered. GoAhead WebServer doesn’t bufferthe entire ASP output and thus doesn’tpermit scripted iteration over HTML tags.

It doesn’t support these methods becausethey require the entire ASP document to besucked into memory before being processedand returned to the browser. The docu-mentation suggests that files beused for large amounts of output data.

In addition to those features, this serverincludes support for in-memory CGIprocessing, security, and URL handlers.All the details on those goodies can befound in the API documentation availablefrom the demo server setup web pages.

SPINNING UP A WEB SERVER To be honest, before I downloaded the

GoAhead WebServer V.2.0 code, I reallydidn’t think I would get this to work. In myexperience, most of the stuff you get for“free” is worth exactly what you pay for it.So, I prepared myself for bunches of bittwiddling and customization.

I was also concerned with the lack of online documentation the web site keptalluding to. W hen I couldn’t find the how-to stuff I thought I’d need, I checked out thenewsgroup. I found some interesting

I’m using Windows NT here to explore,not deploy, an embedded version of theserver. In reality, NT and GoAhead Web-Server would work well together in an Intra-net- or Internet-application environment.

This server incorporates several

features, including Active Server Pages(ASP). ASP is another one of Bill’s concoc-tions developed to serve web pages withdynamic content. ASP documents aredelimited by an extension and useembedded scripting to insert dynamic databefore a page is sent to the user’s browser.

The GoAhead WebServer supports anopen-scripting architecture. This enablesscripting engines to be selected at run-time with the possibility of individual pagesusing multiple scripting engines at will.

JavaScript is the only scripting engineyou’ll hear about in this segment becausethe GoAhead WebServer V.2.0 supportsEmbedded JavaScript natively. The pack-age even includes an embedded-oriented

JavaScript API set.

Listing 1—An oasis of w ords. Guess which set of instructions I executed?

Page 41: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 41/68

A P C

CIRCUIT CELLAR OCTOBER199952 www.circuitcellar.com

entries, but nothing Icould use at the time.

One entry even asked,“Where or how do I start?”

With that, I was determined toanswer that question for myself.Not knowing what I was getting into,

I prepared a Windows NT 4.0 workstationwith lots of disk and memory space and ahefty processor. I loaded up every serviceI thought I would need.

Just in case I needed access to externalutilities from other machines in the lab, Iadded the web-server machine to the labdomain. This arrangement would also makeit easy to test and troubleshoot my newfoundweb server. I assigned the IP address of 10.10.0.1 to the initial test web-servermothership. Finally, I laid in Bill’s C++ V.5,N etscape Communicator 4.5 , and

downloaded GoAhead Web-Server V.2.0.Before running the unzip process, I

opened the zip file with WinZip andlooked over the package. I wasoverwhelmed with the amount offiles with names that looked like theymight point me in the “get started” direction.

I started looking through them and gotthe scent, but I still couldn’t tree anything.(For those of you consulting your techmanuals for the “tree” process, that’s asouthern hunting term for the process of

cornering and thus “treeing” your game.As this term is usually invoked whenhunting squirrels and opossums, “tree” isa very appropriate term here.) Eventually,I found a couple of files and the

Listing 2—This snippet uses the JavaScript API. All J avaScript API members begin with .The definition for can also be found in the code example.

chase began. (I’ve never done the fox andhorses thing, so let’s move on.)

The file was most helpful. The first paragraph apologized for the

seeming lack of documentation andreminded me that this was a beta version.I was assured that full documentationwould be provided with the full release of V.2.0. I was then instructed to consult thehome page ( )for access to the beta documentation.

As I read further into the text,I was also assured that I had everything Ineeded to compile and run a GoAheadWebServer. I was beginning to feel better,but I still had no clue until I read the blurb

you see in Listing 1. With this discovery,I decided to GoAhead and unzip the webserver package and attempt the compile.

Everything was unzipped and endedup in the directory. Just like

the file said, there was asubdirectory for every supportedOS and a gaggle of C files and Cheader files spattered about the

directory.It wasn’t difficult to determine

that was the directory I needed. The text in Listing 1 pointedto it, and stood out amongother subdirectories such asand . I was told that I hadeverything, so I ran the NT compilecommands in Listing 1.

The linker gave me the hi sign. The compile and link were successful. To my surprise, after executing webs,I had a working GoAhead W eb-

Server! Well, at least according to theSystem Tray GoAhead WebServer entry.

The only way to know for real was to serveup a page from 10.10.0.1.

I added an entry to the file of another workstation to map GoAhead to10.10.0.1. On the same workstation Istarted Netscape and entered

and the home page shown inPhoto 1 appeared in the browser window.

At this point, everything I was lookingfor was now in one place. All of thedocumentation could be accessed fromthe browser. By following the includedsource code, I was able to easily followthe flow of how the server and its Embedded

JavaScript and API sets worked together.As it turns out, I got the server tooperate without twiddling bits or specialcustomization. This isn’t to say that itcannot or should not be customized. Theidea behind GoAhead W ebServer is towelcome any type of customization.

There’s a section that describes somebasic GoAhead W ebServer configurationswitches, but the server is intended toprovide a basic platform for the webdeveloper to build on. I must agree thateverything needed to assemble a fullyfunctional web server is included for free.For that person in the newsgroup who waspleading for help, just go after it like I did.

You’ll be pleasantly surprised. and in the

directory describe how the server is initial-ized. These files also show how to mapweb-server functions to C code and the APIsets. Listing 2 is a code snippet from

that describes how a test JavaScriptapplet is coded behind the scenes.

The test applets are included with theserver code and can be accessed from the

Photo 2—This embedded PC is a desk-top in embedded clothing. You can get this baby with Pentium power, too.

Page 42: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 42/68

CIRCUIT CELLAR OCTOBER199954 www.circuitcellar.com

page. The whole GoAheadWebServer package is wide open likethis. Proprietary is a bad word here.Within this server, there’s enough APIfunctionality to fill three or four columns.

As I’ve shown, it’s a snap to put thisserver up. The key is to install the Web-Server prototype, which unlocks the soul of the product. So, download a copy andinstall it, and I’ll leave the reading to you.

THE HARD(WARE) PART Their home page states that GoAhead

WebServer was designed expressly forthe embedded web-server developer. Thismeans that the footprint must be small andthe functionality must be immense.

Now that I’m over my skepticism of thesoftware, how does it take to various typesof hardware? My first thought was to find

every piece of embedded hardware in theFlorida Room and attempt to install theserver and serve some pages.

RIDING A SNAKE The first piece of hardware I came

across was a Teknor VIPer806. This boardis quite broad as far as peripherals areconcerned. My VIPer has a 100-MHz’486DX2 processor, 16 MB of RAM, anSMC Ethernet adapter, the usual comple-ment of parallel and serial ports, IDE and

floppy interfaces, keyboard and mouseports, an SVGA adapter, and bunches of other stuff that you would normally find ondesktop machines.

I figured this little monster would easilyhandle a load of NT and the server software.I see the VIPer as an embedded desktop.

To make things easier, I dug out an ISA-based Tempustech backplane. Using astandard passive backplane makeschanging embedded platforms easy. Thepower plane is an integral part of thebackplane, and the embedded engines Iwill use (or attempt to use) plug right intothe ISA socket strips.

Because NT is being used as the testplatform, a hard disk and a CD-ROMdrive were used here too. Of course in anactual embedded implementation, I wouldemploy the flash memory on the VIPer806and use a smaller or embeddable OS. I’msure I could fit NT into an embeddedplatform by tossing out some of the fat, butthat’s not why we’re here today.

If you’re familiar with Windows NT, youknow it’s fat and robust, and that there are

many ways to load N T. I configured theVIPer to use the hard disk, floppy, and CD-ROM just as a desktop would.

I attempted to load NT Workstationusing the three install diskettes. Everythingwent fine until the reboot after the text installphase. Seems the VIPer couldn’t find theboot files on the hard disk and just hung up.

After a few hours, I gave up and

decided that I had somehow damagedthe VIPer or the hard disk was loopy. So,I loaded Bill’s DOS 6.22. I knew I couldn’tboot from CD-ROM and load NT becausethe BIOS in the VIPer wasn’t at the latestlevel and didn’t mention CD-ROM support.

I knew I would eventually have to usethe CD-ROM to complete the load of N T.DOS was loaded and operational, andthe VIPer seemed to be OK. So, why notload the CD-ROM driver under DOS andperform the NT install from the CD-ROM?

It took some time, but I finally completedthe install and hooked the VIPer into thelab domain. Loading software isn’t alwaysa piece of cake, and I had some troublegetting the VIPer806 Ethernet drivers totake, thanks to a signature on the originalVIPer driver diskette that NT didn’t like.

I ended up imaging the diskette to adirectory on the VIPer hard disk, and I gotrid of the offending file by process of elimination. After getting the SMC 8416Ethernet card to load, the server codewent on as easily as it did on the mother-ship, and I was serving pages in no time.

Photo 3—It may be cheap and it may be ugly,but it runs!

Page 43: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 43/68 OCTOBER1999 EMBEDDEDPC 55www.circuitcellar.com

Fred Eady has over 20 years’ experience as a systems engineer. He has worked withcomputers and communication systems large and small, simple and complex. His forte is embedded-systems design and communica-tions. Fred may be reached at [email protected].

If you’re going to run NT on theVIPer806, be sure to use plenty of RAM.It’s a wet dog in the cold with 16 MB of RAM. And for you NT gurus, no, I didn’tcheck the NT hardware compatibility listto see if the VIPer or the CD-ROM drivewas tested or accepted.

The way I see it, if I can make it work withtroublesome and problematic hardware,

just think of how big a hero you’ll be bymaking it work with approved equipment.

The VIPer setup is shown in Photo 2.

GOAHEAD ON THE CHEAPI’ve gotten GoAhead WebServer to

load and run on two pretty rich machineswith not-so-uncommon backgrounds. Let’sstep it down a notch. Photo 3 is thereduced-instruction setup. The “down-graded” web server is based on an

inexpensive Tempustech VMAX SBC301. The VMAX board is a ‘486SXLC running

at 66 MHz with only 8 MB of RAM. Thatmeans Windows NT won’t fly. Just forgrins I tried loading Windows 98.

Did you know Win 98 requires a mathcoprocessor? Did you know the programtells you if you don’t have one? OK, I getit. Windows 95 it is.

In addition to the VMAX CPU board,the “downgraded server” hardwareincludes a $14 SVGA board, an SMC8416

Ethernet adapter, the VIPer spinning diskset, and the Tempustech ISA backplane.During the Win 95 WebServer install

I encountered an interesting anomaly. Iused a 2-GB IDE drive for the VIPerconfiguration and attempted to do thesame with the VMAX board set. TheVMAX wouldn’t recognize or configurethe 2-GB drive. I couldn’t even manuallyenter the cylinder/ sector count data in thesetup fields. The VMAX BIOS maxed outat 2048 cylinders and the 4092-cylinder2-GB drive hung the system at startup.

The smallest drive I had on the benchweighed in at 1.7 GB. I figured the VMAXwould choke on that one, too. So, Iresorted to a 250-MB Western Digital Ifound in a box in the corner of the lab.

After I installed the little W D drive, theVMAX went into autoconfiguration modeon powerup and found the smaller drive,

just like the manual said it would.Sometimes bigger isn’t better.

The good news is that I have someclear spinning media looking for somenew code. The bad news is that I’m sure

I’ll have to shoehorn every bit of that newcode including the OS, Bill’s C++ compiler,and the server onto it.

Only 225 MB later, I was serving webpages to the domain members from theVMAX platform. But, I wasn’t able tosuccessfully compile the server code in thenative VMAX environment (probablybecause of the lack of real memory andenvironment space).

I copied over the server executablefrom the mothership via the LAN. VMAXdidn’t know the difference. The VMAX“stack” is shown in living color in Photo 3.

GOING AHEADI’m a firm believer in the future of

anything that’s embedded and uses theInternet or Intranet to control and monitorremote devices. GoAhead WebServer is

a step toward bringing this technology toall of us faster. With Windows NT, thisserver is a good way to start or extendyour understanding of embedded web-server technology.

As you’ve seen, Windows NT isn’tnecessarily the best (or the only) solutionforprojects such as this one. The real beautyof this freeware concept is that you canuse this software with any embeddedplatform you can port it to. Not to mentionthat having access to the free code gives

you a head start on making a difference inthe embedded control world. APC.EPC

SOURCESWindows NTMicrosoft Corp.(206) 882-8080

Fax: (206) 936-7329www.microsoft.com

GoAhead WebServerGoAhead Software, Inc.(425) 453-1900Fax: (425) 637-1117www.goahead.com

VIPer806 Teknor Microsystems, Inc.(514) 437-5682Fax: (514) 437-80 53www.teknor.com

VMAX Tempustech(800) 634-0701(941) 634-2424

Fax: (941) 643-4981www.tempustech.com

Page 44: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 44/6856 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Figure 1—The start switch (S1) that activates the LEDs is

connected to the microcontroller’s master clear input pin (*MCLR).

Hands-On PIC Trainer

FEATUREARTICLE

Jon Varteresian

iSometimes it takes asimple project tolearn the practical

(and fun) applicationsof a basic technology.That’s the idea be-hind Jon’s assembly-coded device thatprovides immediate

visual feedback with-out a simulator.

f I can borrow aline from Fred

Eady, I’d have to agree,“ It doesn’t have to be

complicated to be embedded.” Some-times it can be simple. Sometimes itcan just be fun. And I’m sure you al-ready know that doing something funis a great w ay t o learn the basics.

The assembly-language firmwaredescribed in this article demonstratesbasic PWM techniques, timer opera-tion, a nd general I/O m anipulat ion.The informat ion presented here willenable you to ta ckle a wide range ofembedded-control problems.

I designed a simple electronic safetydevice for nighttime joggers—or even,given that it’s October, trick-or-treat-ers. Its hi gh-brightn ess LED s alert on-coming traffic to your presence.

This device is built aroundMicrochip’s P IC16LC54A. Thismicrocontroller includes an8-bit data path, 12-bit instruc-tions, an 8-bit timer, 512 bytesof ROM, and 25 bytes of RAM.

As for pow er, ty pically, coincell battery–operated devicesand LED s aren’t a good mat ch.A current-hungry LED candrain a battery in mere hours.Having m ore than one LED onat any one t ime drains the bat-tery even faster. Unless you use

some kind of intelligent power-con-servation t echnique, your bat tery bil lis going to be quite high.

Several pow er-conservation tech-niques can be used in this design,including:

• low ering the LED s’ forward cur-rent—this extends battery life butat the cost of the w earer’s safety

• enabling one LED at a t ime, cyclingthrough all eight—this helps pre-serve the batt ery, but the visualpattern of the LED s is l imited, ifnot boring

It’s more visually appealing if therew ere tw o (or more) LED s on at a nygiven time. This pattern can be ac-complished by turning on LED A for a

short t ime w hile B is off , and thenturning A off and B on.

If the cycle repeats fast enough, thehuma n eye can’t detect th e f lashing.So, it appears that both LEDs are on,granted at a slightly reduced light-level output.

That’s the technique employed inthis firm w are. It produces an ever-changing, multi-LED pattern eventhough only one LED is conducting atany given time. This technique ex-

tends the device’s 3-V, 150-mAh bat-tery life to w ell over 10 h.

First I’m going to describe the as-sembly-language programming details,and then I discuss how to build theproject. Building the device is a pieceof cake—it uses surface-mount andthrough-hole components on a single-sided PCB. All you need is a fine-tippedsoldering iron and, depending on youreyesight, m aybe a m agnifying glass.

Program m ing in Assem bly

Page 45: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 45/68 CIRCUIT CELLAR ® Issue 111 October 1999 57www.circuitcellar.com

CIRCUIT OVERVIEWThe circuit show n in Figure 1

comprises a microcontroller (U1,PIC 16LC54A), eight LEDs, on esw itch, one battery, and a sprin-kling of resistors and capacitors.

When you press and releasethe sw itch, th e PIC’s programcounter is reset to the beginningof code space and the lightingsequence begins. To t urn t heLEDs off, press and release thebutton again.

Power is supplied to the micro-controller and LED s through the bat -tery (B1), w hich i s a sta nda rd 20-m m3-V coin cell. Resistor R10 and capaci-tor C 1 generate an RC clock input forthe PIC. The operating frequency is anominal 256 kHz, which means that

the instruction rate inside the PIC is:1

256 kH z× 4 = 15.625 µs

The RC operating mode of the PICis inherently imprecise and can varyas much as 20%. However, this appli-cation is relatively timing-insensitive.Resistors R1–R8 (36 W) limit thecurrent through the LEDs to 25 mA.

Not e that , besides the LEDs, al l ofthe components are of the surface-

mount variety. If you decide to getcreative and put artw ork on the oppo-site side of the PCB, through-holecomponents would get in the way.

FIRMWAREThis device is a useful educational

tool because w hen you experiment w iththe firmw are’s assembly code, you getimm ediate feedback. D id you programit r ight? You’ll know right away.

Everyt hing begins w ith a low -to-

high pulse on *MC LR. Once thispulse is generated, it resets t he pro-

gram counter of the PIC to t he begin-ning of code space.

The PIC init ial izes al l softw arevaria bles, configures all I/O, an d setsup timer0 for internal clocking and aprescaler value of 4, so every time the

internal instruction clock incrementsfour t imes, the t im er increments by 1.Remember that t he PIC is executinginstructions every 15.625 µs.

Next, the PIC inverts .This variable decides w hether t o be-gin flashing the LEDs or put the PICinto Sleep mode. If is a1, the PIC begins flashing the LEDs. Ifit’s a 0, the PIC goes to sleep.

Remem ber, softw are variablesdon’t lose their state in Sleep mode.

The only time they lose their state isw hen power is removed. By inverting

every time someonepresses the mom entary butt on, thedevice effectively turns on and offwith every push.

The PIC loads t im er0 wit h a valueequal to 7 ms. Note that the t imercounts up and is considered to be ati ts terminal count w hen i t rolls from0xFF to 0x00.

Normally when a t imer rolls, an

interrupt is generated, causing aninterrupt handler to handle the event.

Because the ’16LC54A doesn’thave interrupt capabili ty, t hecounter must be manuallypolled. When it finally rolls, thePIC reloads the timer to countanother 7 ms, executes the nextsection of the code, and thenreturns to the tight loop beforethe 7 ms are up.

Before w e can discuss w hathappens wh en the 7-ms coun terrolls, we need to tak e a look athow th e LED s are enabled. First,let’s define a rule that restricts

how the f irmw are operates.Because the batt ery is sm all and

can’t provide a lot of instantaneouscurrent, only one LED can be enableda t any g iven t ime. So, i f you w ant tw oLED s on at once, you’ll have to f ind

ano ther w ay to do i t .Let ’s assume tha t you w ant tw o

LED s (A and B) to appear to be on atthe same time. The device does this isby tu rning LED A on and LED B offfor a short period of t im e. Then LEDA is turned off and LED B is turned onfor the same short period of time. Theprocess is then repeated continuously.

If the LEDs are turned on and offfast enough (faster than 60 times persecond), human eyes can’t perceive

that the diodes are actually turning onand off. Although their brightness isreduced, both LEDs will appear to beon at the same t ime.

The LEDs are tu rned on and offevery 14 ms (71.5-H z rat e). That ex-

plains the reason for the 7-ms counter.It equa ls hal f of th e on/off period.

If you only w ant one of the LED sto be l i t , you w ould st i l l need to usethe above steps except that LED Bw ould be absent. LED A is lit for a

short amount of t ime and then i t isshut off for the same am ount of t im e.

Table 1— Here’s the order in which the LEDs are enabled for each of the eight patterns.When Pattern 8 is completed, the cycle restarts at Pattern 1.

Pattern Pattern Pattern Pattern Pattern Pattern Pattern Pattern1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 88 and 2 1 and 3 2 and 4 3 and 5 4 and 6 5 and 7 6 and 8 7 and 17 and 3 8 and 4 1 and 5 2 and 6 3 and 7 4 and 8 5 and 1 6 and 26 and 4 7 and 5 8 and 6 1 and 7 2 and 8 3 and 1 4 and 2 5 and 3

5 6 7 8 1 2 3 46 and 4 7 and 5 8 and 6 1 and 7 2 and 8 3 and 1 4 and 2 5 and 37 and 3 8 and 4 1 and 5 2 and 6 3 and 7 4 and 8 5 and 1 6 and 28 and 2 1 and 3 2 and 4 3 and 5 4 and 6 5 and 7 6 and 8 7 and 1

1 2 3 4 5 6 7 8

Figure 2—As this LED enable waveform shows, LED A is enabled while LED B is disabled, and then the roles are reversed.

LED A

LED B

On

Off

On

Off

7 ms

14 ms

LED A on LED B on

Page 46: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 46/6858 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Figure 3—Seeing the order in which the LEDs are lit for the first three patterns makes it easier to extract the formulas to describe each LED pattern.

the single LED rotates one LED clock-w ise and the patt ern repeats.

The eight possible LED pat ternsare show n in Table 1 . Note tha t eachsubpatt ern is enabled for 14 ms × 8,w hich equals 112 m s.

Now , we need to f ind a way t ocode that pattern without explici t lycoding each step. Although there’s noreason w hy a brut e-force m ethod ofcoding the pattern wouldn’t work, i t’sjust not very challenging. There has tobe an overlying pattern that w e canuse to generate each subpattern.

To find this overlying pattern, takean 8-bit register and put an X in theb i t loca t ion when you w ant an LED toturn on. I f you star t with Pattern 1,you’ll end u p w ith Figure 3. The LEDsare numbered from 1 to 8, and the

registers are numbered 0 to 7.Figure 3 should help you figure out

the rules for determining w hich diodesshould light. Not e the cells w ith th ebold blue X in them. This pattern isnothing more than a circular left shift.

D escribing the cells w ith t he non-bold blue Xs is only a little more com-plicated. I t’s a circular right shif t w ith

a twist . The twist is that every ninthshif t is a lef t instead of r ight. N ow , byinclusive-ORing these tw o shift pat-terns together, you can generate thepatterns you want.

This circular right shift techniqueis much easier than t rying to code allthe individual subpattern states. Thetw o registers that contain t he shiftpatterns are called and

.Once the 14-ms cycle time is de-

fined and the pat terns described, weneed to determine w hich LED s w ill beon and off wit hin the subpatterns.This dilemma is resolved by takingthe first subpattern in each patternand defining the A LEDs to be the bold-X LED s plus X + 1, X + 2, and X + 3.Each of the remaining four LEDs plays

the part of the B LED.If you try t o assign a fixed pattern to

th e LEDs (e.g., LEDs 1–4 are A, an d 5–8 are B), it w ill result in som e sub-patterns having both desired LEDs ineither t he A or t he B group. The vari-able contains the A or Bdesgination informat ion and is used bylogical ANDing w i t h

LEDs

8 7 6 5 4 3 2 1Pattern X 1 X X

X XX X

XX X

X XX X

XPattern X 2 X X

X XX X

XX X

X XX X

XPattern X 3 X X

X XX X

XX X

X XX X

X

Figure 2 show s the LED -enable w ave-forms a nd t he on-off periods.

N ow , let’s define a patt ern. Eachpattern starts as a single lighted LEDand t hen travels in pairs around thecircuit board until reaching the oppo-site side w here it ends in a single LEDand then t ravels back. At t hat point ,

Page 47: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 47/68 CIRCUIT CELLAR ®

www.circuitcellar.com

the inclusive OR of theand variables.

By coding the LED pattern in thismanner, substantial code compressionis achieved, w hich leaves valua blecode space to handle other tasks.

By the way, if you wish to modifythis f irmw are, you need a suite oftools available from Microchip. Mostof the PIC tools are free, including theassembler and simulator, and can bedownloaded the M icrochip web si te .

ASSEMBLYBegin by programming the PIC

w ith t he source and programm ingfiles, w hich are available via the C i r - cu i t C el l a r w eb si te. Next, solder thePIC t o the circuit board and note thelocation of pin 1.

Att ach t he sw itch (S1) and solderthe 10-k Ω resistors (R9 and R10) andth e 300-pF capac it or (C 1). N ow solderthe eight 36- Ω resistors and the coincell bat tery h older (B1). And t hat com-pletes the main circuit assembly ex-

cept for the LEDs.Of course, you can put a label onthe front of the device. Then, using acommon straight pin, poke 16 holesfor the LEDs and push the leadsthrough the circuit board. Bend theleads slightly to hold each LED inplace wh ile you insert t he others.

Before you insert each LED, notethe location of pin 1 (or anode). Pin 1,(identified by t he longer of the t w oleads) must go to the square pad onthe circuit board. When you’re done,solder all 16 leads and trim the excess.

Figure 4—If everything has been done right up to this point, probing the PIC’s clock signal (pin 16 of U1) with an oscilloscope should result in a waveform like the one shown here.

1/27/99 8:47:32 PI

2 µs/div 0 .4 V /d iv 0 .113 VDC 1.73 V p-p 0.571 V rms –62.7 dB

dV = 0 .0252 V d t = 5 µs f = 200 kHz

Jon V art eresian ow ns and operates JV Enterprises, w hi ch offers educat ional electroni c ki ts and provid es con- sult in g servi ces. Jon special izes in deep em bedded control of w ireless tr ansceivers and u ser int erface m anagem ent . You m ay reach him at

j v en t erpr i ses@w or l d n et t .a t t .n et .

SOURCESProject componentsJV Enterprises(978) 928-5655jventerprises.home.att.net

Digi-Key Corp.

(800) 344-4539(218) 681-6674Fax: (218) 681-3380w w w .d igi -key.com

All Electronics(800) 826-5432(818) 904-0524Fax: (818) 781-2653www.al le lec t ron ics .com

Jameco(800) 536-4316(415) 592-8097Fax: (415) 592-2503www. ja m e c o .c o m

DID YOU DO IT RIGHT?The last step is to

insert the coin cell bat-tery in the bat tery holderwith the posit ive termi-nal positioned up. Now press and release thereset button (S1).

If you’ve assembledeverything correctly, theLEDs will star t to f lash.If they don’t, check yourw ork for solder bridges(shorts) or faulty solderjoints. If that doesn’thelp, use an oscilliscopeto probe the PIC’s clocksignal (see Figure 4).

And there you have it—a simplew ay t o learn programm ing in assem-

bly on a PIC. I

SOFTWAREAlong w ith a complete parts l ist ,the source and programming filesfor this project can be downloadedf rom t he Circu i t C el l a r web si te .

Page 48: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 48/6860 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

IrDA Technology

FEATUREARTICLE

Hari Ramachandran

oCameras talking toPDAs, talking to PCs,talking over theInternet, talking toeach other…?Once you get thelatest word on IRcommunicationstandards, yourembedded designswill want to join theconversation, too.

ur industry is rifewith acronyms. Most

engineers shudder w henan industry a ssociation is

formed and yet another set of acronyms

is spawned.In 1994, the Infrared Data Associa-

tion (IrDA) w as formed by a group ofcompanies, including HP, IBM, andSharp. The goal of th e association w asto promote t he ubiquitous deploymentof infrared appliances that interoperatewith each other.

For this to happen,both t he physical layerand protocols for com-municat ion needed to be

established. Much to t hecredit of the companiesin the IrDA, these speci-

Figure 1— There are three major layers needed in a basic IrDAapplication—physical, protocol, and application. A basic IrDA link requires a reliable physical layer and

IrLAP/IrLMP layers. What’s loaded on top of those layers is up to you.

fication s w ere adopted and ratified inless than a year.

By 1995, laptop PCs and IrDA PCadapters that adhered to t he standardmade their appearance and Microsoftreleased IrD A support for Window s 95.Since then, in fits and starts, IrDA hasbeen adopted in almost all laptops andis being used in consum er devices(e.g., digita l cam eras, cell phones, andpagers). How ever, the breadth of t hetechnology and i ts applications hasleft even seasoned industry w at chersand engineers a bit dazed and confused.

My goal here is to dispel some ofthe confusion and provide an overview of IrD A technology. I w ant to focusspecifically on physical-layer imple-mentations, which will be the focusof Part 2 next m onth.

THE VISIONBefore delving into the details, it’s

a good idea to discuss the purpose ofthe IrDA. The key concept is ubiquitousinteroperability—the ability to inter-connect to a variety of devices, exchangefiles, electronic business cards, andimages, print documents, and synchro-nize data betw een PD As and desktopPC s, cell phones, and IR w atches.

For the IrDA’s goals t o be reached,

a number of key technical hurdlesneeded t o be overcome. First of all,the physical-layer specification had tobe ratified. These specifications in-cluded w avelength, t ransmissionpower, comm unication speed, anddata-modulation schemes.

Part 1: An Overview

IrDA-SIR 1.0(115.2 kbps)/FIR 1.1 (4.0 Mbps)

IrLAP (Link access protocol)

IrLMP-MUX (Link management protocol)

IrLMP-IAS – Information access services

Tiny TP (flow-control for a multiplexed channel)

IrCOMM – printer, RS-232C emulation

IrOBEX – Object exchange protocol

IrTranP – IR transfer picture protocol

IrMC – IR mobile communications

Physicallayer

Protocollayer

Applicationlayer(s)

Page 49: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 49/68www.circuitcellar.com CIRCUIT CELLAR ® Issue 111 October 1999 61

Next, a robust rel iable data com-municat ion protocol had to be estab-lished. The protocol needed to t akeinto account t he ad hoc nature of a

w ireless connection as w ell as supportpoint-to-point connectivity and theability for devices to negotiate capa-bil i t ies like data frame size and m axi-mum communication transfer rate.

And last, in order for devices tocomm unicate, application layers forcomm unication betw een cell phones,digital cameras, and PDAs needed tobe established.

IrDA LAYERSThe end result of almost three years

of discussions and various levels ofexecution is the IrDA architecture.Each layer is described in the sectionsshow n in Figure 1.

At th e lowest level , the physicallayer specifies the physical character-istics of the infrared medium, the data-modulation scheme used, and thestructure of an IrDA frame. G enerally,the physical layer comprises a UART,a m odulat or/demodulat or ASIC, and

an IrDA-compatible transceiver.Tables 1–2 describe key characteris-tics of the IrDA physical layer.

For data rates up to and including1.152 Mbps, the return t o zero inv erted(RZI) modulation scheme is used and alight pulse represents a 0. For rates upto and including 115.2 kbps, the opticalpulse duration is 3 ⁄ 16 of a bit duration(or 3 ⁄ 16 of a 115.2 kbps-bit duration).

For 0.576 and 1.152 Mbps, the opticalpulse duration is 1 ⁄ 4 of a bit duration.Informally, communication rates upto 115.2 kbps are termed serial infrared

(SIR). A signaling rate of 1.152 Mbpsis termed MIR, and a 4-Mbps rate, FIR.Figure 2 illustrates the basic buildingblocks for an SIR implementation.

The RZI (SIR) encoding schemeshow n in Figure 3 relies on a clock t odrive the m odulation engine. This clock(16XC LK) is set to 16× the com mu ni-cation transfer rate.

For example, if communication at115.2 kbps is requi red, 16XC LK is set to:

16 × 115200 = 1.8432 MH z

A space or 0 TXD valu e is encodedas a single pulse (IRTX) of duration ( 3 ⁄ 16)of the bit t ime or:

1

115200×

3

16= 1.63 µ s

The demodulation schemestretches the received pulses (IRRX)to recreate the original signal (RXD).A practical implementation of an SIRphysical layer solution is describedin Figure 4, w hich out lines a practi-cal microcomputer-based SIR physi-cal layer solution.

The key building blocks a re theHP HSDL 1001 (an IrDA transceiver

designed to accommodate signalingrates up to 115.2 kbps), an HP HSDL7001 or Parallax’s PLX 7001–IrDAEndec (applies the RZI [SIR] encoding

scheme as described in Figure 3), andD alla s’ 80C 320 (8051 CP U derivat e).

If run at 25 MHz, the 80C320 caneasily accommodate communicationup to 115.2 kbps. The UART signals(TXD and RXD) are tied to the HSDL7001. Three control lines from theDallas chip are used to set the signal-ing rate of the HSDL 7001.

Table 1— The pulse durations for each signaling rate can be critical in building a reliable physical-layer implementation.Issues can arise if the pulse duration generated by the IrDA transceiver doesn’t match that supported by the encoder/ decoder.

Rate tolerance Pulse duration Pulse duration Pulse durationSignaling rate Modulation % of rate minimum nominal maximum

2.4 kbps RZI ±0.87 1.41 µs 78.13 µs 88.55 µs9.6 kbps RZI ±0.87 1.41 µs 19.53 µs 22.13 µs19.2 kbps RZI ±0.87 1.41 µs 9.77 µs 11.07 µs38.4 kbps RZI ±0.87 1.41 µs 4.88 µs 5.96 µs57.6 kbps RZI ±0.87 1.41 µs 3.26 µs 4.34 µs115.2 kbps RZI ±0.87 1.41 µs 1.63 µs 2.23 µs

0.576 Mbps RZI ±0.1 295.2 ns 434.0 ns 520.8 ns1.152 Mbps RZI ±0.1 147.6 ns 217.0 ns 260.4 ns4.0 Mbps

(single pulse) 4PPM ±0.01 115.0 ns 125.0 ns 135.0 ns(double pulse) 4PPM ±0.01 240.0 ns 250.0 ns 260.0 ns

Table 2a— To be compliant, IrDA optoelectronics must comply to these physical specifications as well as the irradiance specifications outlined in (b).b— Matching the transmission/receiver power of an IrDA optoelectronic

pairing is critical. The IrDA protocol allows multiple devices to be “discovered,” so a device that transmits too muenergy can saturate other listeners and drown out other devices.

Specification Data rates Minimum Maximum

Peak wavelength, up, µm All 0.85 0.90Max. intensity in angular range (mW/Sr) All — 500Min. intensity in angular range (mW/Sr) <_ 115.2 kbps 40 —Min. intensity in angular range (mW/Sr) 115.2 kbps 100 —Half-angle, degrees All ±15 ±30Signaling rate (i.e., clock accuracy) All See Table 1 See Table 1Rise rime (Tr) 10–90%, <_ 115.2 kbps — 600 fall time (Tf) 90–10% (ns)Rise rime (Tr) 10–90%, 115.2 kbps + — 40 fall time (Tf) 90–10% (ns)Pulse duration All See Table 1 See Table 1Optical overshoot, % All — 25Edge jitter, % of nominal bit duration <_ 115.2 kbps — ±6.5Edge jitter relative to reference clock, 0.576 & 1.152 Mbps — ±2.9

% of nominal bit durationEdge jitter, % of nominal chip duration 4.0 Mbps — ±4.0

Maximum irradiance All — 500 in angular range (mW/cm 2)Minimum irradiance <_ 115.2 kbps 4.0 — in angular range (µW/cm 2)Minimum irradiance 115.2 kbps + 10.0 — in angular range (µW/cm 2)Half-angle, degrees All ±15 —Receiver latency allowance (ms) All — 10

a)

b)

Page 50: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 50/6862 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Listing 1, writ ten in 8051 assemblylanguage, demonstrates how to set upboth t he D allas 80C 320 as w ell as theHSDL 7001 to send out the character“ h” repea ted ly.

Because the HP HSDL 1001 doesn’toptically isolate the send and receivechannels, you’ll see data coupling backwhen you transmit data, causing anapparently spurious reception of data.When implementing a half-duplex link,be sure to accomm odate this si tuat ionby clearing t he receive buffer aft ersending out a frame or byte of data.

One other critical issue to under-stand when implementing an IrDAlink is latency, which ties into the factthat there’s no optoisolation betw eenthe send and receive channels. Duringtransmission, the sender sends out a

byt e to th e responder device, w hichcauses th e receiver on the sender tosaturate, thereby causing a loss in itsreceiver sensitivity.

For the HSDL 1001, the latency is10 ms. In that 10-ms period, any datareceived w ill most l ikely be corrupted.The t rick is for th e responder to h oldon for 10 ms after receiving beforeattempting to send any data to thesender. In IrDA t erminology, th is tim elag is known as the minimum turn-

around time and is ordinarily handledby the infrared link access protocol(IrLAP) layer.

4PPM MODULATIONFor 4.0-Mbps communication, the

modulation scheme is 4PPM. 4PPMmodulation is achieved by defining adata symbol duration ( D t ), ordinarilyset to 500 ns, and dividing this intofour time slices, called chips. Theduration of each chip is 125 ns.

Because the signaling rate is 4 Mbps,each D t period w orks outto tw o data bits (D t = 500 ns= 2 × 1 ⁄ 4 Mb ps). D ur ing aspecific D t , only one chipcan be a logical one.

D espite the relativesimplicity of the 4PPMmodulation scheme, build-ing a practical 4-Mbpshardw are scheme is non-tr ivial . Simply put, the4-Mbps datastream is fast!In addit ion to a 4PPM

modulation engine, you need a serialcommunication controller that handlesDMA if you’re going to build a practi-cal 4-Mbps hardw are scheme.

Figure 5 outlines a relatively low-cost 4-Mbps hardw are scheme. Let’slook at the key modules for this solu-t ion. The H P H SD L 1100 FIR trans-ceiver supports communication allthe w ay from 9600 bps to 4 Mbps.

The NS 87109 UIR controller en-compasses the 4PPM and RZI m odula-tion schemes (supports 9600 bps to4 Mbps). It a lso funct ions as a serialcommunication controller, and handlesdata int egrity, bit stuff ing, and CRCcalculations (which, at 4 Mbps, aretoo com plex to do in firmw are).

The ’87109 also su pports D MA,w hich is another critica l performa ncefact or. Though a polled I/O a pproachcan be used t o receive 4-Mbps dat a, it

requires too m uch C PU overhead.Because effective communication

w ith th e ’87109 using regular polledI/O is usually not w orkable, I chose theN EC V850E/M S1 single-chip processor.It supports up to 128-KB internal flashmemory and up to 4 DMA channels, soit’s ideal for I/O-intensive applicat ions.

PROTOCOL LAYERSOnce a stable physical-layer imple-

mentat ion is put in place, the next

step is to build the protocol layers.

First-pass processing of received IRframes is handled by the IrLAP layer.The IrLAP layer is a variant of the IBMHDLC protocol, modif ied to take intoaccount t he ad hoc nat ure of wirelessconnectivity.

The IrLAP layer controls discoveryof devices w ithin range, uniquely iden-tifies those devices, and establishes areliable, error-free communication chan-

nel. You can think of it as a glorifiedwire that’s implemented using infrared.

IrLAP commands are passed up tothe infrared link mana gement protocol(IrLMP ) layer, w hich allow s the singleIrLAP cha nnel t o be shared acrossmu ltiple logical chann els. This w ay, asingle IrDA device can support m ultiplefunctions (e.g., faxing, printing, andLAN access) through different logicalchannels w hile using the same physi-cal layer (a single IrLAP connection).

IrLMP is l ike a swit chbox that routesdata to and from the IrLAP layer.

INFORMATION ACCESS SERVICEBecause the IrDA protocol is in-

tended to be used wit h a variety ofappliances, w e need a w ay t o identifythe features supported by the device.The information access service (IAS)accomplishes just that. Think of theIAS as a Yellow Pages of services andfeatures supported by the device.

For example, if the device is a cam-era, it advertises itself by anentry in t he IAS databasethat indicates that i t is acamera and includes infor-mation about an externaldevice that can connect t oit. The first t hing a connect-ing device does is send a“ query IAS” command todetermine what the deviceis and what i t can do.

Finally, on the protocollayer, is the t iny transporta-

Figure 3— The SIR encoding scheme relies on a clock (CLK16X) set to 16× the trans- mission bit time. The signal to be encoded is on the falling edge of TXD, an internal

timer “times” seven of the CLK16X pulses before pulling IRTX high for three clock cycles and low for the remaining six cycles. SIR decoding is the inverse of this process.

CLK16X

TXD

IRTX

16 × CLK16X

3 × CLK16Xor

1.6 µs fixed

7 × CLK16X CLK16X6 ×

Figure 2— These building blocks are what’s required for a basic SIR physical-layer implementation. You’ll need an IrDA-compliant optoelec- tronic device, an SIR encoder/ decoder chip, and a microprocessor with a built-in UART.

SIRencoder/ decoder(endec)

IrDAcompliant

optoelectronicsUART/

microprocessor

IRRX RXD

IRTX TXD

CLK16X

Page 51: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 51/68www.circuitcellar.com CIRCUIT CELLAR ® Issue 111 October 1999 63

Listing 1— The code I used to implement a simple 115.2-kbps communication link uses the hardware configuration from Figure 4 and programs the UART of the 80C320, sets up the 7001 for 115.2 kbps, and sends out a character “h.” Don’t confuse this code with a complete IrDA protocol stack implementation.

tion protocol (Tiny TP). Because theIrLMP layer supports multiple logicalchannels, Tiny TP is needed to preventa deadlock situation in w hich one chan-nel hogs th e IrLAP/IrLMP ch ann el. Ituses a credit transaction scheme tocontrol (or buy) access to t he chann el.

APPLICATION LAYERSAfter the physical and protocol

layers are built up, the next step is tobuild application support for thedevice(s) you w ant to com municat ew ith. I’ll just give a prelimina ry sum-mary of the application layers here.

Page 52: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 52/6864 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

The main methods of exchanging datathrough an IR connection are IrCOMM,IrOBEX, and IrTRANP.

IrCOM M is int ended for legacy-w iredserial or parallel port applications thatare to be converted to support IrDA.For insta nce, if you w ant t o replaceth e RS-232 w ired connection betw eena m odem a nd a PC , you need to con-nect an IrDA adapter to your PC andbuild an IrDA m odem adapter.

If the IrDA stack on your PC andmodem adapter contain the IrCOMMextensions, both your PC and m odemcontin ue to operate as if th e RS-232cable wa s connected. You can continueto use the PC modem application as ifyou were using a vir tual COM port .

If you install t he Window s 95 IrDAdrivers, t he IrDA protocol is exposed

as virtual COM and LPT ports on yoursystem. The IrCOMM layer essentiallyopens up the IrDA protocol through aseries of comm unicat ion API look-alikecomm ands, so changes to t he baseapplication aren’t required.

The infrared object exchange (Ir-OBEX) standard is intended as an OS-independent method of transferringobjects. If you want to send a file fromone device to another, IrOBEX estab-lishes the means of identifying and

converting the file into a universalobject that both devices can under-stand and interpret. It also specifies asimplified protocol of putting andgetting objects from devices.

Sony, Sharp, Casio, and a few otherdigital camera vendors established theinfrared picture transfer protocol (Ir-TRANP). IrTRANP enables users tobeam images between cameras, PDAs,PCs, and even directly onto the Internet.

An application developed by NTT

for the Nagano Olympics enabled usersto beam their images onto a personalw eb page via an IrDA kiosk. IrTRANP

H ari Ramachandran is the managing

di rector and found er of Parall ax Re- search, a design com pany f ocused on providi ng IrD A solut ions. He designed th e H P HSD L 7001 and H P HSD L 7000 IrD A chips, and developed I rD A proto- col s tack softw are for num erous com- panies and specifi c applicat ions. You m ay reach hi m at hari @parallax .com .sg.

Figure 4— This design uses a Dallas 80C320,the HP HSDL 7001 (encoder/decoder), and HP HSDL 1001 (IrDA optoelectronics) and is all that’s necessary to build a working IrDA(SIR) hardware implementation. To complete the full IrDA implementation, you’ll need to code the IrDA protocol stack, which can be the most daunting aspect of implementing an IrDAsolution.

HPHSDL1001

7001or

ParallaxPLX 7001

Dallas80C320

Txd

Crystal3.6864 MHz

Transfer rate selection

Rxd

IRTXD

IRRXDHP HSDL

Figure 5— Building a 4-Mbps IrDA solution is a more complex (and more expensive) undertaking than building a basic SIR solution. This practical building block uses an NEC V850E/MS1

CPU and NS 87109 universal IR controller chip and the HSDL1100 IrDA optoelectric assembly.

HSDL1100

FIRXceiver

NS87109

UIR controller

NEC V850E/MS1CPU

SRAM

used the IrCOMM layer to open a reli-able communication medium betweendevices, a simple command executionprotocol (SCEP) to manage the com-municat ion session, and binary f tpcomm ands to exchange images.

SAMPLE COMMUNICATION SESSIONNow you’ve been introduced to a

set of incredibly poetic-sounding a cro-

nyms and nifty concepts. But how doesthe IrLAP layer talk to the IrLMP layer,and how does IRTRANP come into thepicture? Let’s look at a session betw eena PD A and an IrTRANP cam era.

The user selects a n im age from aIrTRANP camera, points it at the PDA,and presses Send. All communicationis at the default IrLAP 9600-bps signal-ing rate. The camera sends an IrLAPdiscovery command, attempting to findIrDA-compliant devices.

After the PDA responds and identi-fies itself, the camera sends a negotia-tion request (to determine the PDA’smaximum communication speed) andconnects at that speed. Once an IrLAPconnection is established, the camerainitiates an IrLMP connection to chan-nel 0 (IAS channel) and q ueries w heth erthe PDA supports IrCOMM services.

The PD A responds, “ Yes. I supportIrC OMM , go ahead and connect t o chan-nel x , w hich is my IrCO MM channel.”

The camera disconnects from the IASchann el (channel 0), connects to t heIrCOMM channel (channel x ), and sends

an IrTRANP connect com mandthrough the IrCOMM channel.

After the P D A acknow ledgesthe IrTRANP com mand, t hecamera executes an IrTRANPput comm and and sends theimage over. Once the image istransferred, the camera shutsdown the IrTRANP, IrCOMM,IrLMP, and finally, the IrLAPsession.

NOW YOU KNOWAlthough the vision espoused by

the IrDA is simple, understanding thetechnical aspects can be somewhatdaunting. Now that you’ve been intro-duced to the concepts of IrDA, I hopethat you’ll f ind i t easier to im plementyour ow n IrDA solutions. I

SOURCES80C320

Dallas Semiconductor(972) 371-4448Fax: (972) 371-3715www.d a l se m i . c o m

HSDL7001 , ’1001 , ’1100Hew le t t -Packard(408) 435-4303Fax: (408) 435-4303w w w. h p . c o m

PLX7001Parallax Research Pte Ltd.

+ 65 791 7388Fax: + 65 793 0086w w w .parallax-research.com

NS87109 UIRNational Semiconductor(408) 721-5000Fax: (408) 739-9803www.n a t io n a l . c o m

V850/MS1NEC Electronics(408) 588-5008

Fax: (408) 588-5017www.n e c e l . c o m

Page 53: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 53/6866 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

22

Rolling Your OwnMicroprocessor

MICROSERIES

Monte Dalrymple

lPrick upyour earsas Monte

takes a detailed lookat the ports, timers,interrupts, andother features thatmake this newmicroprocessora hair (er, hare?)better than the Z80.

ast month , Icovered the design

and debug process forthe Rabbit-80 micro.

Now , I’d l ike to introduce you to thechip’s features. The Rabbit-80 is builtaround an enhanced Z80-compatible

C PU and contains a set of on-chipperipherals designed t o address t ypicalembedded-control applications.

Not e that no on-chip memory isincluded. The majority of applicationsserved by Z-World controllers requiremore f lash memory and RAM than wecould include on-chip at a reasonableprice, especially given th e low pricesof individual 256K × 8 flash memoryand 128K × 8 RAM devices.Let’s look at each of the

blocks of Figure 1.

THE CPUFor the most part , t he

CPU in the Rabbit is Z80-compatible. We madechanges to the instructionset to provide a greater

degree of support for t he C language.Several seldom-used instructions (seeTable 1a) w ere remov ed in favor of t henew instruct ions listed in Table 1b.

Many of the new inst ructions pro-vide 16-bit operations t hat w eren’treadily available in the Z80. Theseadditions provide a big performanceboost in the math libraries, especiallyw ith the new 16 × 16 signed multiply.The instruction requires just 12clocks to provide a full 32-bit result .

Operations such as the stack-rela-t ive load and store, and the abil i ty todirectly allocate or deallocate stackspace simplify parameter passing tothe stack. This feature is a must forC-language support.

The original Z80 architecture haddedicated I/O instructions tha t required

specific registers and addressing modes.Instead, the Rabbit u ses tw o prefixbyt es, w hich precede an instruct ionint ended to a ccess I/O.

The prefix bytes identify w hetherthe desired I/O loca tion is int ernal orexternal , and change the t iming andcontrol signals appropriately to provideaccess to t he peripheral. This setupgives greater flexibility w hen access-ing peripherals because the prefixescan be used with any instruction that

accesses memory.A sim ilar approach provides access

to the Z80 alternate register set. The prefix sw itches the destinat ion

register to the corresponding registerin the alt ernate register set, w hich cutsdown on the bank switching necessaryw hen using the alternat e registers.

The final additions support thelarge physical address space. Loads

D esign Applicat ion w ith th e Rabbit-80

Figure 1—This is what the Rabbit-80

looks like on the inside. Only external memories are required.

RTC

WDT

Clock control Port A

CPU

Port B

Port C

Port D

Port E

Serial port D

Serial port C

Serial port B

Serial port A

Oscillators Slave port

Timer BTimer A

Periodic int.

I/O Control

External bus and control

Internal bus

P a r t

of2

2

Page 54: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 54/68 CIRCUIT CELLAR ® Issue 111 October 1999 67www.circuitcellar.com

Instruction type Mnemonics

Conditional call CALL ccBCD operations DAA, RLD, RRDBlock I/O INI, OUTI, etc.Byte multiply MLTInterrupt control DI, EI, IM n , RETNI/O IN, OUT, TSTIO, etc.Test TST

Alternate register bank ALTD instruction prefixI/O instruction prefix IOIP, IOEP16-bit math AND, OR, RL, RR,

BOOL, MULStack-relative addressing LD (SP + n )Stack-space allocation ADD SP,dLong address program flow LCALL, LJP, LRETInterrupt priority stack IP n , IPRES, PUSH

IP, POP IP16-bit load and store LDLoad/store (physical address) LDP

and st ores use a direct 20-bit physicaladdress instead of th e usual 16-bitlogical address. The program flow -control (jump, call, and return) in-structions load one of the MM U bankregisters in addition to the PC to pro-vide program access to the full physi-cal address space.

MEMORY MANAGEMENTThe Z180 provides an MMU with

two bank registers to create thelarger (1 MB) physical address space.The Rabbit adds anot her bank regis-te r and the ab i l ity to bank-swi t ch themem ory chips for even m ore programand data space. The MMU addresst ransla t ion a lgor ithm is show n inFigure 2.

The MMU uses the upper four bits

of the logical address to select one ofthe ba nk registers to use for addresstranslation. The exact boundary w hereone bank ends and another begins iscontrolled by another register.

The exception is a n ew ly addedbank register, w hich is alw ays usedfor translation w hen the logical ad-dress is betw een E000h an d FFFFh.This new bank register is accessed bythe new program control instructions.

Translated addresses may be modi-

fied to separate instruction and dataareas in the memory chips. This arrange-ment only w orks for accesses using oneof the bank registers and allow s execu-tion out of RAM w hile accessing datain flash memory. Address bits 16 or19 (or both) can be inverted for dataaccess, so dat a can be accessed at eit her64 or 512 KB above or below th e code.

At this point, the address goes toth e chip-select decoder, w hich uses th eupper tw o bits of t he 20-bit a ddress to

generate t hree chip-select signals, tw ow rite-enable signals, and tw o output-enable signals. Each memory quadrantcan use any com bination of a singlechip select, an output enable, and aw rite enable. Figure 3 shows a t ypicalsystem configuration.

The chip-select signal typically usedfor RAM can be forced continuallyactive to circumvent the delay inherentin routing the signal through an exter-nal pow er controller for batt ery-backedapplications. Each m emory quadrantcan be individually w rite-protected.

The final address modificat ion allow sthe tw o most signif icant bits of theaddress to be flipped (individually foreach memory quadrant) after the chip-select decision is m ade. This arrange-ment a l lows a 1M × 8 memory ch ip tobe bank-sw itch ed w ithin a 256-KBquadrant of the physical memory space.

BUS TIMINGThe basic instruction time and bus-

cycle t ime are both tw o clock cycles.

Memory-w rite cycles have one w aitstate au tom atically a dded. The basicread cycle is show n in Figure 4a, andthe ba sic w rite cycle, in Figure 4b. Foreach of the four memory quadrants,there is a choice of zero, one, tw o, orfour au tomat ic w ai t s ta tes .

Separate strobes are provided forI/O t ransa ct ions an d up to eight I/Ochip-select signals can be output onPort E. The 64-KB ext ernal I/O a ddressspace is evenly divided for th e eight

I/O c hip select s. Each I/O region ca nbe programmed for 1, 3,7 , or 15 automat ic w aitstates and can be w rite-protected.

Int ernal I/O a ddressesare separate from externalI/O addresses. O f cou rse,most of the t ime a Rabbitsystem w on’t need exter-nal peripherals becausemost of the digital periph-erals an embedded systemmight need are on-chip.

SLAVE PORTOne unique feature of the

Rabbit is the slave port. Thisbyt e-w ide port is a bidirec-tional communications chan-nel betw een th e code on theRabbit and a master system.To the master, the Rabbitlooks like a combination of

th ree w rite registers, t hree read registers,and a status register. The Rabbit C PUhas the sam e view of t he slave port .

Figure 5 show s th e slave-port hard-w are interface. Since the chip select isdesigned int o t he slave-port interface, anumber of Rabbit slaves can be simul-taneously used in a system .

The mast er writ ing to t he slaveport can generate a Rabbit interrupt,and a Rabbit w rit ing to the slave portcan activat e the interrupt signal to the

master. This setup permits high-speedinterrupt-driven transfers.

A primary use of the slave port isto offload the intelligence required todrive peripheral devices onto the Rab-bit system. Thus a sm all Rabbit sys-tem w ould look like a group of “ smart”peripheral devices to a master system.

SERIAL PORTSThe Rabbit has four in dependent

serial ports: tw o are async-only, and tw o

are com binat ion a sync/clocked serial.

Table 1a—These Z80 and Z180 instruc- tions were removed to make room for new instructions. They can all still be emulated in software.b— These new Rabbit-80 instructions provide higher performance. The main additions are the 16-bit math operations and long address operations.

Figure 2—The MMU translates logical addresses to physical addresses. It also provides for instruction/data separation and bank switching.

16-bit logical address

Selected base register

Invert A19 and/or A16 only if data

Binary addition

Physical address for CS decision

Invert A19 and/or A18, by quad

Physical address output to pins

+

+

+

a)

b)

Page 55: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 55/68

Page 56: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 56/68 CIRCUIT CELLAR ® Issue 111 October 1999 69www.circuitcellar.com

individually programmable for datadirection. Each bit can be programmedto be open-drain as an output, and PortD has higher dr ive capabil i ty t han t heother ports for driving LEDs, optoiso-lators, solid-state relays, and more.

As outputs, the tw o nibbles of Port

D can be clocked independently byTim er A’s output or by either Tim er Boutput. Any data writ ten to the port’sdata register isn’t clocked to the pinunt il the selected signal is activ e, allow-ing precise timing of the Port D outputs.

Port E has capabilities similar toPort D ’s but lacks the high drive out-

puts or open-drain capability. Port Ecan be program m ed to provide th e I/Ochip selects and the ch ip-select inputfor the slave port. Four Port E pins canalso be used as CP U interrupt inputs.

INTERRUPTSThe Z80 interrupt mechanism has

been completely revised in the Rabbit.In the Rabbit interrupt scheme, thereare four interrupt priority levels.

The CPU’s current priority leveldetermines w hether or not an interruptis accepted, thereby allow ing only int er-rupt requests with higher priority tobe accepted. As well, th e CP U keeps astack of the four most recent prioritylevels, w hich allow s preemption.

Every int errupt source can be pro-gram med to request an int errupt at

one of th e four levels. Of course, aninterrupt requested at level 0 w ouldnever be accepted because it isn’thigher than anything. This is how individual interrupts are disabled.Similar ly, when the CPU is at level 3 ,no interrupts w ill be accepted, becausethere isn’t a higher priority.

A typical priority assignment mightbe to have the serial ports and timersrequest at level 1, external interruptsat level 2, and one external interruptat level 3 , simulat ing a nonmaskableinterrupt. Then the normal CPU prior-ity w ould be level 0, enabling all in-terrupts. Of course, if there are criticalsections of code that can’t be inter-rupted, then t hey should be run w hilethe priority is temporarily set to level 3.

All accepted interrupts cause anautomatic branch to a fixed location inm emory, as show n in Table 2. Int er-

Figure 5—The Rabbit looks like an I/O device when using the slave port. This feature allows the Rabbit to be used as a smart peripheral device.

SLAVE_AD[1:0]

SLAVE_D[7:0]

SLAVE_CSB

SLAVE_WRB

SLAVE_RDB

SLAVE_ATTNB

Rabbit-80

PORT_B[5:4]

PORT_A[7:0]

PORT_E[7]

PORT_B[3]

PORT_B[2]

PORT_B[7]

Figure 6—Timer B takes care of PWM tasks easily. The double buffering reduces time-critical overhead.

10-bit counter

Buffer register 1

Buffer register 2

Match register 2

Match register 1

Comparator Match 2Match 1

Page 57: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 57/6870 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

a bat tery-backed system can keep timewhen the main power fails. Both the32-kHz oscillator and the RTC areoptimiz ed for power consumption. Ifthe m ain pow er is absent, a 150-mAhbatt ery pow ers the RTC, so the Rabbit

can keep time for about a year.

CLOCKING AND POWER OPTIONSThe 32-kH z oscillat or is accom pa-

nied by a separate high-speed oscillatorfor the remainder of the chip, but anumber of clocking options are avail-able. After reset, everything starts outrunning in divide-by-8 mode from thehigh-speed oscillator, but you can alsoselect full speed or 2× full speed.

The 2× option saves some pow er in

the high-speed oscillator. The Rabbitcan be programmed to use the 32-kHzclock and the high-speed oscillator canbe turned off during inactive periods.Or, you can power down everything butthe RTC for the ultimat e pow er savings.

BOOTSTRAPA primary design goal wa s to allow

for remote bootstrap (i.e., to make itpossible to have RAM-only systemsusing the Rabbit). In this mode, the

CPU fetches instructions from a small(12 byte) internal ROM containing thecode in Listi ng 1. At each int ernal I/Oread instruction, the internal logic holdsthe CPU in a wai t s ta te un t i l a by te isavailable from the selected peripheral.

Tw o pins control bootstrapping byselecting normal operation, boot fromthe slave port, or boot from serial PortA in async or clocked serial mode. TheRabbit samples the pins after reset(w hen t he PC address is 0000 in th efour least significant bit s) to enablethe boot ROM.

Th ank s to everyone at Z -Worl d, espe- cial ly N orm Rogers for conceivi ng the Rabbi t-80, and Pedram A bolghasem for runni ng the project (and d oing m uch of the work) there.

M ont e J. D alry m ple has been design- in g IC s for m ore th an 20 years. He current ly has his own com pany, w hich develops in tell ectu al propert y. You may reach hi m at m onted@system yde.com.

rupts from internal peripherals use theR register to set the upper eight bits ofthe address of the service routine andthe external interrupts use the I regis-ter to set the upper eight bits of theaddress, which is similar to how theseregisters are used in t he Z 80.

The entry points are separated by16 bytes in memory. Some interruptscan be serviced in this amount of codeor enough housekeeping can be doneto share the bulk of a service routine.For exam ple, the four serial ports canuse identical code, as long as the portaddresses and da ta -ta ble pointers areset up in these 16 bytes before branch-ing to the common routine.

The Rabbit has one ot her interrupt—th e periodic interrupt, w hich occursat a rat e of 2.048 kHz. This interrupt

is useful for t im e-slicing or low -speedstatus monitoring and is generated fromthe 32-kHz oscillator, which also clocksthe w atchdog tim er and real-tim e clock.

WDT AND RTCThe w at chdog t im er (WDT) can be

programmed to time out after 250 ms,500 ms, 1 s, or 2 s. Its control registerrecognizes four specific bytes to set t henext t imeout period. Any ot her bytesw ritt en to this register are ignored, an d

if one of these four bytes isn’t writtenin t im e, the Rabbit is reset .

The RTC doesn ’t k eep hours/m in-ut es/seconds tim e; it’s a 48-bit count erclocked at 32 kHz. It can be set to aspecific count by softw are before itstarts counting up. If the software startscounting from zero, that’s 272 years oftimekeeping (yes, it’s Y2K compliant).

The Rabbit contains a completelyseparat e power plane for the RTC, so

SOURCERabbit-80Rabbit Semiconductors(530) 757-8400www.r a b b i tm ic r o . c o m

The bootstrap mode assumes datatransfers in groups of t hree bytes. Thefirst tw o bytes are the address for thedata , followed by the data it self. Thisarrangement al low s data to be loadedanywhere in memory.

To select betw een external m emoryand in ternal peripheral cont rol regis-ters, the Rabbit uses the most signifi-cant bit of t he down loaded address.Once the peripherals are accessible,the M MU can be programm ed, provid-ing full memory access.

To exit bootstrap mode, w rite to abit in an internal control register orchange the pins back to normal opera-tion. It’s easy to exit this mode, becausethe I/O locat ion th at disables it is

accessible during bootstrap.

ROLLING ALONGNow that you know how the Rabbit

was designed and what it contains, whatcan you do w ith i t ? Anything a Z 80 orZ180 can do, and more. Plus all thedevelopment soft w are is available. I

Listing 1— Just 12 bytes are needed for the bootstrap loader. The hardware automatically modifies the bytes to select the bootstrap source and to select an internal I/O destination.

ISR startingInterrupt source address

Periodic interrupt R, 00000000Slave port R, 10000000Timer A R, 10100000Timer B R, 10110000Serial port A R, 11000000Serial port B R, 11010000Serial port C R, 11100000Serial port D R, 11110000External interrupt 0 I, 00000000External interrupt 1 I, 00010000

Table 2—Interrupt routines start on 16-byte boundaries,

which provides space for some housekeeping before jumping into the main service routines.

Page 58: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 58/6872 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

FROM THEBENCH

Jeff Bachiochi

GetSmartMedia

Yourlatestassign-ment:Follow

Jeff as he goesundercover (underthe embedded-device cover, that is)to investigate how toaccess the Smart-Media nonvolatileflash memory.

ast month , Iwent over the

physical makeup ofthe SmartM edia f lash-

memory device. I’d like to start outthis article by introducing some cir-cuitry I designed that enables you toaccess the SmartMedia.

As you can see from Figure 1, there’snot m uch to t he interface. A microcon-

troller handles both the SmartMediainterfacing as well as a serial comm u-nications channel.

One of the important points of thiscircuit is t hat i t can run at ei ther 3.3or 5 V. The SmartMedia device in-serted into the SmartMedia socket indi-cates the necessary voltage throughthe out put pin 17. (If you m issed lastmonth’s column, now might be a goodtime to go back and read it because I’mgoing to assume t hat you’re familiarw ith t he signals of the SmartMedia.)

SmartMedia products cover such alarge range, you must be able to sensethe type and size of the device insertedinto y our equipment. If you don’t recog-nize the SmartMedia, you should makeaccommodations to reject or at leastnot corrupt t he data held in t he device.

Therefore, it ’s recomm ended tha tyou follow certain steps to determinew hether the device is compatible w ithyour equipment: t he detection of inser-tion, operating voltage, type and size,physical format, and logical format.

INSERT HERE Ma ny SmartM edia sockets have an

internal microsw itch w hich enablesyou to determine if a device has beeninserted into the socket by the physi-cal operation of the sw itch’s contacts.This mechanical insertion verificationcan also be achieved through the Smart-Media contacts.

The interface has a pull-up resistortied to pin 11 of the SmartMediasocket. When t he device is not fullyinserted into the socket, the pullupregisters a logic high w ith t he inter-face. When fully inserted, pin 11, w hichis physically connected to t he V SS (pins1 and 10) contacts of the SmartMediadevice, grounds the pullup and registersas a logic low to t he interface.

PARAMETER DETERMINATIONOnce insertion has been resolved,

the proper operation voltage must bedetermined because, certainly, apply-ing 5 V to a 3.3-V device is just askingfor trouble. Again, mechanical micro-sw itches can be used to determineoperating voltage (at the same time asinsertion).

Besides the fact that the operatingvoltage is w rit ten on the SmartMedia,the packaging has eit her a left -clipped

corner, indicating 5-V operation, or aright-clipped corner, indicating 3.3-Voperation. So, tw o swit ches strat egicallyplaced at eit her corner of the socketcould be used to mechanically iden-tify the proper operating volt age. TheSmartM edia’s clipped corner would n otengage one of the tw o sw itches, thusindicating which m edia w as inserted.

Determining the proper voltage canbe done electrically as well, via pin18. This tim e a pulldow n is used. On5-V devices, pin 18 floats (internallyuncon nect ed), w hereas on a 3.3-V device,pin 18 is connected to V C C.

So, once inserted, a 5-V SmartMediadevice will not affect the logic low read by the interface, indicating theneed for a 5-V supply. On the otherhan d, a 3.3-V device w it h pin 18 con-nected to V C C raises the interface to alogic high, w hich indicat es the needfor a 3.3-V supply.

Personally, I think a pullup makesmore sense here. This w ay, t he inter-face w ould see th e need for a 3.3-V

l

Part 2: Hands On

Page 59: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 59/68CIRCUIT CELLAR ® Issue 111 October 1999 73www.circuitcellar.com

ing PC MC IA memory cards. When aSmartMedia card is inserted into aPC MC IA ATA adapter card, the PC M-CIA slot looks for this information asif i t were a PCMCIA memory card.Voilà! Instant device recognition basedon a previously designed standard.

The 16-byte redundant area holdsinformat ion pert inent to t he validityof the previous 512 bytes of the page(see Figure 2). This area is brok en dow n

into seven pieces of information. Thefirst 4 bytes are reserved for extensioninformation.

The next byte is the page data valid-i ty m arker. If the data w rit ten is notcorrect, a 0 indicates that the usershould not consider this page to begood and should proceed t o t he nextpage for CIS/IDI i nformat ion.

The next byt e is fixed at FF, w hichis normally the bad block marker. Thenext t w o bytes are fixed at 00 and 00(the physical block num ber). Follow-ing those two bytes are three bytes oferror correction code (ECC) data.

The ECC ’s 22 bits are calculat ed fromthe first 256 bytes of t he page. Finally,the physical block number, in this case

a fixed 0000, is repeated follow edby an ECC on th e second 256 bytesof th e page.

So, not only is t he C IS/IDI dat arepeated tw ice w ithin t his page,but separate ECCs are calculatedand saved in the page’s redundantarea. The ECC values enable a

In addit ion to test ing and ma rkingbad blocks, the manufacturer does someadditional housekeeping to comply withthe physical format specifications. Thefirst physical page (or first good physi-cal page) must have card informationstru ctu re and/or identify drive infor-ma tion (C IS/IDI) data w ritten t o it.

You should note that, although earlySmart Media devices used a 256-byt epage (w it h an 8-byt e redunda nt a rea),

the larger devices made today use a512-byt e page (w it h a 16-byt e redun-dant area). For the remainder of t hisdiscussion, however, I’ll only talkabo ut t he 528-by t e (512 + 16) page.

The CIS field is the first 128 bytes.It identifies the device and determinesif the device has been physically for-matted. The IDI field is the second128-byt e data area, w hich can be usedby the ATA-interface-equipped hostsystem.

As a precautionary measure, theC IS/IDI dat a is repeated in t he secondhalf of the page (see Figure 2). TheC IS/IDI format is defined by P C MC IA.

The PC MC IA slots on m ost laptopsinterface to many peripherals, includ-

supply w hen no device is insertedand i t w ould prevent the interfacefrom thinking it should supply 5 V,w hich w ould be a bad thing duringa 3.3-V device insertion. Anyw ay,using pin 18 enables the device tobe probed at the lower voltage andraised only if necessary (and safe).

SHOW SOME IDAt t his point, th e proper opera-

tional-voltage parameter can be set,the media type and size identified,and we can begin to communicatew ith t he SmartMedia device. A

command regurgitates botha m aker ID a nd device code. Themanufacturer ’s ID may be 98H(Toshiba ), EC H (Sam sung), or a not hercode registered with the SSFDC.

You’d think that w ith so few original players creating t he sta ndard,device type and size codes w ould bestandardized throughout m anufactur-ers. Although this is true for manycodes, some device types and sizes havedifferent codes from each manufac-turer for the same part description.

The device code indicat es parameterslike device size, operating voltage, andmem ory type. If you find ID and devicecodes that you don’t recognize, it only

ma kes sense to reject t he device. Afurther operation on an unknow n deviceruns the risk of dam aging the data heldw ithin the device.

PHYSICALLY FITSmartMedia manufacturers pretest

every page of flash memory for stuck(bad) bits. If a bad bit is detected inany page w ithin t he block, every pagein that block is marked as bad.

Remember that this indicator byteis f lash m emory and w hen the blockis erased, so is the bad block byt e. So,w hen erasing a block, the user mustremark it as bad either from a user-compiled list of ba d blocks or by re-testing the block for stuck bits.

Size 1 MB 2 MB 4 MB 8 MB 16 MB 32 MB 64 MB 128 MBCylinders 125 125 250 250 500 500 500 500Heads/Track 4 4 4 4 4 8 8 16Sectors/Head 4 8 8 16 16 16 32 32Total sectors 2000 4000 8000 16,000 32,000 64,000 128,000 256,000Sector size 512 512 512 512 512 512 512 512

Table 1— CHS parameters are predefined for present and future SmartMedia devices.

Figure 1— A PIC processor can be used to create a simple interface to a SmartMedia device socket. A 5-/3.3-V supply inot shown. However, the PIC can operate at either voltage. The VCNT1 connection is used to control the appropriate operating voltage, depending on the device inserted into the SmartMedia socket.

Page 60: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 60/68CIRCUIT CELLAR ® Issue 111 October 1999 75www.circuitcellar.com

HOW ECC WORKSThe ECC is a string of odd

parity bits representing therows and columns of the256-byte data field. For the8-bit (2 3) row parity, six bits(2 × 3) of ECC dat a are required.For the 256-byte (2 8) columnparit y, 16 bits (2 × 8) of ECCdata are required.

Each ECC row bit holds oddparity data for four differentcolumn bits of all 256 bytes.Each ECC column bit holds oddparity data for eight differentrow byt es of al l eight bits.

The ECC data is writ teninto the page’s redundant areaalong with the page data.When t he page is read from t he

device, the EC C data can becompared to newly calculatedECC data. A good comparewill ensure good data integrity.

What happens when a badbit occurs somew here? If thebad bit is in the data area, everyECC data b i t tha t uses thebad bit in i ts calculation willbe affected and will show upin one of each pair of ECCbits. From this pattern you

can determine w hich data bitis at fault and correct i t .

I f two dat a bits are bad, theECC data w ill ref lect an error

in both bits of an ECC pair. This pro-cess identifies an error, but the bitsinvolved cannot be pinpointed and sothe errors can’t be fixed.

If a bit in the ECC data is bad,i t show s up as a single EC C biterror. This kind of error cannot becaused by any combination of baddata-area bits. So, it can be ignoredand filed in t he proverbial bitbucket.

The 22 bits of ECC data is inthe following format: most signifi-cant byt e of the 16 line-paritybits, follow ed by the least signifi-

single bit error in the 256-byte pagearea to be repaired. Mult iple bit errorscan be identified but not repaired.

Note here that, except for the CIS/IDI block, the physical block numberstored in the redundant area of eachpage is in the range 0–999 (actually 2 ×(0–999) + 1000h + even parit y).

The blocks are kept in groups (orzones) of 1024. Although larger de-vices may require the use of severalzones, smaller devices may call for apartial zone.

Within a zone, not all availableblocks are designated for use. On adevice w ith 1024 physical blocks,only 1000 logical blocks are used. Theremaining blocks are spares (or in thecase of blocks with bad bits, unusable).But, as y ou w ill see, the good spareblocks do get rotated into use withinthe zone.

cant byte of the line parity, and finallythe six column-parity bits shifted lefttwice with the least signif icant bitsfilled with 1s.

Calculating the ECC data can bedone ahead of tim e wh ere the parityequivalent of each da ta value (0–255)fills up a look-up table, or it can becalculated on a byte-by-byte basis.Figure 3 shows which bits of eachbyte value are XOR’d to create theline parity (LP) and colum n parity(CP) data.

ECC calculations can be handledby ha rdw are or softw are. The programlisted in the Softw are section is aBASIC program that calculates the22-bit EC C for a half page of data(256 bytes).

This program runs on a PC under

QBASIC and w ill respond w ith t heLPHigh, LPLow , and CP bytes for thearray D (1)–D(256). You can plug va luesinto the array to see how changes inthe array affect the parity generated.

THAT’S LOGICALTo make using SmartMedia simpler,

there must be even more complexity.Huh? Yeah, that’s right—just like most“ user fr iendly” devices, i t of ten takesmany layers of complexity to simplify

its use.Although w e could stop here and

use the SmartM edia in an application,the data in the flash-memory devicew ould be unreadable elsewhere (un-less you w rote drivers for every pieceof equipment that needed to access the

Figure 2— With a serial terminal, the SmartMedia interface can be used to investigate SmartMedia devices. Here’s the boot record of a device.

Figure 3—Line parity and column parity data bits can indicate and correct for single bit errors. This figure shows how each half page of data is used

to create the 22 bits of ECC (error correction code) data.

0 0 0 0 0 0 0 1

1 1 1 1 1 1 1 1

0 0 0 1 1 0 0 0

0 0 0 0 0 0 0 1

0 0 0 0 0 0 1 1

1 1 0 1 1 0 0 1

Bit7

Bit6

Bit5

Bit4

Bit3

Bit2

Bit1

Bit0

Byte 1

Byte 2

Byte 3Byte 4

Byte 5

Byte 6

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

Byte 252

Byte 253

Byte 254

Byte 255

Byte 256

LP0LP1

LP14LP15

CP0 CP1

CP2 CP3

CP4 CP5

Page 61: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 61/6876 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

data). Formatting the physical formatwith a DOS fi le logical format makesSmartMedia compatible with otherequipment that’s set up to process theDOS file format. We use floppies, harddrives, and CDs everyday—all of whichuse the DOS FAT file structure.

Three items are necessary for t heproper format. First, there must be adefinition of CHS parameters. Take alook at Table 1 to see how the cylin -ders, heads, and sectors are definedbased on the media’s size.

The CHS parameters are based onthe logical blocks set up in the physi-cal formatting. With a sector size of512 bytes (a page), and 32 sectors perhead (a block), calculations are easy.

The first logical block consists ofsectors 0–1Fh of cylinder 0, head 0.

The second logical block consist s ofsectors 20h–3Fh of cylinder 0 head 1,and so on.

Second, the media must have amaster boot sector located on the firstgood sector of t he device. If you re-member back to t he physical format ,th e C IS/ID I also resides th ere. Thereis no conflict because the first parti-t ion info star ts at offset 1BEh wit h th eboot ID 80h. Table 2 lists t he rest ofthe partition parameters.

Offset 1C6h–1C 9h indicates wh erethe partition boot sector islocated (in t his case, logicalsecto r 37h). G iven one pageper sector, the P BS is oncylinder 0, head 1, andsecto r 17h.

The final piece is thepartition boot sector. Again,there are a num ber of pa-rameters here, as well asthe FAT and t he directory.Table 3 gives you all thepertinent informat ion.

The FAT follow s th eparti t ion boot sector, w hichindicates how many sectorsare required for the FAT andthat there are tw o copies(redundancy = security). So,the offset to the second FATand to the first directoryentry can be calculated.

A directory entry is32 bytes long and containsthe file nam e, extension,

and attr ibute, along withthe last edit tim e/date,the starting cluster ofthe file, and its length.Instead of speaking interms of sectors, theterm “ cluster” is used. Acluster is defined in thepartition boot sector andis the minim um number of sectorsthat can be allocated to a f i le .

From the starting cluster number,the starting logical sector of the file’sdata can be determined. If the file’slength exceeds the clust er size, addi-tional clusters can be allocated throughthe FAT.

SECTOR MANIPULATIONRemember when I m entioned how

not a ll of the physical blocks w ere givenlogical addresses, and that some extrablocks w ere left una llocat ed? Well, the

first t ime the block is writ ten with

data, t he data m erely gets programm edinto the erased logical blocks.

When a block needs to be changed,the block m ust be read from the device(including t he redundant area), t hepertinent data changed, and the blockw rit ten back to any unu sed block inthe same zone. The redundant area isalso written, identifying it as the samelogical block that w as just read. Now,the original block is erased, removingit from service. If you are keeping a t ableof w hich physical block is w hich logi-cal block, you must correct the table.

I’ve purposely not mentioned thislogical-to-physical ta bleunti l now because i t re-quires 1000 entries and notall equipment has enoughRAM to keep a table ofthis size. It speeds thingsup, though, since you don’thave to search the w holedevice, physical sector byphysical sector, looking forthe logical sector you re-quire. As long as you buildthe table and keep it cur-rent, you won’t have tocontinually search t hedevice.

PROBING SMARTMEDIAThe PIC I used in this

project (’16C63) has lessthan 256 bytes of RAM, sothere’s no way I can attemptto keep track of physicaland logical mapping. Norcan I buffer 528 bytes of

DataOffset Parameter (64-MB device)

000h–1BDh Boot command (not used) 00h–00hPartition 11BEh Boot ID 80h1BFh Start head 01h1C0h Start sector 18h1C1h Start cylinder 00h

1C2h System ID 01h1C3h End head 07h1C4h End sector 60h1C5h End cylinder F3h1C6h–1C9h Start logical sector 00 00 00 37h1CAh–1CDh Partition size 00 01 F3 C9h1CEh–1DDh Partition 2 (not used) 00h–00h1DEh–1Edh Partition 3 (not used) 00h–00h1EEh–1FDh Partition 4 (not used) 00h–00h1FEh–1FFh Signature AA 55h

Table 2— Once the device is formatted, the boot sector provides information about the device,including where to find the first partition.

DataOffset Parameter (64-MB device)

000h–002h Jump command E9 00 00h000h–00Ah Manufacturer’s name

and version (ASCII, 8 bytes)00Bh–00Ch Bytes/sector 02 00h00Dh Sectors/cluster 20h00Eh–00Fh Reserved sectors 00 01h010h Duplicate FATs 02h011h–012h Root directories 01 00h013h–014h Total partition sectors 00 00h015h ID byte F8h016h–017h FAT sectors 00 0Ch018h–019h Sectors/track 00 20h01Ah–01Bh Heads 00 08h01Ch–01Fh Hidden sectors 00 00 00 37h020h–023h Total par tition sectors (32 bit) 00 01 F3 C9h024h Physical drive 00h025h Reserved 00h026h Extended boot record signatures 00h027h–02Ah Volume ID (4 bytes) 00 00 00 00h02Bh–035h Volume label (ASCII, 11 bytes) 00h–00h036h–03Dh File system type (ASCII, 8 bytes) FAT1203Eh–1FDh Reserved (IPL code area) 00h–00h1FEh–1FFh Signature AA 55h

Table 3— The partition boot sector has more information, including the location of the directory and FAT.

Page 62: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 62/68CIRCUIT CELLAR ® Issue 111 October 1999 77www.circuitcellar.com

data for a single page and it s redun-dant a rea.

What I can do is enable the user touse the basic operations ava ilable wit hSmartMedia by dumping data read fromthe device to a serial port. By using a

COMM program like PROCOMM (oreven HyperTerminal) the user canfully investigate SmartM edia.

But, y ou’ll be required to preparepage data m anually, including theredundant area (ECC calculation,block address, etc.). Figure 3 illus-trates a dump of the directory area of

Figure 3—After I took a single picture with my digital camera, the directory holds a single entry. The file name is .

one of my digital camera’sSmartMedia cards.

U sing a SmartM edia cardtakes some w ork to be able tofully handle all the necessaryformat ting. But, only a few routines are necessary if all youw ish to do is save some data.You can get aw ay w ith a mini-mum amount o f RAM, bu tthere is a tradeoff of speed ifyou need to do any searching.

The only other problem Isee is if you are collecting

data and a page (sector) you have justw rit ten comes up with an error. Cor-recting t he dat a (reading, correcting,and rewrit ing) is impossible w ithou tenough RAM to hold the page. In thiscase, you might just keep going. If it’s

only a one-bit error, it can be cor-rected using the ECC w hen the data isread back out of the device.

If you’re designing equipment witha removable storage media require-ment, consider using SmartMedia. Itsphysical size versus storage capacityis quite remarkable. I

Jeff Bachiochi (pronounced“ BA H -key- A H -key”) i s an electri cal engin eer on Circuit Cellar ’s engin eeri ng staff . H i s

back ground in clu des product d esign and m anufactu rin g. H e m ay be reached at jeff.bachi ochi@circu it cell ar.com .

Thank s to D oug Wong, Toshib a, for hi s Sm artM edia experti se and docum enta- t i on, and t o Jeff Schm oyer, mi croEngi- neerin g Labs, for th e PIC BA SIC Pro.

SOURCESSmartMedia

Toshiba(408) 737-9844Fax: (408) 737-9905www. to sh ib a . c o m

Samsung Semiconductor, Inc.(408) 544-4000Fax: (408) 544-4907www.usa .samsungsemi .com

SOFTWAREThe BASIC program u sed to calcu -late the 22-bit ECC is available viathe Circu i t C el l a r web si te .

Page 63: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 63/6878 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

w hen i t comes togetting embedded

gadgets onto the I-w ay, designers have

quite a few options to choose from,w ith m ore emerging all the tim e. Thechallenge is picking one that bestmatches your apps requirements.

If circumstances allow , w hy notrely on a standard off-the-shelf PC as

your ’Net gatew ay? Thanks to themarch of silicon (and some might say,the deat h-w ish pricing tendencies ofPC suppliers), you can get a perfectlyadequat e PC for w ell under $1000.

And besides, even the ch eapest P Chas plenty of horsepow er, comes w ith

the softw are to accomplish ’Net trans-actions, and h as an unparalleled quiverof development tools.

More pow er to you if t he PC ap-proach w orks for you, but desktop PC scarry a lot of baggage. They’re big,consume a bunch of pow er (considergoing w ith a la ptop), take a long tim eto boot, and n either the hardw are norsoftware is especially robust.

Embedded PC s, whether Com pact-PC I, PC /104, or a st and-alone SBC ,can easily address the packaging andpower concerns raised by t heir desk-top brethren. Another option is to useLinux instead of Window s, exactly t hetack t aken by Stanford University’sWearable Computing Lab.

They built a tin y, Linux-based webserver using a miniscule EPC [1]. Re-

fer to t he lab’s w eb page or back toIngo’s articles on embedding Linux(Circu i t Cel l a r 100–104) if you’reinterested in this approach.

Note that I didn’t include price inthe list of concerns. The fact is, EPCscost h undreds of dollars (th e EMJ boardused at Stanford lists for over $400)and at best a re just competit ive w ithdesktop pricing. It would be easy tospend more putting together an EPCthan buying a clone off the shelf.

A more streamlined solution thatoffers PC-class performance withoutextra baggage is a 32-bit CPU (’ x 86 orRISC) running an RTOS or WindowsC E, fully loaded w ith protocol stacks,Java, and all the rest. You still need ahefty am ount of si l icon, and cobbling

’Net-in-a-Chip

There areplenty ofoptionswhen itcomes to

the hardware andsoftware for gettingan embedded gadgeton the Internet. Thismonth, Tom considersusing the S-7600A asan entrance ramp tothe I-way.

SILICONUPDATE

Tom Cantrell

T06T05T04T03T02

T16

VDD

T15

T14

T01

T07

T17

R S

C S

C 8 6

R E A D X

V S S

N T 1

W R I T E X

N T 2 X

B U S Y X

P S X

T I 3

N T C T R L

R T S X

D T R X

D C D

R X D R

I

C L K

C T S X

T E S T

R E S E T X

D S R X

T X D

V S S

SD1SD2SD3SD4SD5

TI2

TI1

NC

SD7

VDD

SD0

SD6

12

253637

48

24

131

Figure 1— The Seiko ’7600A is a standard chip based on iReady i1000 protocol processing hardware that handles all the details of TCP, UDP, IP, and PPP.

PPP

IP

UDP TCP

Serial port S e r i a l p o r t

CPUinterface

SRAM interface

T o

C P U

SRAM (10 KB)

Network stack

Page 64: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 64/68 CIRCUIT CELLAR ® Issue 111 October 1999 79www.circuitcellar.com

together all the pieces isn’t trivial, butpackaging, pow er consumpt ion, andprice challenges are easier to over-come w ithou t th e Wintel baggage.

One of the best of this breed is theNET+ARM from NETsilicon. It com-bines a high-integration ARM CPUw ith netw orking hardwa re (Ethernet,UART, etc.) under the supervision ofan RTOS that includes all the requi-si te netw orking softw are. N ET+ ARMpricing ranges from $10 to $40 depend-ing on version and volume, and in-cludes a glueless interface t o (EP)ROM ,SRAM, DRAM, SDRAM, and so on,making for a quick and easy minim alchip count design.

As an interesting aside, N ETsilicontipped me off to the formation of theIndustrial Automation Open Network-

ing Alliance by several embedded Inter-net players, including big guns likeG E Fanuc, Siemens, C utler-Ha mm er,Andover Controls, and Sun [2].

It’ll be interesting to see how theIEEE 1451 standard ( Circui t Cel lar 103)and its prime proponent HP fit in.There’s alw ays been an in terest inbridging th e gap betw een office andfactory automation. Now, the ’Netprovides a w ay.

’NET UARTWhichever w ay y ou cut i t , embed-ded ’Net solutions ca ll for a 32-bitCP U and a fa ir amount o f memory.C utt ing more fat can get int eresting.

Consider Myron Lowen’s approachin “ Internet Appliance Interface”(Circu i t Cellar 108). He got on the

’Net w i th l i t t le more than a PIC and2400-bps modem by short-circuiting abunch of protocol bloatware. Risky?Indeed, in terms of ISP and tool com-patibility. Intriguing? Very!

Back in May (“ Betting On Web-wa r e, ” Circu i t C el l a r 106), I describeda nontraditional solution offered byiReady. The i1000 protocol engineoffloads a host C PU by handling allth e detail s of TC P/IP, H TTP, SM TP,POP, and so on. Because it works withany C PU , the i1000 is a potential lyeasy and inexpensive way to add net-w ork capability to existing designs.

I say “ potential ly” because, as Ilamented then, the i1000 isn’t actu-ally offered as a chip but as a bunch ofIP (i.e., Verilog) from w hich you a resupposed to build an ASIC —a fire drill

that’s neither cheap nor easy. What’sneeded is an off-the-shelf IC to sup-port innovative and specialized apps.

Now, iReady has made a deal withSeiko to create just such a device, theS-7600A, also know n as t he iC hip (seeFigure 1). Packed in a tiny 48-pin QFPand under $10 in volume, the ’7600Ais a networking solution that won’tbog dow n efficient em bedded designs.

On one side is a generic processorinterface. On the other is a conventional

RS-232 port. In betw een is the net w ork-ing know -how and silicon (protocolengine and SRAM) to ha ndle tw o sock-ets worth of IP, TCP, UDP, and PPP.

BOUNTIFUL BUSConnecting with your favorite

controller is easy, thanks to a versa-

tile interface. At RESETX, the ’7600Achecks the state of PSX and C86 todetermine w hether to use a serial or

parallel host interface and, if the lat-ter, w hether Intel or Mot orola flavor.The Intel convention features separateread and w rite strobes, but M otorolauses a read/w rite stat us line and adata strobe. The appropriate funct ionsare ma pped to READ X and WRITEX.

SD7–SD0 make up the parallel databus. In serial mode, SD7–SD5 becomethe serial data in, clock, and out , respec-tively. C hip select (C S) enables accessw hen asserted and tr istat ing outputs

w hen deasserted so t he ’7600A canshare the bus w ith other peripheral ICs.

The ’7600A uses the BUSYX outputto handshake w ith t he host . The ac-tive-high and activ e-low int erruptrequest outputs (INT1 and INT2X) areconfigured as totem-pole or open-drain by setting INTCTRL high or low .

Inside the ’7600A,you’ll find dozens ofregisters that controlvarious aspects of thechip’s operation, as yousee in Table 1. Therearen’t enough a ddresslines for direct access,so getting at a specificregister is a multistepprocess (see Figure 2).

First , t he host w ritesth e desired address w iththe register select (RS)pin low . Then, it issuesa read or w rite comm andwith RS high to init iatethe register access. The

Figure 2— Whether you’re using the parallel or serial (shown here) interface mode, reading data from the ’7600A is a three-step process—write the desired register address, start the read operation and, after BUSYX returns high, read the data.

A6 A5 A2A3A4 A0A1A7

A6 A5 A2A3A4 A0A1A7 D6 D5 D2D3D4 D0D1D7

CS

RS

RWX

SCL

SI

BUSYX

SO

tWRB

tEB

tAHtAStSL

tSHtRWE

tERW

tDE

text

tEB

Photo 1— Exploiting the ’7600A, Mike Johnson fields a worthy contender for “world’s smallest web server” bragging rights.

Page 65: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 65/6880 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

Once connected (i.e., tw o socketsta lkin g via TCP /IP), th e ’7600A han -dles all th e details (e.g., flow control,and error recovery) and it’s easy totransfer data, either polling or underinterrupt control at your discretion.

All buffering is handled on-chipwith 10 KB of SRAM. Each socket hasa 1-KB send buffer and 2-KB receivebuffer. The remaining 4 KB is allo-cated to protocol-specific (e.g., TCP,IP, PPP) buffers and data structures.

LAYER IT ON MEAs I explained in May, a fully loaded

i1000 could in corporat e hardw are sup-port for higher layer protocols such as

ets the ’7600A supports. The value (0or 1) set in the Index register (0x20)defines whi ch is accessible.

In Internet-speak, a socket is a full-duplex port uniquely identified by theconcatenation of IP address and asocket num ber. A pair of sockets de-fine a connection (also unique), thougha single socket can simultaneouslyparticipate in multiple connections.

Per TCP, at this point you’d need abunch of softw are to open a socketand establish a connection as show n inFigure 3. Instead, the ’7600A handlesall the grunt w ork. All you have to dois set an a ctivate socket bit a nd w aitfor a connection established bit.

0x00

0x01

0x02

0x04

0x08

0x090x0A0x0B0x0C–0x0D0x10–0x130x1C0x1D0x20

0x210x22

0x230x240x260x280x2A

0x2B

0x2C

0x2D0x2E0x300x30–0x310x32–0x330x34–0x350x36–0x370x38–0x390x3A0x3C–0x3F0x60

0x610x620x640x6F

Revision Major revision number Minor revision number

General_Control

General_Socket_LocationMaster_Interrupt

Serial_Port_Config

Serial_Port_IntSerial_Port_Int_MaskSerial_Port_Data Serial port data register

Baud rate divider registersBAUD_Rate_DivOur_IP_Address Our IP address

Clock_Div_LowClock_Div_HighIndex

TOS*Socket_Config_ Status_Low*

Socket_Status_Mid*Socket_ActivateSocket_InterruptSocket_Data_AvailableSocket_Interrupt_ Mask_Low*

Socket_Interrupt_ Mask_High*

Socket_Interrupt_Low*

Socket_Interrupt_High*Socket_Data*TCP_Data_Send (WO)*Buffer_Out (RO)*

Buffer_In (RO)*Urgent_Data_Pointer*Their_Port*Our_Port*

Socket_Status_High*Their_IP_Address*

PPP_Control_Status

PPP_Interrupt_CodePPP_Max_Retry

PAP_StringPPP Test Control

– – – – – –

– – – – –

– – – – –

– – – – –

– –

SW_ RST

0 0 0 0 0 0 1 1

PT_ INT

LINK_ IN_T

SOCK_ INT

S_DAV /

Loop backmode

Parallelmode

DCD / DSR/ HWFC CTS RI DTR RTS SCTL

PINT DSINTPINT_EN DSINT_EN

Low byte for 1-kHz clock dividerHigh byte for 1-kHz clock dividerSocket index

Type of service fieldProtocol_TypeData_

Avail/RST

Data_ Avail_En

Buff_ Full

Buff_Full

Buff_ Empty

Buff_ Emp_En

TO

Data_ Avail

Buff_ Full

Buff_ EmptyTO

URG RST Term

Term_En

ConU

URG RST Term ConU

ConU_En

TCP State – – – – –

– – – – – – – – – –

– –

– –

– – – –

– –

– – – –

– – – –

– – – –

– – – –

– – – S1 S0I1 I0

DAV1 DAV0

TO_ EN

URG_ En

RST_ En

Socket 8-bit dataAny write causes data to be sentBuffer out lengthBuffer in lengthUrgent data offset pointer, UDP datagram sizeTarget port addressOur port address

Snd_BsyTarget IP address

PPP_Int PPP_ Int_En

Con_ Val

Use_ PAP

TO_ Dis Kick PPP_

EnPPP_ Up / SR

Interrupt codePPP maximum retry

Pap user name and passwordTes t Bypass Loop

Back

Register Bit definitionsAdd

Table 1— The host controls the ’7600A operation and transfers data through various registers. A number of the registers in the range 0x21–0x3F (marked with an asterisk) are duplicated for each socket and selected with the Index register (0x20).

’7600A asserts BU SYX w hile it per-forms the data transfer. For a read, thehost retr ieves the data w ith a thirdaccess after BU SYX is deasserted.

The netw ork connection is a simpleU ART. There’s a 16-byt e receive FIFO,option al RTS/C TS handsha king, andindividual interrupt-enable bits forreceive and transmit ready. Format isfixed at 8N1, and the data rate is de-rived as a programmable divide ratioof the chip clock.

Speaking of the clock (CLK), it canbe quite leisurely because the ’7600Aimplem ents protocol processing wit hhardw are stat e machines. The mini-mum clock rate depends on the datarate demands of the physical channel,but it’s only on t he order 1 Hz per bpsof physical chann el bandw idth, so a

mere 100 kHz could handle any mo-dem. The low -speed clock and opti-mized hardware also make for low pow er consum ption (i.e., milliam ps inoperation and microamps in standby).

PROTOCOL POWERIn Figure 2, after RESET, the host

initia lizes th e ’7600A and does house-keeping via registers 0–1D . For ex-ample, it sets the serial port data ratedivider (and a similar divider respon-

sible for generating a 1-kHz timebase),enables interrupts, and so on.

Here, your software controls theserial port and is responsible for estab-lishing communication. The likelyscenario is to issue the commandto a connected modem and dial anISP. Here’s where it gets int eresting.

After the modems establish com-municat ion, your softw are f lips theserial control (SCTL) bit in the con-figuration register (0x08) and theonch ip P PP logic (registers 0x60–0x6F)takes control of the serial port andstar ts yacking wit h the ISP’s softw are.The ’7600A handles the back-and-forth of options, passwords, and suchthat otherwise call for a lot of code.

Once PPP does i ts t hing, includingassigning Our_IP_Address (i.e., negoti-ated or floating assignment) if youdidn’t set it explicitly, you’re on the’Net and action shifts to registers0x20–0x3F, w hich front th e TC P/IPservice. Note that this set of registersis duplicated for each of th e tw o sock-

Page 66: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 66/6882 Issue 111 October 1999 CIRCUIT CELLAR ® www.circuitcellar.com

e-m ail (i.e., SMTP an d PO P3), w eb(i.e., HTTP and HTML), and file (FTP).But, the ’7600A incorporates none ofthese protocols. Is this a problem?

Not really. Remember, the i1000isn’t an act ual chip but rather a col-lection of know -how to enable you todesign you r ow n ASIC. Thus, eachi1000-based chip should only includethe functions required by an applica-

tion (e.g., a chip designed to handle e-ma il doesn’t need w eb support).

By contrast, the ’7600A (like allstandard chips) has to strike a com-promise. It needs enough features tomeet the requirements of a broadrange of applications; add too manyextras, and customers will object topaying for features they don’t need.The ’7600A designers sa y TC P/IP andPPP are the sw eet spot.

First, of t he alphabet soup of proto-cols that a bound, TC P/IP and PP P areamong th e most complex. A quickway to i l lustrate the si tuation is tocheck the file sizes of the variousRFCs (Request for Comments; i.e., theseminal I-way specs from the DARPAdays). TCP/IP and PP P com prise about300 KB (that’s just the main RFCs, notall the embellishments and add-ons)com pared t o 150 KB for FTP, 120 KBfor SMTP, and a mere 35 KB for POP3.

Furtherm ore, TC P/IP an d PP P arethe comm on denominat or for al l theother protocols. By contrast, higher

level functions such as e-ma il, w eb, and file are de-signed to functionindependently . If you justneed FTP, there’s no need tobother w ith H TTP, SMTP,POP3, and so on. Whicheverprotocol(s) you choose, you’llneed TC P/IP and PP P u nderthe hood.

Finally, many embeddedInternet apps, such as secu-

r i ty, data logging, m ainte-nance, and inventory, require

minimal abil i ty to communicate. So,i t’s l ikely t hat a part icular app w on’trequire all the frills of a full-blow nserver. In fact, if y ou strip aw ay abunch of the fat you’ll f ind that t he

softw are to handle simple w eb, e-mail,and f i le duties isn’t t hat hard at al l .

How ever, if t he ’7600A put t hesehigher layer protocols in silicon,there’d be little choice but to offer arather complete implementation—probably overkill (and overpriced) forhigh-volume, cost-sensitive apps.

SILICON SERVERMike Johnson at iReady combined

the ’7600A w ith a PIC to create amin im alist w eb server (see Photo 1).Add a modem and you’re on the air.

D on’t believe that such a m easlyamount of silicon can push your bigbad brow ser around? See for yourselfat htt p://xsmall.m ycal.net .

Mike w as kind enough t o send mea copy of his code, which dem onstra-

tes the ’7600A’s power to t urn a low lymicro into a w eb wa rrior. Remember,t he P IC (’16F84) ha s a 1024-ins t ruc-tion (14 bits each) code memory tha tleaves little room for bloat.

Even the limited 1-KB instructioncapacity overstates t he softw are’s

Listing 1— When it comes to web service, it’s much easier to give than receive. To create the page, the PIC just spits out hardwired HTML ( a ). Otherwise, the software mainly just talks to the ’7600A with register access macros ( b ), leaving the chip to handle all the details.

a)

b)

CLOSED

LISTEN

rcv SYN

snd ACK

ESTAB

CLOSING

TIME WAIT

passive OPEN

create TCB

CLOSE

delete TCB

rcv SYN

snd SYN, ACK

CLOSE

delete TCBSEND

snd SYN

rvc ACK of SYNx

rcv SYN, ACKsnd ACK

SYNRCVD

SYNSENT

CLOSE

snd FIN

CLOSE

snd FINrcv FIN

snd ACKFIN

WAIT-1

CLOSEWAIT

rcv ACK of FIN

x

rcv FIN

snd ACK

CLOSE

snd FIN

FINWAIT-2

rcv FIN

snd ACK

rcv ACK of FIN

x Timeout=2MSL

delete TCB

rcv ACK of FIN

x

CLOSED

LAST-ACK

activeOPENcreate

TCBsndSYN

Figure 3— As this diagram, duplicated from the original 1981 Request For Comment (RFC793) shows, babysitting TCP isn’t easy. Don’t worry, the ’7600A handles all the details. If you’re curious, find out what state you’re currently in by checking the TCP State field in register 0x23.

Page 67: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 67/68 CIRCUIT CELLAR ® Issue 111 October 1999 83www.circuitcellar.com

Problem 1 —The circuit show n in t he figure is builton a stan dard FR-4 PCB. It is moun ted in a NEMAenclosure on a factory floor. The temperature inthe N EMA enclosure is 30 oC . The thermocouple,an E-ty pe, is moun ted on th e housing of a three-phase synchronous mot or. The mot or housing is75 oC .

The IA’s offset volt age is a + 125 µV. The IA’sint ended gain is 1000 V/V, but th ere is a 2% gainerror tha t produces an act ual gain of 1020. Assumethe E-ty pe thermocouple is linear and has t empera-tu re coefficient of 60 µV/ oC. What is the outputvoltage of th e IA?

Problem 3 —C an y ou rewri te th is funct ion to s ignificant ly increasei ts speed, wit hout chan ging the basic algorithm ?

Problem 2 —G iven th e same pressure andtem peratu re conditions, is a cubic m eter ofhum id air more or less dense than a cubicmet er of dry air?

Have you forgotten the basics since getting that management job? Did your university ignore real circuits and tell you that HTML was the only path to fortune? Each moYour EQ presents some basic engineering problems for you to test your engineering quotient. What’syour EQ? The answers are posted at www.circuitcellar.com along with pastquizzes and corrections. Questions and answers are provided by Ray Payne of Under Control, Benjamin Day of Schweitzer Engineering Laboratories, and Bob Perrin of ZYou may contact the quizmasters at [email protected].

complexity. The HTML for the homepage (stored in the PIC’s code memory)chew s up nearly half the space asshow n in Listing 1a, and a significantportion of the code handles routinetasks such as macros to bit-bang readand w rite ’7600A registers.

The guts of the server is less than100 lines of real code, not cou ntin gmacro expansions (see Listing 1b) thattake five PIC instructions for each’7600A register access. The processboils down to: open a socket, listenfor a request, increment the hitcounter, and then dump the page.

RAY OF HOPEThe ’7600A is an exciting develop-

ment on the embedded Internetfront—partly because it’s available off

the shelf, w hich opens the door forspecialized applications and garageshops tha t w ould never be able tojustify an ASIC.

Also, I like the idea of stickingw ith PP P and TCP/IP and leaving thedecisions about higher level servicesto be determin ed by t he needs of spe-

cific applications. I suspect time willshow this t o be the right decision.Few custom ers need all the protocolsw i th a l l the t r immings, and most w i l lbe glad they don’t have to pay forfeatures they don’t need.

I expect t he ’7600A to spaw n anexplosion of embedded ’Net gadgetsbecause it makes networking simpleand inexpensive, which it reallyw asn’t before.

So, if you’ve been contemplatingputting your embedded app on theInternet but couldn’t justify the costor complexity, you’d better thinkagain. And if you w eren’t contemplat-ing putt ing i t on the ’N et, bett er thinkagain anyway because the ’7600Amakes it real easy for you, and foryour competitors. I

Tom Cant rel l has been w orkin g on chip, board, and system s design and m arket ing in Si l icon Val ley for m ore than t en years. You m ay reach him by e-mai l at tom .cantrel l@circui t cel l ar.com , by t elephone at (510) 657-0264,or by f ax at (510) 657-5441.

REFERENCES[1] Stanford University Wearable

C omputing Lab, Information onembedding Linux, www.wearables.stanford.edu

[2] Information about IA OpenNetw ork ing Al l iance, w w w .iaopennetw orking.com

SOURCESiChipiReady Corp.(408) 330-9450Fax: (408) 330-9451www.i readyco .com

Seiko Instruments, Inc.Semiconductor Products G roup(408) 433-3208

Fax: (408) 433-3214w w w .seiko-usa-ecd.com /int cir/

htm l/w hat snew

NET+ARMNETsilicon, Inc.(781) 647-1234Fax: (781) 893-1338www.nets i l icon .com

Problem 4 —What does this circuit do?

Cold Junction

x1000

+

_ Ref

AD620

V out

+5 V

–5 V NEMA Enclosure

+

_

12 feet

MotorHousing

Rg

10 k Ω500-Hz sine wave +

+

IC23

IC22 R5810 k Ω

R511 M Ω

D2

D1

C13100 nF

R52 1 M Ω

Output

R571 M Ω

Probe

Page 68: Circuit.cellar.111.Oct.1999

8/13/2019 Circuit.cellar.111.Oct.1999

http://slidepdf.com/reader/full/circuitcellar111oct1999 68/68

PRIORITY INTERRUPTSpreading the Wealth of Knowledge

i ’d like to sayCircuit Cellar exists because I’ve always had a grand scheme for the perpetuation of technicalknowledge, but I’m afraid it’s a little simpler than that. I’ve just been doing things that seem worthwhile (and pretty

much being on target). At times I’ve made silly gadgets and told funny stories, but I don’t think anyone misunderstoodthat underneath all the amusing rhetoric and ridiculous contraptions, there was always a real engineering message.

Credibility is something we’ve always maintained even though our methods of presentation have frequently bordered on theextreme. Our engineering message is clear. The important thing aroundCircuit Cellar is application, application, application.

I’ve done a lot of things over the years to promote this ideal, and I get a lot of mail from the people who have been influenced byit. One of the inspirations that I look back on with great pride is our College Engineering Program. In this program, college professorsregister the students in their engineering classes and we give them free copies ofCircuit Cellar for the semester. I learned at an earlyage that there were only two ways to learn things: trial and error, or somebody tells you. Our College Engineering Program is my wayof giving our educational process a little “somebody tells you” boost.

I get a lot of positive correspondence from the program, but a recent letter from Jack Dillon of Analog Devices summed it up quitenicely. I thought I’d share some of the salient points in it with all of you.

Circuit Cellar has been a tremendous influence in my work and I cannot imagine where I would be today without it. Where Iwork, we bring in engineering students from a local university and develop them. Actually, it is a two-way learning experience. Iam in awe of some of their skills and totally baffled by their lack in other areas. They typically know C and maybe someassembly, but when we get to running an app on an 8051 or other small micro, they really come up short. The look on their face,when you tell them that using will use up all of the available code space, is priceless. The good news is that theirengineering (math, physics, etc.) and general computer skills are superb.

All of the engineering students we have hired have at least seen a copy ofCircuit Cellar . The students that looked forward toevery issue were a step above the rest. I needed to let you know how much influence your magazine has had with myself and theengineering students we work with.

Circuit Cellar has done a tremendous job of presenting the entire picture–lots of hardware and plenty of software, but mostimportantly, how the two are brought together to make the system work. That, from my perspective is what embedded systemsare all about.

Our college program is just one aspect of the continuingCircuit Cellar message. Students, regular subscribers, and Internettechies can now enjoy even more applications each month throughCircuit Cellar Online . We have lots of editorial coming from thewinners of our Motorola Design99 contest who will be announced in the December issue and our recently announced InternetPIC2000 contest (running onCircuit Cellar Online ).

This month we’re extending our application goals even further as we inaugurate our regular print magazine contest—Design 2K.This year I am especially proud to announce that it is an 8051-based competition sponsored by Philips. Quite surprising, consideringthat we’ve published many 8051-family articles over the years, is that we’ve never had an 8051-exclusive contest before. The widerange of 8051 core products offered by Philips will no doubt result in some truly esoteric and ingenious entries


Recommended