circuit cellar - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/circuit_cellar/circuit...

68
CELLAR THE MAGAZINE FOR COMPUTER APPLICATIONS www.circuitcellar.com CIRCUIT ® # 1 1 1 O C T O B E R 1 9 9 9 EMBEDDED SOFTWARE Open-Source Home Automation Program Downloadable Web Server Software How Does Windows CE Stack Up? The Roots of Java

Upload: buidan

Post on 25-Sep-2018

233 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

CELLART H E M A G A Z I N E F O R C O M P U T E R A P P L I C A T I O N S

ww

w.c

irc

uitc

ella

r.c

om

CIRCUIT®

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

EMBEDDED SOFTWAREOpen-Source Home Automation Program

Downloadable Web Server Software

How Does Windows CE Stack Up?

The Roots of Java

Page 2: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

— COLUMNS —Considering the DetailsI/O for Embedded Controllers—Part 1: Digital I/OBob PerrinI/O, I/O, so off to work…. Designing generic controllerswith only guesstimations of what the end-product I/Oneeds might be keeps Bob busy. Save yourself some workand look at the circuits covered in Part 1 of this series.

Lessons from the TrenchesPowering Your MemoryGeorge MartinFar too often, especially in programming, you can get awaywith what’s less than best. Having personally tried allthe less-than-best methods to write memory managementroutines, George invites you to listen in as he shares thebest way to accomplish the task.

Silicon Update OnlineWire WarsTom CantrellThe action’s getting lively on the USB–versus–IEEE 1394 front as bothsides fortify their legaldefenses andrally

the troops.Catch Tom’s latest

report from the 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 MillierWhen he got his TV satellite dish, Brian discovered thefreedoms of satellite network programming—and thelimitations 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 SolutionPeter GravestockUpgrading firmware 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 remote and automatic fixes can be.

Testing 1, 2Part 3—Standards: Prepping Your PrototypeGeorge NovacekCoping with environmental challenges is a walk in thepark in comparison to getting the power right. Georgeexplains the testing requirements as well as the changesyou’ll need to make for your product to succeed.

Ethernet Networking: Desktop to DeviceWilliam Peisel and Dick CaroAfraid to venture into the gloomy tangle ofEthernet? William and Dick aren’t tellingtales when they say low costs andInternet integration capa-bilities will lead toEthernet

networks atall levels of industry

in the near future.

Resource Links• CAN–Controller Area Network• Digital Signal ProcessingBenjamin Day• Printed Circuit Board Software and Manufacturers• Pointers to NanotechBob Paddock

Test Your EQ8 Additional Questions

Connect Your PIC to the Internet

NOW, GETTING CONNECTED TO THEINTERNET CAN EARN YOU CASH

www.circuitcellar.com/pic2000

PIC® 2000contest

Internet

Table of Contents for September 1999

WWW.CIRCUITCELLAR.COM/ONLINE

Page 3: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

38 Nouveau PCedited by Harv Weiner

40 What’s in a Name?Windows CE vs. a Hard RTOSMal Raddalgoda

45 RPC Real-Time PCWhere in the World...Part 3: Fighting the Wind with GPSIngo Cyliax

50 APC Applied PCsGoAhead for Nothing—Getting the Server StartedFred Eady

ISSUEINSIDE

MisterHouse—An Open-Source Home Automation ProgramBruce Winter

The Java Virtual MachineDave Lyons

A Versatile Timer/SynchronizerBrian Millier

Calling on the Standards—Making Sure Your Modem Can CommunicateArthur J. Carlson

Hands-On PIC Trainer—Programming in AssemblyJon Varteresian

IrDA Technology—Part 1: An OverviewHari Ramachandran

I MicroSeriesRolling Your Own MicroprocessorPart 2: Design Application with the Rabbit-80Monte Dalrymple

I From the BenchGet SmartMedia—Part 2: Hands OnJeff Bachiochi

I Silicon Update‘Net-in-a-ChipTom Cantrell

6

8

11

83

95

96

12202430566066

72

78

111111

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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

THE MAGAZINE FOR COMPUTER APPLICATIONS

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 in Circuit Cellar®.Entire contents copyright © 1999 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit 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 having contributedsomething. 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

8 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 most of the circuitry commonly used withPICmicros, including a 5-V power supply, crystal-con-trolled oscillator (adjustable from 4 to 20 MHz), andreset circuit. Application circuits include a switchmatrix, potentiometers, LEDs, LCD module, serialEEPROM, real-time clock, temperature sensors, servoconnectors, RS-232/-485 and IR interfaces, and speaker.

All of the I/O pins are brought out to headers nextto a 40-pin ZIF socket. This allows connection tooffboard circuits as well as allowing onboard circuits tobe connected to other PICmicro pins, if desired. ThePIC-X1 is designed to work with 40-pin PICmicros, butmay be jumpered to work with smaller devices.

Projects such as calculators, LCD clocks, digitalthermometers, LCD backpacks, tone dialers, TV re-mote controls, and so forth may be created using thePIC-X1. It includes in-circuit programming 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 PIC-X1 is priced at $199.95 for an assembled unit,$139.95 unassembled, or $49.95 for a bare PCB. A partslist, schematic, and example programs are also included.

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

EMBEDDED CONTROLLER MODULEUni-Micro is a compact, 8051-compatible embedded

controller module featuring a combination of memory,digital I/O, and analog I/O that is perfect for instru-mentation, monitoring, and control applications. Itprovides enhanced JTAG-based serial programmingthat 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 battery back-upscratchpad SRAM, 3000 gates programmable logic, and54 programmable I/O pins.

The eight I/O ports on the Uni-Micro can functionas microcontroller I/O, CPLD I/O, address out, addressin, latched address out, latched address in, data port,special function out, alternate function in, peripheralI/O, or open-drain outputs. Each I/O port is easilyconfigurable by programming two 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 the MCU ROM. Serial programming of theUni-Micro module can be accomplished using a PCequipped with a JTAG board.

By integrating all the programmable logic, concurrentflash memory, data flash memory, SRAM, and I/O MCUcore, the Uni-Micro Module has a power consumptionof 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

NEW PRODUCT NEWSFIBER-OPTIC MODEM

The Model 232FLST Fiber-Optic Modem providesthe EMI/RFI and transient immunity of fiber optics ina transparent cable connection between PCs 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 twopieces of asynchronous RS-232 equipment tocommunicate full or half duplex over twofibers up to 2.5 mi. RS-232 data signals at upto 115.2 kbps and RTS/CTS handshake linesare supported. Port powering allows operationwithout external power in most PC applications.Low-powered ports such as laptops may require anoptional 12-V power supply.

The RS-232 connector is DB-25 female and thefiber cable connectors are ST style. The modem isonly 4.3″ × 2.3″ × 1″.

The modem sells for $154.95 (two 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

NEW PRODUCT NEWSPHONE LINE SIMULATOR KIT

Ring-It! is a microprocessor-controlled telephone-linesimulator 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 simulator 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 also 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-cycletesting, including automatic ring-up. An LED readout

displays the DTMF digitsthat are dialed to verify useof touch-tone phones.

Ring-It! can be purchasedassembled or as a kit thatincludes a PCB, electroniccomponents, and a techni-cal manual.

The factory-assembledunit (RI-001F) sells for $325.The deluxe kit (RI-001D) is$205 and includes thecaller-ID option and cus-

tom enclosure. Non-caller-ID kit versions (RI-001) areavailable starting at $149.

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

Page 8: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

READER I/OKEEPING UP TO DATE

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

TI no longer supports this device, but Texas Ad-vanced Optoelectronic Solutions (TAOS) has licensedthe optoelectronic sensor product portfolio (whichincludes the TSL1401) from TI. Information can befound at www.taosinc.com or by calling (972) 673-0759.

Carl [email protected]

FINDING THE WAY AROUND SAI enjoyed the GPS article by Ingo Cyliax in the

August issue (109) and the earlier series by Do-WhileJones (Circuit Cellar 77–78). Both did a great job ofgetting right to the meat of the matter. However, botharticles may give readers a misunderstanding withregards to Selective Availability (SA) and position error.

The DoD implemented SA by diddling with thetiming of the signals, among other things. This trans-lates into a different range error for each satellite.These range errors, once crunched through the math,give the position errors noted in the articles.

Both articles gave the impression that the SA errorscan be “subtracted out” by knowing the position errorof a known fixed site. Here’s the rub—the fixed site’serror in position will only be the same as the observer’sif both positions were computed from the same set ofsatellites. In the real world, any two GPS receivers mayuse different satellites if one particular satellite islocally obscured. In that case, the position errors arelargely uncorrelated, and fixing the problem, as out-lined in the articles, can actually make matters worse!

To fix SA, broadcast the range errors, not the positionerror, so the corrections can be made before the data iscrunched. That’s what the Coast Guard and otherDGPS providers do. I hope this clarifies things.

John WilsonAnnandale, VA

Page 9: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

12 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.

et’s start witha quiz. Which of

the following bestmatches your philosophy

in home automation?

• Computers are too ornery and difficultto manage to be meddling in dailyaffairs of the house.

• Automating daily house chores witha computer is a fun and useful thingto do, but it can only reliably be donewith a dedicated and specializedmicroprocessor.

• PCs are destined for more than justsending e-mail and playing golf;soon they will rule the world (or atleast parts of your house)!

If you subscribe to the first philoso-phy, you’re probably reading the wrongmagazine. I bet a good number of youare members of group two. I used to bea member of this group when I startedworking with home automation (HA)with Steve’s first Home Run HA sys-tem from the BYTE magazine 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 widerchoice of programs and hardware tointegrate. Every day it seems like thereis some neat new program or deviceyou can hook into a PC.

At my day job (designing chips atIBM), I’ve found great productivity ina programming language called Perl.About a year ago, I decided to write aPerl-based, open-source multiplatformHA program. I call it MisterHouse—which is easier than calling it a Perl-based, open-source multiplatform HAprogram.

This article gives a little backgroundon MisterHouse and shows how I useit to log phone calls and announce whois calling over our house PA system.

WHY OPEN SOURCEIt used to be that when someone

wrote a program and then made itavailable for free, it was called “freesoftware.” Often, only the binary forthe program would be distributed.

Recently, the term “open source”has been promoted. There’s an officialdefinition at www.opensource.org/osd.html, but the basic idea is thatthe source of the software is posted onthe Internet so that anyone can helpwork on it.

With new hardware becomingavailable daily and the amount ofinformation on the Internet growingexponentially, the number of HApossibilities is growing faster thanany one person can possibly keep upwith. Using the open-source idea, ifthe program doesn’t do what you needdone, you can extend it and then shareit for others to use.

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

THE OS DECISIONHere’s another quiz: Which is the

better OS to do HA on? Windows andthe great wealth of fun software avail-able on it, or a Unix OS with its 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

independent. For example, on Windows,a serial port item will use the Serial-Port module to read and write serialdata using Win32 API calls to a serialport DLL. On a POSIX-compatible Unixsystem (Linux and most others), thatcall is translated by the SerialPortmodule to use POSIX TERMIOS calls.

Here’s another example. When youask MH to run a background processon Windows, the Perl Win32::Pro-cess module is used; on Unix, the forkfunction 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 with built-in voice soft-ware, but it talks to programs that do.

On Unix, you can implement textto speech (TTS) with the Festival speechsynthesis system. Festival provides aserver that MH can talk to via TCP/IP

sockets, and you can plug in differentvoices and languages.

On Windows, you can do both TTSand voice recognition (VR) using freelydownloadable engines from Microsoft.These engines provide access via OLEmethods, which Perl also supports.Several different voices are available,including some digitized voices thatsound amazingly humanlike.

The VR is in a command-and-con-trol mode (i.e., it will not recognizeany arbitrary set of words; only theones from a set of phrases you specifyusing the MH Voice_Cmd object).This mode improves reliability overwhat you might get with a dictationmode, where any word can be expected.

PICK YOUR INTERFACESAll of the voice command objects

you specify will be available with VR,as well as from the command line, aGUI Tk interface, and a web interface.

The Tk interface is built using PerlTk widgets. These widgets enable usto create GUI objects with just a fewlines of code. Photo 1 shows the de-fault Tk interface.

The web interface can be used fromany Internet browser, whether it’s inyour house or not. The interface usesa web-authentication password to allowremote control (e.g., go to misterhouse.net and you can take a look at the oneon my house).

Using HTML templates, the webinterface can be easily changed. Thedefault web interface is shown inPhoto 2.

Other programs communicate withMH through TCP/IP sockets or viacommands in a file. The “HardwareInterfaces” sidebar shows the variousinterfaces that MH currently supports.

A QUICK LESSON IN PERLAll HA programs have some sort of

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

Perl is a powerful language and itcan take quite a while to learn all ofits tricks. But, by using object-ori-ented programming and extending itwith HA-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 want to cover afew basic Perl syntax rules. All vari-ables start with a $. Strings are quotedwith either single or double quotes. Usedouble quotes if you want variableswithin the string to be substituted.

Commands begin with # and com-mands end with a semicolon. Do loopsand conditional blocks start and endwith . There are two ways to doif statements—if (test) ac-tion and action if test;. Iftests are == (or !=) for numeric dataand eq (or ne) for string data.

Local variables are declared withthe function called my. Object methods(e.g., set) can be specified in two ways:

set $dishwasher ON; # Indirectobject form

$dishwasher->set(ON); # Classic'object oriented' form

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 time_now function can handle time offsets and the $Time_Now variable will get substi-tuted on-the-fly.

$pedestal_light = new X10_Item("O5");if (time_now "$Time_Sunset + 0:30") set $pedestal_light ON; speak "I just turned the pedestal light on at $Time_Now";

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

$callerid = new Serial_Item('I');$phonetone = new Serial_Item('O');

if ($caller_id_data = state_now $callerid)# On startup, old caller-id strings might be sentignore them if (time > ($Time_Startup_time + 15)) speak("rooms=all " . &Caller_ID::make_speakable($caller_id_data)); my ($cid_date, $cid_number, $cid_name) = unpack("A13A13A15", caller_id_data); logit("$Pgm_Path/../data/phone/logs/ callerid.$Year_Month_Now.log", "$cid_number $cid_name"); logit_dbm("$Pgm_Path/../data/phone/callerid.dbm", $cid_number, "$Time_Now $Date_Now $Year name=$cid_name");# Log outgoing phone numbersif ($phonetone_data = state_now $phonetone) logit("$Pgm_Path/../data/phone/logs/phone.$Year_Month_Now.log", $phonetone_data)

Page 11: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

By looking at the examples suppliedwith the MH package, you can learnwhat you need to know about Perl forits use in MH. Another good startingpoint is www.perl.com. The referencebook of choice is Programming Perl. Ifyou want to know how to do somethingin particular, The Perl Cookbook 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 with a speaker in key rooms.

But what if you want to have aconversation with your house in theliving room while your spouse is try-ing to sleep in the bedroom? You caneither get him/her a nice set of earplugsor you can insert a computer-controlledrelay card between the PA amplifier andthe speakers, as shown in Figure 1.

The digital I/O card is an inexpen-sive ($30) PIC-based card availablefrom Weeder Technologies. The relaycard is a Universal Relay Card fromJameco ($100). By modifying pa_con-trol.pl, you can define which roomis controlled by which relay.

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

speak "rooms=bedroom Time towake up";

speak(rooms => "all", text =>"The laundry clothes aredry");

The other two Weeder cards shownin Figure 1 let you monitor outgoing andincoming phone numbers. The DTMFcard detects any pressed phone keys,and the caller-ID card decodes the nameand number of incoming calls. If youhave a caller-ID-capable modem, youcan use it instead. By sensing when themodem is not in use, MH can sharethis modem with other programs.

The code in Listing 2 monitors thedata coming from these two cards.

The Weeder kits have a simple proto-col that uses the first character of astring to indicate which card is send-ing data: “I” is for the caller-ID cardand “O” is for the DTMF card. The MHcode detects these codes and stores theincoming data in the $callerid and$phonetone objects.

The $caller_id_data string isparsed by the Caller_ID::make_speakable function, which changesthe phonebook-formatted name into amore pronounceable name. For example,it changes “WINTER BRUCE LA” into“Bruce Winter” by swapping 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 will use a user-defined rule to replace the receivedname with a more phonetically correctname or a prerecorded WAV file.

$phonetone_data and $caller_id_data are logged into monthly logfiles that can be retrieved and displayedby display_calls. The Tk interfacefor this feature is shown in Photo 3.

The caller-ID signal is sent betweenthe first and second rings. In order togive MH a chance to decode and speakthe caller-ID information before thephones start ringing, a ring morpher isinserted between the external phoneline and the other phones in the house.

The ring morpher has the sideeffect of delaying the ring by one

Figure 1— The computer’s sound card drives the housePA speakers through a relay card controlled by a digitalI/O interface. The phone line is monitored with DTMFand caller-ID cards.

Serialport

Soundcard

Computerspeakers

DTMFdecoder

Phoneline

Caller ID PAamplifier

Digital I/ORelaycard

Speaker1

Speaker...

Speaker8

+12 V

Hardware InterfacesCM11—The ActiveHome kit ($50) includes a two-

way X-10 CM11 interface, lamp module, and acouple of remote controllers.

Weeder kits—Weeder Technologies offers the follow-ing PIC kits, priced from $30 to $50 each:

• two-way X-10 interface• 12-bit digital I/O (can be input or output, switch

or button)• 8-port analog I/O, 10-bit resolution• caller ID: name and number• outgoing DTMF phone monitor

These kits are good for PCs with a limited numberof serial ports because they can all share the sameserial port.

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

WX200/198 weather stations—These weather stations areavailable from Radio Shack and mail-order catalogs,ranging in price from $200 to $300. They monitorindoor/outdoor temperature, humidity, barometricpressure, wind speed and direction, wind chill, andrainfall amounts.

Modem—Using the is_available method, a caller-ID-capable modem can be shared with other programs. Itcan also be used to send messages to pagers.

Ham radio TNC modem—Using a ham receiver attachedto a radio modem (terminal node controller), MH canmonitor packet radio traffic. This information includeslocations and speed of cars equipped with GPS devicesand weather information from home weather stations.

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

Page 12: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

cycle. This delay allows us tohear the caller-ID announce-ment (e.g., “phone call from BillClinton”) at the same time thephones start to ring.

OTHER EXAMPLE EVENTSHere are a few of the events

we use to control our house.You can find them online (seethe Software section).

I have window quilt curtainshooked up to pulleys attachedto 24-V DC motors and a set ofrelays. Each curtain has tworelays—on/off and up/down.These relays are driven eitherby local switches or by WeederDIO outputs. curtains.plmonitors the outside tempera-ture and sunlight levels using aWeeder analog kit, and opens orcloses the south-facing curtainsto maximize solar heat gain inthe winter months.

The deep_thought.pl trivia.plmodules display and/or speak fun factsfrom various databases. It certainlymakes breakfast entertaining!

door_monitor.pl monitors dooropenings and closings using magneticreed relays connected to Weeder DIO

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

It also monitors movements inhallways and stairways using X-10

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

Photo 1— The bottom two frames are logs of what has been spoken andlogged. 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 tell where people aregoing—sort of like a high-techsqueaky door!

internet_data.pl retrievesand processes pages off the web(e.g., Letterman’s top 10 list, localweather conditions). It also setsthe clock according to an Inter-net-connected atomic clock.

The internet_mail.plevent uses a background processto call the get_email script,which checks who has sent youmail in specified e-mail boxes.After the process has finished,MH announces what new e-mailyou received and from whom.

Using a user-specified IPsocket port, telnet.pl lets youuse a telnet program to log in,

specify an optional password, and issuecommands.

Like a kitchen timer, timer_sec-onds timer_minutes timer_hoursperiodically tells how many seconds,minutes, and hours are left on yourtimer.

A ham-radio enthusiast wrote thetracking.pl code. Using a GPS 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 position with respect tovarious landmarks (e.g., “Dad’s carhas just left the IBM parking lot” or“Junior’s car is parked at lover’s lane”).

This code does other nifty thingswith packet radio (e.g., monitor currentweather conditions from the nearestpacket radio–connected weather station.

Using the get_tv_grid script in abackground process, tv_grid.plcollects customized TV programmingfrom the Internet to local files. It addsa “program the VCR” button to theTV grid entry, so you can not only seewhat’s on but also instruct MH to createan event to start and stop the VCR ata certain time for the specified channel.

weather_monitor.pl weather_wx200.pl reads data from a WX200or WM918 weather station. It then logs,displays, and optionally speaks the data.

Page 13: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

SOFTWARESoftware for the MisterHouse appli-cation is available via the CircuitCellar web site, misterhouse.net,and misterhouse.webjump.com.

Bruce Winter designs integrated cir-cuits as a senior engineer at IBM inRochester, MN. This has nothing todo with home automation, but itsounds impressive in a bio. You mayreach him at [email protected].

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

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

hardware currently supported, you canstill run MH and play around with theweb, Tk, VR, and TTS interfaces.

The install.html file has theinstallation instructions. mh.html hasdocumentation on the various objects,methods, and functions, and updates.html contains a list of updates.

mh_src_###.zip has all the sourcecode, support files, and documentation.If you don’t have Perl installed, you’llneed mh_win_###.zip or mh_linux_###.zip, which have the platform-dependent compiled versions of MH.

Depending on how many events youload and if you have the Tk interfaceturned on or not, MH will use from 5to 15 MB of memory. At ten passes persecond, it uses about 30% of the CPUcycles of a 100-MHz Pentium CPU.

So, dust off that old PC, give yourhouse a little personality, and comejoin the open-source movement andmake the world a better place! Or atleast have your house train your kidsto keep the back door closed. I

RESOURCEST. Christiansen and N. Torkington,

The Perl Cookbook, O’Reilly,Sebastopol, CA, 1998.

MH events for author’s house,misterhouse.net/mh/code/Bruce

Mailing list, www.onelist.com/subscribe.cgi/misterhouse, www.onelist.com/archives.cgi/misterhouse

L. Wall, T. Christiansen, and R.Schwartz, Programming Perl,O’Reilly, Sebastopol, CA, 1996.

SOURCESDigital I/O cardWeeder Technologies(850) 863-5723www.weedtech.com

Universal Relay CardJameco(800) 536-4316(415) 592-8097Fax: (415) 592-2503www.jameco.com

TTS and VR engineswww.microsoft.com/iit/download/ speechengines.htm

Text-to-speech with Festivalwww.cstr.ed.ac.uk/projects/festival

ActiveHome kitX10 (USA), Inc.(800) 675-3044www.x10.com

InterfacesJDS Technologies(858) 486-8787Fax: (858) 486-8789www.jdstechnologies.com

Page 14: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

The Java Virtual Machine

FEATUREARTICLE

Dave Lyons

iIs dependability morevaluable than speed?When James Goslingcreated Java, hethought so. Daveagrees and wants toshow us the JavaVirtual Machine andhow easy and howconvenient workingwith Java can be.

n 1991, JamesGosling was develop-

ing a new programminglanguage for use in intelli-

gent consumer devices. He started withC++ but realized that no number ofextensions to the language would meetthe requirements. Because intelligentdevices need a wide variety of OSs andprocessor families, the new languageneeded to be machine independent.

Gosling designed a language wherethe source code was compiled intomachine code targeted at an abstractprocessor. Applications wouldn’t haveto be recoded or even recompiled. Onlythe code that implemented the abstractprocessor would have to be ported.Gosling named his new language Oakafter the tree outside his window.

Oak was object oriented and pro-grams were composed of classes andinterfaces. An interface defines a setof methods that a class can implement.This approach allows much of thefunctionality of C++’s multiple inher-itance without the runtime overhead.

The Oak syntax was similar to Cand C++. A handful of basic typeswere provided including byte, short,int, long, char (an unsigned 16-bitvalue), float, double, and boolean.

The sizes of these basic types wereexplicitly defined so that Oak applica-tions would behave consistently across

various platforms. Floating-pointfunctionality was based on the IEEE-754 standard and was explicitly de-fined so programmers could preciselypredict behavior.

In developing Oak, Gosling deter-mined that reliability was more im-portant than speed. Consumers expectappliances such as VCRs, telephones,and toasters to work. They wouldn’ttolerate a product that needed to berebooted. Several aspects of Oak’sdesign reflected the reliability issue.

Objects in Oak were allocatedusing the new operator but were onlyreturned to the heap when the garbagecollector determined that there wereno longer any references to the object.

Oak also avoided the problem ofusing variables before they were ini-tialized by rigorously checking to besure that all variables inside an Oakmethod were set beforehand. A used-before-set condition resulted in a fatalcompiler error. And, perhaps the mostsignificant reliability-related change—there were no pointers in Oak.

OAK BECOMES JAVAAs time passed, Sun’s Green

project (later spun off as FirstPerson,Inc.) was shut down when no marketcould be found for the technology. Ata group meeting, Gosling, along withother Sun notables such as Bill Joyand John Gage, recognized that theInternet had recently been made moreaccessible by way of web browsersand that it was a good fit 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 way.

The goals Gosling had set out toaccomplish fit perfectly with the wayapplications were being written, de-livered, and used on the Internet.Although the discovery was quiteaccidental, it appeared that the Oak/Internet combination had potential.

Oak was eventually renamed Javaand a web browser called HotJava waswritten in the language. This browser,besides being able to display standardweb pages containing text and graph-ics, also permitted small applications(applets) to be embedded in pages.

Page 15: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Userprogram

class files

Java APIclass files

Class loader

The Java Virtual Machine

Internal class representation(includes bytecodes)

Execution engine

Java API native methods

Host operating system

Sun decided to make Java and Hot-Java freely available 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,known as the Java Virtual 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 also needed tobe ported to the new platform. TheseAPIs defined standard mechanisms forgraphics and windowing, file storage,and network access.

Figure 1 illustrates the Java run-time environment. User programs andthe bulk of the Java API reside in classfiles which the 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-wide registers—the programcounter, top of stack, current stackframe, and local variables pointer. In-structions for the JVM consist of a one-byte opcode followed by zero or moreoperands. The instructions vary incomplexity from simply pushing aconstant onto the stack to allocating amultidimensional array of objects.

The JVM is also able to make callsto native methods, which are imple-mented in a native system language,typically C or C++. Native methodsare used to interface to the underlyingOS, but they can be used in othersituations 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 wrapperfor 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 portability (or as Suncalls it, “Write once, run any-where”) is key to Java’s ap-peal, so Sun created a programcalled 100% Pure Java. To becertified 100% Pure, an appli-cation can be made up ofonly Java bytecodes.

THE PERFORMANCE KEYIt’s not hard to imagine that

the key to 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 most of the timeis spent interpreting the byte-codes. Because of this, mostefforts to improve Java per-formance have focused onspeeding up the interpreting process.

The simplest way of speeding upthe bytecode interpreter is to hand-code the interpreter loop in nativeassembly language. This approachoften results in a smaller interpreter,which takes advantage of modernmicroprocessor cache as well as in-struction pipelining. Writing thebytecode interpreter in assembly lan-guage can increase the speed twofold.

A larger performance gain can beachieved by using a just-in-time com-piler (JIT). A JIT converts the Javabytecodes to native machine code atruntime, resulting in speed increaseson the order of 10×, which is helpfulfor computationally intense code.

However, a JIT can result in aspeed decrease when there’s a largeamount of code that isn’t executedfrequently. This setback is because ofthe overhead of converting the Javabytecodes to native code.

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

Methods that are frequently calledcan be inlined and the code insidemethods can be optimized becausemuch more information about a pro-gram is available at runtime than atcompile time, which is where optimi-

zations have traditionally been done.Although no concrete performancenumbers have been published, Sunhopes HotSpot will enable Java perfor-mance to approach that of C++.

HARDWARE CONSIDERATIONSThe bytecode interpreter plays a large

role in determining the performance ofJava on a particular platform, but theunderlying hardware also plays a sig-nificant role. A processor with a highclock rate may not perform as well as aslower processor with a larger cache.

Although true in general, executingJava code magnifies the difference be-cause so much time is spent in therelatively small bytecode interpreter.The effect would not be as pronouncedif a JIT or HotSpot-based interpreterwas used. A bytecode interpreter thatfits entirely into cache could dramati-cally affect Java performance.

Floating-point support can also besignificant in determining Java perfor-mance on a platform. Processors with-out floating-point hardware process theJava floating-point instructions up to10× slower than similar processorswith hardware floating-point support.

The problem is compounded by thefact that processors lacking floating-point support are typically lower horse-power chips aimed at consumer devices.Application programmers should take

Figure 1 —The class loader converts Java code files into a formusable by the execution engine. The underlying operating systemservices such as networking and graphics are accessed throughnative methods in the Java API.

Page 16: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

note of this situation. If a piece ofcode is targeted at consumer devicessuch as those based on the new Per-sonalJava platform, floating-pointusage should be kept to a minimum.

ULTIMATE JAVA PLATFORM?It may seem that the obvious an-

swer to the Java performance questionis to build a JVM in hardware. Sun hasdone just that with their picoJava ar-chitecture, which uses Java bytecodesas its native language.

The architecture is also designed tooptimize access to the Java stack. Eventhough these Java chips may seem likethe obvious choice, many 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 microprocessor canmake a huge impact on the economicviability of a consumer product. If oneprocessor includes built-in peripheraldevices such as serial ports or an LCDdriver at a lower price than a compet-ing chip, a difference in executionspeed may become inconsequential incomparison to the difference in price.

Java chips may offer the best per-formance, but when a technology likeHotSpot narrows the gap between 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

Dave Lyons is a software architect atMicroware Systems. During his 12years there, he has worked with filesystems, booting mechanisms, anddevelopment tools. Currently, Daveis focused on the company’s port ofPersonalJava for OS-9. You mayreach him at [email protected]

SOURCE

Java Virtual MachineSun Microsystems(800) 786-7638(408) 276-5200Fax: (408) 276-0633www.java.sun.com

Page 17: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

A Versatile Timer/Synchronizer

FEATUREARTICLE

Brian Millier

sYou may not be ableto teach an old dognew tricks, but youcan use Visual Basicto train a group ofcounter/timer devices.Brian shows us howto 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 rarelyexisted outside of Disneyland but arenow becoming commonplace on thefactory floor. These specialized robotscan be trained by human operators todo assigned tasks with little outsideintervention.

This project follows the same phi-losophy as the industrial robot, just ona smaller scale. At its heart is a groupof counter/timer devices controlled bya PIC16F84. Training the device (i.e.,setting the configuration and timingparameters of all the timermodules) is done with aWindows-based programrunning on a PC.

After you choose a con-figuration, you downloadthe data via a serial port tothe PIC16F84. The deviceis now a freestanding unit,producing all the timingsignals, synchronized trig-gers, and everything elseneeded for the application.Only if you needed to

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

The CTS9513 was designed toprovide a master timing synchronizerand pulse generator for a laser-basedresearch instrument. Like most cus-tom research equipment, the actualrequirements weren’t well-known inadvance. In the past, similar situa-tions have led to time-consumingredesigns. This time, I built a generaldevice using two CTS9513 counter/timer devices (see Figure 1).

Each CTS9513 contains a five-stagescaler and five 16-bit timing modulesthat can be programmed to handledivide-by-n, delay, or PWM functions.Many of the clocking and gating inter-connections among the timing mod-ules can be configured in software andmany additional interconnection per-mutations can be handled by jumpers.

In addition to the two scalablequartz oscillator clock sources is apower-line zero-crossing trigger (60 or120 Hz), as well as provision for anexternal clock source. Eight of the 10timing modules are buffered and rout-ed to BNC outputs that can be set toproduce either active-high or active-low outputs (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-tuting an AMD AM9513, you can usea quartz crystal instead of an oscilla-tor module, but the maximum clockfrequency is 7 MHz.

In Circuit Cellar 78, I described aportable pulse generator based on anAM9513 that generated various user-

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

Page 18: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

defined pulse trains, but thetimer configuration wasfixed in firmware.

This time, I used the’16F84 as the controller chip.This $5 micro has enough I/Olines to control two CTS-9513 timers, a serial link tothe host PC, and a status LED.

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

Developing the program code wentquicker because I didn’t have to wait fora UV erasure of the device with eachcode modification. Although the ’16F84doesn’t contain a UART function, it’sfast enough to implement a 9600-bpsserial input function in software.

The CTS9513s go for around $30and the total chip cost for the circuitis about $80—quite reasonable consid-ering the unit’s capabilities.

HARDWARE DESCRIPTIONI broke up the circuit diagram into

two parts. Figure 2 shows the control-ler, timer ICs, power supply, serialport, and everything else needed. Notethat I used one AM9513 and one CTS-9513 to show the different clock cir-cuit needed for each device. Apartfrom that, programming the devices isthe same. Use whatever device youhave available.

Figure 3 shows the input clock/gateselection circuitry as well as the out-put buffering and polarity selectioncircuits. Depending on your applica-tion, the circuitry shown in Figure 3could be different. For example, theoptocoupled inputs and 50-Ω outputdrivers (necessary in the noisy envi-ronment my unit encounters) may notbe necessary in your application.

Q1 and the associated parts convertthe RS-232 serial data from the hostinto TTL levels, which is fed intoRA0 of the ’16F84. Software routinesin the micro convert the serial data-stream into parallel form. Notice that

there’s no hardware handshaking. Thehost application paces its transmissionof parameters to match the ’16F84’sresponse time, which is limited bythe flash-memory write cycle time.

I tied the 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 the design, when I wasusing a terminal program to send thecommands and parameters. My prob-lem was remembering to send theupper-case command mnemonics thePIC firmware expects!

Port pins RA1–RA3 provide thecontrol signals for the ’9513 devices.The CTS9513 uses a data-pointerarchitecture to access its 30+ regis-ters, so only a *WR line is needed foreach device (along with a shared com-mand/*data line). This design neverreads the ’9513’s registers, so the *RDline is tied high and the RA4 linedrives a status LED, which is de-scribed later.

Port B is programmed as an outputport to provide the 8-bit data bus forthe ’9513s. Notice that these devicesactually have a 16-bit bus. The uppereight bits must be tied high and acommand sent to the device to enableit to operate in the 8-bit mode.

The power supply is conventionalexcept that the bridge rectifier acts asboth the full-wave rectifier for thepower supply and provides 120-Hzunfiltered DC to optocoupler U3 forthe zero-crossing detector circuit. Aseparate diode, D2, is used if 60-Hzzero-crossing is needed.

The zero-crossing detectoris a simple MOC5009 optodevice with a Schmitt triggeron the detection side to re-ject AC line noise. As config-ured, this circuit provides atrigger whose rising edgeleads the 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 would 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 powerup. This setupensures stability when the CTS9513sare loaded, which is important be-cause they are only loaded at power-up. I used the LM2925T, but you canuse a conventional ’7805 and put acapacitor to ground on the *MCLRline instead.

The gating and output circuitry inFigure 3 is pretty straightforward. Ichose ’74128 50-Ω driver devices be-cause they provide TTL-level signalswith lots of drive for opto-couplersand are more robust when drivinglong cables that pick up inductivenoise. The 74LS86 XOR gate allowsfor output polarity selection, as wellas 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 myselfto use C with small micros contain-ing only a few kilobytes of memory

Clock

Clock

PIC16F84RS-232

CT

S95

13 #

1C

TS

9513

#2

Buf

fers

Buf

fers

Outputs1–5

Outputs6–8

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

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

Page 19: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

www.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-critical bit ma-nipulation of ports.

The firmware con-sists of:

• 9600-bps serial datainput routine, using asoftware UART

• simple commandmnemonic parsingroutine

• data EEPROM writ-ing/reading routines

• ’9513 setup and reg-ister-loading routine

When writing codefor a small device withfew debugging facili-ties, it makes sense todevelop general soft-ware routines to assistin debugging. So, alongwith the necessaryprogram code, thefirmware also containsroutines to write to any dataEEPROM location, read any EEPROMlocation by sending it out to Port B,and manually load any of the ’9513register(s) via serial port.

Because of limited RAM space inthe ’16F84, the 58 parameter bytes inthe ’9513 that are downloaded 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-tion must “pace” the download toallow for this condition. I wanted a9600-bps routine for other projects,which explains my choice of 9600 bpsrather than a much slower rate, whichwouldn’t have needed any pacing.

The correct operation of the ’9513timer modules depends on their re-ceiving the correct parameters atpowerup, so I wanted 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 data thatmake up the ’9513’s parameter/con-figuration data are supplemented by asingle checksum byte, which is calcu-

lated by the host application programand sent along with the rest of thedownloaded data.

Immediately after a download (andat each powerup), a checksum calcula-tion is done on the data EEPROMarray. If an error is found, the check-sum LED remains lit (it’s turned onduring a download and flickers duringthe checksum testing at powerup).

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

find that the professional V.3 handlesmy needs without generating hugeprogram files and loading too manysupport files into the end user’s Win-dows directory like the new versions do.

Photo 2 shows the program in ac-tion. The first time the 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 Celeritousweb site). Although you can still getthe AM9513, it has been discontinuedso its databook is no longer available.However, the AM9513 is similar tothe CTS part so the CTS datasheet can

be used for configura-tion purposes.

The first stage ofsetup is to initialize thedevice by putting it into8-bit mode and to preparethe five counter/timersfor loading. Becausethis process is done bythe PIC firmware, youneedn’t be concernedwith it. 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 the frame atthe right in Photo 2) toselect binary/BCD divi-sion ratios for the scaler,select an Fout source,and so on. Becausethere are two ’9513devices in this project,there are buttons to

switch between the two Master Moderegisters. Press the “save MM configu-ration” button when you are finished.

Certain bits of the Master Moderegister must be set properly for the PICfirmware to work. The host PC pro-gram doesn’t allow access to these bits.

Last, configure as many of the ninecounter/timer modules as necessary.Even though there are 10 modules inthe two ’9513 devices, there’s onlyenough room in the ’16F84’s dataEEPROM for nine module’s worth ofparameters.

The output buffers are in a quadconfiguration, but I only wired eightof the timers to output buffers. Mod-ule nine can only be used to feed an-other timer module.

To complete a counter/timer con-figuration, select a module from thepull-down menu. Notice that all of theselections are grayed out until theselected module’s configuration 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Modes that perform a divide-by-n, generate 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 mode 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 window. The range is0–9999 in BCD and 65536 inBinary mode. Certain modes alsorequire you to place a count inthe Hold Register window.

Next, choose the output mode.Only High TC pulse and TC-toggledare useful in this design. High TCproduces a pulse (width = clock) ateach terminal count. The TC-toggledmode changes the state of the outputpin at each terminal count, whichproduces either a square wave or a

PWM waveform, depending on themode you have chosen. At powerup,all output flip-flops are reset, so thesense of the PWM waveforms 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 “Time per singlecount” window for timing calcula-tions.

After the Master Mode registers areset up, and all necessary counter/timermodules configured, the data can be

Figure 3 —To work in a noisyenvironment with long inter-connecting cables, I used afancier I/O scheme than justTTL-compatible gates.

Gate 1Gate 2Gate 3Gate 4Gate 5

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

Gate 6Gate 7Gate 8Gate 9

Out 6Out 7Out 8Out 960/120 HzEXT Gate 1EXT Gate 2

Gate jumper array

Page 21: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

downloaded to the PIC by clicking onthat menu item. This process takes afew seconds during which the check-sum LED will light. If this light stayson after the download, then there wasa problem with the data transfer.

Test the unit by selecting the “Load9513 Timers” menu item or poweringthe unit off and on again. During anypowerup, the checksum light flickersbriefly if all’s well or remains lit if thedata EEPROM is corrupted.

Although the configuration andtiming parameters were loaded intothe PIC’s nonvolatile EEPROM, thedata displayed by the host PC programis only loaded into RAM and will belost when the program is exited.

I recommend saving this setup to adisk file via the File Save menu. Dif-ferent file names would enable you tostore various configurations.

WRAP-UPIt occurred to me that other periph-

eral devices may need to be config-ured in a particular way at powerup toperform useful functions without

SOFTWAREThe source code for this article isavailable for download via theCircuit Cellar web site The code isalso available for download atwww.bmillier.chem.dal.ca.

Brian Millier has worked as an instru-mentation engineer for the last 17years in the chemistry department ofDalhousie University, Halifax, NS,Canada. He also operates ComputerInterface Consultants. You may reachhim at [email protected].

SOURCESCTS9513-2Celeritous Technical Services Corp.(800) 687-6510(806) 783-0904Fax: (806) 783-0905www.celeritous.com

PIC16F84Microchip Technology, Inc.(800) 437-2767(602) 786-7200Fax: (602) 899-9210www.microchip.com

Programmed PIC16F84 ............. $15Brian Millier31 Three Brooks Dr.Hubley, NSCanada B3Z 1A3

further computer control. The flash-memory–based PIC16F84 would prob-ably serve this function well.

The 8253/8254 triple timer, whichis quite inexpensive because it wasdesigned into early IBM PCs andclones, would be another good option.CTS also makes a higher-speed ver-sion of this device for about $7.

Another candidate might be Telco’scross-point switch ICs. For example,the PIC would set up a complexswitching arrangement (which doesn’tchange frequently) PIC at powerupbut easily reconfigured using a serialdata link.

With the various technologiesavailable today, there’s certainly noshortage of choices and options forprojects like this one. I

Page 22: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

30 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 OEMs whose pri-mary business doesn’t

include designing modems. Fortu-nately, modem test standards TSB 37-A and TSB 38 provide consistent anduniform criteria to compare the per-formance of modems. Draft digitalstandards 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-mation on the statistics of the TSB37-A/PN 3857 network models and anoutline of the 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 well-designed modem product. OEMs shouldexpect their modem vendors to followa comprehensive testing program thatincludes all three types of testing.

FOR EXAMPLE,Your latest assignment is to add an

embedded voiceband modem to yourcompany’s nifty hand-held PersonalPeppy Puppy (PPP) 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 availability,attractive 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 connect at speeds between 38,666and 46,666 bps at different times of theday, probably depending on unknow-able random phenomena in the tele-phone network and your ISP. Besides,modem speed isn’t important becausethe Internet is pretty slow anyway.

You recommend two vendors, pur-chasing negotiates a deal, and youstart your design. The advertising slo-gan, “Put more bark in your PeppyPuppy,” becomes the company’s rally-ing cry. You enter the beta phase twoweeks ahead of schedule. You’re a hero.

That’s when all hell breaks loose.Every beta site north of the Rio Alphaand west of the Chappanoes reportsconnection failure rates exceeding25%. The CEO wants to talk to you.How did you select those modemvendors, anyway?

You wake up in a cold sweat. It’sthat same old nightmare.

ROLE OF MODEM TESTINGModem testing is the activity every-

one loves to hate. But if you’re goingto avoid the Peppy Puppy nightmares,you’d better do your homework.

Modems are complicated and thenetworks they run on have complica-tions of their own. Even Murphy hasno idea of how many things can gowrong, but your customers will findout soon enough if you’re not diligent.

You have no choice but to designyour products as well as you can andthen test the heck out of them.

Boring standards such as V.90 andV.34 dictate the basic requirements ofa modem design. But conforming tothose 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 that the design isworthy of production.

Making Sure Your Modem CanCommunicate

Page 23: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Several levels of re-quirements must be met.Your modem must prop-erly interwork with everymodem already on themarket. Performancemust be as good as theexisting modems. And,your modem must 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 its modems usingtest procedure A and if Company Ytests its modems using test procedureB, how will the OEM judge whethermodem X is better than modem Y?

TESTING STANDARDSEnter testing standards. The Tele-

communications Industry Association(TIA) has worked for several years toevolve a rational set of modem testprocedures. The latest official testdocuments were published in 1994,and an update is in the works.

These documents introduced theconcept of network coverage. Whenengineers use the models and proce-dures defined in these documents, theresults are straight-up comparisons ofa given modem against any others.

After the testing in simulated envi-ronments is finished, there are stillthose pesky situations that come upwhen a new product ventures into thefield. Of course, there are no standardsfor testing at this level, but an OEMwould do well to have assurance fromthe vendor that the modem has beensuccessful in a wide range of real-world environments.

Once reports of field-related prob-lems begin to come in, the modemvendor must have the know-how tounderstand them and make the 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 successfullyinterwork with the big-name modems.

I recall the time my company’sV.32bis modems experienced problemsat a certain ISP. The ISP was usingmodems supplied by a Well-KnownModem Company (WKMC). Our call-mode modems couldn’t connect withthe answer-mode WKMC modems andI was assigned to solve the problem.

I discovered that WKMC’s modemhad a subtle but definite mistake inits training sequence. Usually theerror wouldn’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 little mistake inthe training sequence. He referred meto a junior engineer who had writtenthat section of code. The junior engi-neer and I agreed that there was a prob-lem, and it was my understandingthat he would work on it.

This was too simple for manage-ment to comprehend though, and myVP soon called me in to ask what wasgoing on. He had received a phone callfrom the VP of engineering at WKMC.To better explain the situation, wescheduled a conference call involvingmy VP, WKMC’s VP, and myself.

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

wrong with his modems.Certainly he wasn’t anx-ious to upgrade the thou-sands of modems thatWKMC had in the field.

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

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

INTEROPERABILITYA walk down the aisles of your

favorite electronics superstore willillustrate that a large number of par-ticipants have entered the supply sideof the voiceband modem market.

If you design a new modem, one ofyour steps in qualifying the design is totake your company’s credit card, visitsaid electronics superstore, and buy oneof every modem on the shelf. Then, setup interoperability tests of your modemwith 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 with modem technol-ogy. Traditionally, modem perfor-mance was expressed as a curveshowing error rate as a function ofreceived signal-to-noise ratio.

Modem A was better than modemB if modem A achieved a given errorrate with a lower signal-to-noise ratiothan that required by Modem B. Be-cause error control has come to be anintegral part of their design, virtuallyall modems now perform error free.So much for error-rate comparison.

Current standards define severalmeasures of performance, one of whichis throughput. Throughput is the rateat which user data flows from the inter-face of the transmitting modem to theinterface of the receiving modem.

Figure 2— There are twostages of D/A conversionbetween the server and theclient, which means that PCMconnection is not possible.

Digitalnetwork

Digitalnetwork

Analogswitch

CO

DE

C

HybridLocalloop

Clientmodem

Servermodem

CO

DE

C

Hybrid

CO

DE

C

Hybrid

Digitalnetwork

Digitalnetwork

Digitalswitch

CO

DE

C

HybridLocalloop

Analogimpairments

Digitalimpairments

Clientmodem

Servermodem

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

Page 24: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Modems achieve error-free datatransmission by gathering user datainto blocks encoded so an erroredblock can be detected by the receivingmodem. The receiving modem thenrequests a retransmission.

The detection and retransmissioneliminates most errors, but only bytrading off throughput. All other things

being equal, modem A is better thanmodem B if it has higher throughput.

CONNECTIVITYThe meaning of connectivity has

also evolved with advances in modemtechnology. Today’s modems nearlyalways connect, thanks to their multi-mode structure. Typical modems can

switch personalities 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 between theserver modem at an ISP and a clientmodem can go through several stagesof digital networks and switches.

Sometimes, a DLC even extendsthe digital network partway from thecentral office to the subscriber’sneighborhood. If the whole conglom-eration, starting with the server mo-dem, is digital up to a single CODECwith analog thereafter to the clientmodem, then a PCM connection ispossible. Figure 1 illustrates a PCM-capable connection.

Some network configurations con-tain more than one D/A–A/D stage, asshown in Figure 2. When this occurs,the conditions that permit PCM op-erations are lost, and the modemsmust fall back to V.34 mode.

During their handshake, modemsdetermine whether a PCM connectionis possible. If it is possible, the mo-

Table 1—Voice-band modem technology has advanced from 300 bps in the 1960s to modems that approach56 kbps today (during which time the North American telephone network has evolved from 100% analog to nearly100% 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

dem determines how to cope with anyRBS and digital/analog pads that maybe 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 fall back to V.34 with itsattendant reduction in speed.

HISTORY OF STANDARDSThe TIA/EIA developed several

North American testing standards tohelp compare modems. Table 1 pre-sents a chronology of North Americanmodem test standards, and the “Glos-sary” sidebar contains TIA definitionsfor some key terms.

Modem testing began to be standard-ized in 1989 when the EIA/TIA pub-lished the 496-A standard. This standarddefined a simple telephone networkmodel that included a set of six testchannels representative of end office–to–end office telephone connections.

This connection model includedthe effects of amplitude, delay distor-tion, as well as white noise, and wasadequate for testing modems withspeeds up to 2400 bps and modemssuch as V.22bis. Equipment based onthe standard was used for testing V.32modems, but users were often con-fronted with apples-to-oranges com-parisons when comparing test resultsbecause there was no standard fortesting echo-canceled modems.

The deficiencies in EIA/TIA-496were addressed in TSB 37-A, whichwas published in 1992. TSB 37-A built

on EIA/TIA-496-A but augmented thenumber of test channels from 6 to 16and added a laundry list 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 two-wire paths

that connect the user to the telephonecompany’s central office) and theeffect of the input impedance of localloops. This model was good for evalu-ating the performance of modemsfrom an error-rate standpoint.

Meanwhile, more and more mo-dems began to include error control,so the TSB 37-A model was only use-ful when error control was disabled.Disabling error control lightened theload on the processors that imple-mented the modem, which reducedthe utility of the test. It was time foranother upgrade in testing standards.

The TIA introduced a new ap-proach to modem testing in 1994 withthe TSB 37-A and TSB 38 standards.TSB 37-A defined various telephone-network subsystems that could becombined with LOOs to simulatemodem operation over a wide varietyof typical connections.

TSB 37-A brought the recipe for thetelephone network model to the test-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

3000

2500

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 whereasModem L performs at about 3300 cps, and Modem 3 at a throughput of less than 3000 cps. Thus the chart gives thecustomer an objective means to compare the throughput of these three modems.

Page 26: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

test procedures designed to character-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 presenting the results” [1].

TSB 37-A and TSB 38 defined net-work coverage. Test results now indi-cate the percentage of the telephonenetwork over which 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 PCM modems were intro-duced. Besides creating an upheaval inthe national and international stan-

dards bodies, these modems createdanother testing dilemma—TSB 37-Asaid nothing about digital networks. Itwas time for yet another upgrade.

DRAFT PN 3857 AND PN 3856The simulation model defined in

TSB 37-A and in its update, PN 3857,employs the concept of network cov-erage. Defining a model that coversall possible situations is impossible,so the model sets up a large numberof possible combinations along withan 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 ofcombinations of digital/analog network

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 remote DLC terminal with higher qualityindividual two-wire 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 weighting factor applied to componentsin the PN 5837 network model

PCM—Pulse-coded modulation is a modulation/coding scheme used withinnetworks for digital transmission of voiceband signals. All PCM systemsin the U.S. today digitally encode a 4-kHz–wide analog signal into a64-kbps digital bitstream using a sampling rate of 8 kHz. A/D and D/Aconverters are commonly implemented in pairs in a CODEC (COder-DECoder). These CODECs use µ-law companding (compression/expan-sion) in North America as specified in ITU-T Recommendation G.711 toeffectively provide a dynamic range equivalent to that of a linear 12-bitcoding system, but using a sample word size of only 8 bits, which resultsin 256 possible signal levels

PCM link—a digital link employing PCM or ADPCM encoding that termi-nates in a four-wire analog interface

PCM modem—a modem, as specified in the ITU-T V.90 Recommendation,whose line signal at the sample rate is one of the levels generated by aPCM CODEC

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 that when the least significant bit is used (i.e., robbed),the signal is effectively a seven-bit value for that sample, with the leastsignificant eighth bit effectively becoming a random value. The resultingoutput appears as the original signal with a low-level impulse noise hit.RBS may be used in DLC systems.

Page 27: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

components and the impairments thatoften accompany each component.

Digital impairments include digitalpads and various forms of RBS. Analogimpairments include analog pads, theeffects of various lengths of 22-, 24-,and 26-AWG twisted wire pairs,bridged taps, loading coils, Gaussiannoise, echo, power-line induced noise,and nonlinear distortion. The modelassigns an LOO to each component.

PN 3856 defines many tests thatapply to the PN 3857 model. A typicaltest computes the throughput for agiven configuration along with theLOO for that test case.

Performing tests in a suite yields alist of throughput values and correspond-ing LOOs. Displaying throughput as afunction of cumulative LOO defines anetwork coverage curve that character-izes a given modem. The goal is toachieve the largest throughput over themaximum percentage of the network.

REPORTING THE RESULTSThroughput test results are often

presented as a curve displaying the

throughput achieved as a function ofthe percentage of coverage given bythe reference network. Figure 3 showsthroughput in characters per second(cps) for three different modems.

For about 5% of the network, 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 modems L and 3 in this test.

HANGING UPDesigning voiceband modems has

become quite a process. The sophisti-cated DSP algorithms coupled withthe power of today’s embedded pro-cessors can lead to software-baseddesigns. Testing is a key componentof the design process although testingitself can never improve a bad design.

Arthur J Carlson holds a Ph.D. inElectrical Engineering from the Uni-versity of Iowa. He spent the first 12years of his career on the faculty ofthe University of Missouri, Columbia.He then relocated to Silicon Valleywhere he has worked in high-speedmodem design for 20 years. Art is asenior scientist at AltoCom in Moun-tain View, CA. You may reach him [email protected].

Standardized testing provides OEMswith consistent and uniform criteriafor comparing modem performancelevels and for avoiding those peskyPeppy Puppy problems. I

REFERENCE

[1] TIA/EIA TSB38, “Testing Proce-dure for Evaluation of Two-Wire4-Kilohertz Voiceband DuplexModems,” Introduction.

RESOURCE

TIA standards info,www.tiaonline.org

Page 28: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

CIRCUIT CELLAR OCTOBER 199938

NPC

www.circuitcellar.com

PCNouveauedited 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 BOARDThe 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 GraphicsProcessor (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 ofvideo RAM optimized for 3D rendering. Also available are twoUltra-DMA 33 IDE interfaces, a pair of USB ports, dual serial I/Owith 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC 39

NPC

www.circuitcellar.com

PCNouveau

SINGLE-BOARD COMPUTERThe 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, NT, and CE, support formost leading RTOSs is also available.

Pricing for the CoreModule/P5e starts at $729 in OEMquantities of 100.

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

HIGH-SPEED PARALLEL DSP MODULEThe 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. Internalresources 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-bitinterface. 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

EPC

CIRCUIT CELLAR OCTOBER 199940 www.circuitcellar.com

Mal Raddalgoda

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

With 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 Windows CEmeets the technical requirements of theproject. No 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 Windows CE tech-nologies with the established RTOSs showsjust 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. On 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 OEMdistributors 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-

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

Page 31: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC

EPC

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 atypical 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. Within 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 includesMIPS, 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 Windows 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 RTOSvendors sell directly to vendors or engi-neers engaged in development projectsand provide direct system software andsupport services for their customers. Whenengineers 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’sno 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 ofthe 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 seethree different architectures. The important thing tokeep in mind is that overall system reliabilitydepends on OS architecture—the less code runningin the kernel, the better.

Hardware

Real-timeexecutive

kernel

File systems I/O managers

Application Application

Other...Devicedrivers

Networkdrivers

Graphicsdrivers

Graphicssubsystems

Traditional RTOS architecture

Hardware

Monolithickernel

File systems I/O managers

Application Application

Other...Devicedrivers

Networkdrivers

Graphicsdrivers

Graphicssubsystems

Windows CE architecture

Memoryprotected

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 arethe key criteria for se-lecting an RTOS? Develop-ers are looking at real-timecapabilities, development-toolquality, and footprint size. A fa-miliar API was considerably lessimportant (source: Venture Develop-ment Corp.).

Page 32: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

CIRCUIT CELLAR OCTOBER 199942 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 systemsrather 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 ofJava), 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. Not 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 ofVisual 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 Windows-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 commerciallyavailable 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 ofQNX’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 TOOLSThe availability of rich and compre-

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

Page 33: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC

EPC

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. Windows 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, QNX 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 ofthe 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 technologyanalyst for QNX Software Systems Ltd.,concentrating on the North American mar-ket. Mal has over 10 years of experience

SOURCESWindows 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 andtelecommunications indus-try and has held positions inproduct development, productmanagement, and marketing. He isalso a member of the Embedded Soft-ware Association (ESOFTA). You mayreach 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, Windows 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. Or, willengineers 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC

RPC

45www.circuitcellar.com

Figure 1—Here’s what an airplane that isfighting crosswind looks like. The official termfor this is “crabbing” because, in its extremeform, it looks like a crab walking sideways.

Real-Time PC

Ingo Cyliax

Where 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 hadto compensate his data-acquisition system for the effects of crosswinds tomake sure the ground-mapping camera shoots straight.

be angled with respect to the ground trackthe flight was intended to cover. Withsevere 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 haveto 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

RPC

CIRCUIT CELLAR OCTOBER 199946 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. We 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. Oncewe 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 givesthe 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.

PROJECTThis 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 weare turning into the wind, the pictures are nolonger aligned to the north-south meridian,which is what we would like to see.

Crosswind Course over ground

Image frames

Page 36: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC

RPC

47www.circuitcellar.com

formats in previous articles. If you remem-ber, the GPRMC 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. Where 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 fielddirectly. 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 thesecompasses less expensive now.

I wrote about Precision Navigation’sVector 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 makeit hard to interface with our system.

Precision Navigation also makes aNMEA-based compass module—theTCM2. 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, HC is theprefix for a magnetic compass.

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

An example of anNMEA message from thismodule is:

$HCHDM,182.3,M*21<cr><lf>

This message indicates a heading of182.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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

RPC

CIRCUIT CELLAR OCTOBER 199948 www.circuitcellar.com

Photo 2—The serial servo controller is used to interfaceradio 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 itselfor 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 between10 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 ofabout (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. We 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 andyou’ll see that the code (Tcl) tomake this subsystem work ispretty simple. The loop in List-ing 1 waits for messages on afile description $magchan.This is a serial port, on whichthe magnetic compass sits.

The compass outputsNMEA messages. NMEA mes-sages are line oriented so wecan use the Tcl gets function.In its default behavior, thisfunction reads from the inputchannel until it encounters anend of line, in our case<cr><lf>. The line is returnedin the variable line.

The next function isnmea_valid. This functionchecks to make sure that eachsentence 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 split 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,$HCHDM. 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, thisloop 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 (puts). Here again, thefile descriptor $srvchan 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—TheTCM2 compass

module from PrecisionNavigation has it all, in-

cluding NMEA interface andmore interface options than

you’ll ever use.

Page 38: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC

RPC

49www.circuitcellar.com

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

set mag_decl 2.9## main loop, wait for new heading and update#while [gets $magchan line] != -1

## check NMEA message format and checksum#if [nmea_valid $line] != 0

continue## split sentence into fields#set fields [split $line ',']if [lindex $fields 0] != "\$HCHDM"

continueset hdg [lindex $fields 1]set off [expr ($hdg - $mag_decl) + 90]set pos [expr int (($off * 256) / 90) % 256]## output the servo message#puts $srvchan [binary format "ccc" 255 0 $pos]

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-methoddesign tools for high-assurance systems anddevelops 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

APC

CIRCUIT CELLAR OCTOBER 199950 www.circuitcellar.com

Applied PCs

Fred Eady

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

Nothing, absolutely nothing, is free.No free lunch. No 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 ofit. What’s the catch? Is this another scam?

As it turns out, there is a “catch.” Youcan download the latest version of Go-Ahead WebServer 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 ofthe box with various flavors of Unix, QNX,VxWorks 5.3.1, Windows NT, Windows95 with Service Pack 2, Windows 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 webserver. There arenumerous directories under webserver,including a subdirectory for each of thepublicly ported GoAhead WebServeroperating environments.

A Makefile is included in theindividual OS directories for each OScompiler. In addition to the Makefile,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 CircuitCellar 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

APC

OCTOBER 1999 EMBEDDEDPC 51www.circuitcellar.com

Photo 1—This whole GoAhead webserver thing is a sleeper until you getto this point. You can dig through theHTML files for answers until you’reblue. The answer is to just install it!

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

specified, the default language isJavaScript.

It’s recommended that the languagebe specified in the <HEAD></HEAD>section of your page, as in:

<% language=javascript %>

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:

<h1>You are reading <% write("Circuit Cellar APC"); %></h1>

will output “Circuit Cellar APC” in place ofthe ASP-delimited field.

I won’t write a dissertation on ASP inthis column, but here’s a quickie on justhow the ASP process executes. When auser’s browser requests an ASP document,

the default URL handlerdetermines if the page isan ASP document byexamining the file extension. If.asp 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. Webcomp 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 therelevant 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 *.htm 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 SERVERTo 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 ofonline documentation the web site keptalluding to. When 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 severalfeatures, 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 .asp 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-orientedJavaScript API set.

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

To build and run the GoAhead WebServer, change to the relevantoperating system directory and use make to initiate the build.Some of the make or batch files may need to be modified for theconfiguration of your system or the target system. See the "Con-figuring the GoAhead WebServer" section.

For VxWorks: cd VXW486 makeLoad webs.o onto the target system and use standard VxWorks

procedures to load the program into memory and execute it.

For Windows NT: cd WIN nmake /f webs.mak webs

To stop the web server, right click on the taskbar icon for the GoAhead WebServer and select "Close".

Page 41: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

APC

CIRCUIT CELLAR OCTOBER 199952 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 of10.10.0.1 to the initial test web-servermothership. Finally, I laid in Bill’s C++ V.5,Netscape Communicator 4.5, anddownloaded GoAhead Web-Server V.2.0.

Before running the unzip process, Iopened the zip file with WinZip andlooked over the package. I wasoverwhelmed with the amount of .htmfiles 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 ofcornering 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 README files and the

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

// Test Javascript binding for ASP. This will be invoked when// "aspTest" is embedded in an ASP page. See web/asp.asp for// usage. Set browser to "localhost/asp.asp" to test.

static int aspTest(int eid, webs_t wp, int argc, char_t **argv)char_t *name, *address;

if (ejArgs(argc, argv, T("%s %s"), &name, &address) < 2) websError(wp, 400, T("Insufficient args\n")); return -1;return websWrite(wp, T("Name: %s, Address %s"), name, address);

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

The README.TXT file was most helpful.The first paragraph apologized for theseeming lack of documentation andreminded me that this was a beta version.I was assured that full documentationwould be provided with the full release ofV.2.0. I was then instructed to consult thehome page (//localhost/home.asp)for access to the beta documentation.

As I read further into the README 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 blurbyou 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 webserver directory. Just like

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

It wasn’t difficult to determinethat WIN was the directory I needed.The README text in Listing 1 pointedto it, and WIN stood out amongother subdirectories such as Linuxand Qnx4. 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 Web-

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 Host file ofanother workstation to map GoAhead to10.10.0.1. On the same workstation Istarted Netscape and entered http://goahead 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 EmbeddedJavaScript 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 WebServer is towelcome any type of customization.

There’s a section that describes somebasic GoAhead WebServer 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.

main.c and socket.c in the WINdirectory 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 frommain.c 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 getthis baby with Pentium power, too.

Page 42: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

CIRCUIT CELLAR OCTOBER 199954 www.circuitcellar.com

home.asp 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 ofthe product. So, download a copy andinstall it, and I’ll leave the reading to you.

THE HARD(WARE) PARTTheir 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 findevery piece of embedded hardware in theFlorida Room and attempt to install theserver and serve some pages.

RIDING A SNAKEThe 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 andfloppy interfaces, keyboard and mouseports, an SVGA adapter, and bunches ofother 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 NT. 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 anddecided 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 NT.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 ofelimination. 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

OCTOBER 1999 EMBEDDEDPC 55www.circuitcellar.com

Fred Eady has over 20 years’ experience asa systems engineer. He has worked withcomputers and communication systems largeand small, simple and complex. His forte isembedded-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 ofRAM. 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 aninexpensive Tempustech VMAX SBC301.

The VMAX board is a ‘486SXLC runningat 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 SMC8416Ethernet adapter, the VIPer spinning diskset, and the Tempustech ISA backplane.

During the Win 95 WebServer installI 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 WD 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 isa 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 givesyou a head start on making a difference inthe embedded control world. APC.EPC

SOURCESWindows NTMicrosoft Corp.(206) 882-8080Fax: (206) 936-7329www.microsoft.com

GoAhead WebServerGoAhead Software, Inc.(425) 453-1900Fax: (425) 637-1117www.goahead.com

VIPer806Teknor Microsystems, Inc.(514) 437-5682Fax: (514) 437-8053www.teknor.com

VMAXTempustech(800) 634-0701(941) 634-2424Fax: (941) 643-4981www.tempustech.com

Page 44: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Figure 1— The start switch (S1) that activates the LEDs isconnected 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 immediatevisual 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 way to learn the basics.

The assembly-language firmwaredescribed in this article demonstratesbasic PWM techniques, timer opera-tion, and general I/O manipulation.The information presented here willenable you to tackle 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 high-brightness LEDs alert on-coming traffic to your presence.

This device is built aroundMicrochip’s PIC16LC54A. Thismicrocontroller includes an8-bit data path, 12-bit instruc-tions, an 8-bit timer, 512 bytesof ROM, and 25 bytes of RAM.

As for power, typically, coincell battery–operated devicesand LEDs aren’t a good match.A current-hungry LED candrain a battery in mere hours.Having more than one LED onat any one time drains the bat-tery even faster. Unless you use

some kind of intelligent power-con-servation technique, your battery billis going to be quite high.

Several power-conservation tech-niques can be used in this design,including:

• lowering the LEDs’ forward cur-rent—this extends battery life butat the cost of the wearer’s safety

• enabling one LED at a time, cyclingthrough all eight—this helps pre-serve the battery, but the visualpattern of the LEDs is limited, ifnot boring

It’s more visually appealing if therewere two (or more) LEDs on at anygiven time. This pattern can be ac-complished by turning on LED A for ashort time while B is off, and thenturning A off and B on.

If the cycle repeats fast enough, thehuman eye can’t detect the flashing.So, it appears that both LEDs are on,granted at a slightly reduced light-level output.

That’s the technique employed inthis firmware. 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 well 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, maybe a magnifying glass.

Programming in Assembly

Page 45: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

CIRCUIT OVERVIEWThe circuit shown in Figure 1

comprises a microcontroller (U1,PIC16LC54A), eight LEDs, oneswitch, one battery, and a sprin-kling of resistors and capacitors.

When you press and releasethe switch, the PIC’s programcounter is reset to the beginningof code space and the lightingsequence begins. To turn theLEDs off, press and release thebutton again.

Power is supplied to the micro-controller and LEDs through the bat-tery (B1), which is a standard 20-mm3-V coin cell. Resistor R10 and capaci-tor C1 generate an RC clock input forthe PIC. The operating frequency is anominal 256 kHz, which means thatthe instruction rate inside the PIC is:

1256 kHz

× 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.

Note that, besides the LEDs, all ofthe components are of the surface-mount variety. If you decide to getcreative and put artwork on the oppo-site side of the PCB, through-holecomponents would get in the way.

FIRMWAREThis device is a useful educational

tool because when you experiment withthe firmware’s assembly code, you getimmediate feedback. Did you programit right? You’ll know right away.

Everything begins with a low-to-high pulse on *MCLR. Once thispulse is generated, it resets the pro-

gram counter of the PIC to the begin-ning of code space.

The PIC initializes all softwarevariables, configures all I/O, and setsup timer0 for internal clocking and aprescaler value of 4, so every time theinternal instruction clock incrementsfour times, the timer increments by 1.Remember that the PIC is executinginstructions every 15.625 µs.

Next, the PIC inverts Power_cycle.This variable decides whether to be-gin flashing the LEDs or put the PICinto Sleep mode. If Power_cycle is a1, the PIC begins flashing the LEDs. Ifit’s a 0, the PIC goes to sleep.

Remember, software variablesdon’t lose their state in Sleep mode.The only time they lose their state iswhen power is removed. By invertingPower_cycle every time someonepresses the momentary button, thedevice effectively turns on and offwith every push.

The PIC loads timer0 with a valueequal to 7 ms. Note that the timercounts up and is considered to be atits terminal count when it rolls from0xFF to 0x00.

Normally when a timer rolls, aninterrupt is generated, causing aninterrupt handler to handle the event.

Because the ’16LC54A doesn’thave interrupt capability, thecounter 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 we can discuss whathappens when the 7-ms counterrolls, we need to take a look athow the LEDs are enabled. First,let’s define a rule that restricts

how the firmware operates.Because the battery is small and

can’t provide a lot of instantaneouscurrent, only one LED can be enabledat any given time. So, if you want twoLEDs on at once, you’ll have to findanother way to do it.

Let’s assume that you want twoLEDs (A and B) to appear to be on atthe same time. The device does this isby turning LED A on and LED B offfor a short period of time. 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 perceivethat the diodes are actually turning onand off. Although their brightness isreduced, both LEDs will appear to beon at the same time.

The LEDs are turned on and offevery 14 ms (71.5-Hz rate). That ex-plains the reason for the 7-ms counter.It equals half of the on/off period.

If you only want one of the LEDsto be lit, you would still need to usethe above steps except that LED Bwould be absent. LED A is lit for ashort amount of time and then it isshut off for the same amount of time.

Table 1— Here’s theorder in which the LEDsare enabled for each ofthe eight patterns.When Pattern 8 iscompleted, the cyclerestarts 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 whileLED 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Figure 3— Seeing the order in which the LEDs are lit forthe first three patterns makes it easier to extract theformulas to describe each LED pattern.

the single LED rotates one LED clock-wise and the pattern repeats.

The eight possible LED patternsare shown in Table 1. Note that eachsubpattern is enabled for 14 ms × 8,which equals 112 ms.

Now, we need to find a way tocode that pattern without explicitlycoding each step. Although there’s noreason why a brute-force method ofcoding the pattern wouldn’t work, it’sjust not very challenging. There has tobe an overlying pattern that we canuse to generate each subpattern.

To find this overlying pattern, takean 8-bit register and put an X in thebit location when you want an LED toturn on. If you start with Pattern 1,you’ll end up with Figure 3. The LEDsare numbered from 1 to 8, and theregisters are numbered 0 to 7.

Figure 3 should help you figure outthe rules for determining which diodesshould light. Note the cells with thebold blue X in them. This pattern isnothing more than a circular left shift.

Describing the cells with the non-bold blue Xs is only a little more com-plicated. It’s a circular right shift with

a twist. The twist is that every ninthshift is a left instead of right. Now, byinclusive-ORing these two shift pat-terns together, you can generate thepatterns you want.

This circular right shift techniqueis much easier than trying to code allthe individual subpattern states. Thetwo registers that contain the shiftpatterns are called Reg_chain1 andReg_chain2.

Once the 14-ms cycle time is de-fined and the patterns described, weneed to determine which LEDs will beon and off within the subpatterns.This dilemma is resolved by takingthe first subpattern in each patternand defining the A LEDs to be the bold-X LEDs plus X + 1, X + 2, and X + 3.Each of the remaining four LEDs playsthe part of the B LED.

If you try to assign a fixed pattern tothe LEDs (e.g., LEDs 1–4 are A, and 5–8 are B), it will result in some sub-patterns having both desired LEDs ineither the A or the B group. The vari-able LED_pattern contains the A or Bdesgination information and is used bylogical ANDing LED_pattern with

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 shows the LED-enable wave-forms and the on-off periods.

Now, let’s define a pattern. Eachpattern starts as a single lighted LEDand then travels in pairs around thecircuit board until reaching the oppo-site side where it ends in a single LEDand then travels back. At that point,

Page 47: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

CIRCUIT CELLAR ®www.circuitcellar.com

the inclusive OR of the Reg_chain1and Reg_chain2 variables.

By coding the LED pattern in thismanner, substantial code compressionis achieved, which leaves valuablecode space to handle other tasks.

By the way, if you wish to modifythis firmware, you need a suite oftools available from Microchip. Mostof the PIC tools are free, including theassembler and simulator, and can bedownloaded the Microchip web site.

ASSEMBLYBegin by programming the PIC

with the source and programmingfiles, which are available via the Cir-cuit Cellar web site. Next, solder thePIC to the circuit board and note thelocation of pin 1.

Attach the switch (S1) and solderthe 10-kΩ resistors (R9 and R10) andthe 300-pF capacitor (C1). Now solderthe eight 36-Ω resistors and the coincell battery holder (B1). And that 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 while you insert the others.

Before you insert each LED, notethe location of pin 1 (or anode). Pin 1,(identified by the longer of the twoleads) 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 thePIC’s clock signal (pin 16 of U1) with an oscilloscope should result in awaveform like the one shown here.

1/27/99 8:47:32 PI

2 µs/div 0.4 V/div 0.113 VDC 1.73 Vp-p 0.571 Vrms –62.7 dB

dV = 0.0252 V dt = 5 µs f = 200 kHz

Jon Varteresian owns and operates JVEnterprises, which offers educationalelectronic kits and provides con-sulting services. Jon specializes indeep embedded control of wirelesstransceivers and user interfacemanagement. You may reach him [email protected].

SOURCESProject componentsJV Enterprises(978) 928-5655jventerprises.home.att.net

Digi-Key Corp.(800) 344-4539(218) 681-6674Fax: (218) 681-3380www.digi-key.com

All Electronics(800) 826-5432(818) 904-0524Fax: (818) 781-2653www.allelectronics.com

Jameco(800) 536-4316(415) 592-8097Fax: (415) 592-2503www.jameco.com

DID YOU DO IT RIGHT?The last step is to

insert the coin cell bat-tery in the battery holderwith the positive termi-nal positioned up. Nowpress and release thereset button (S1).

If you’ve assembledeverything correctly, theLEDs will start to flash.If they don’t, check yourwork 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 simpleway to learn programming in assem-bly on a PIC. I

SOFTWAREAlong with a complete parts list,the source and programming filesfor this project can be downloadedfrom the Circuit Cellar web site.

Page 48: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

60 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 whenan industry association is

formed and yet another set of acronymsis spawned.

In 1994, the Infrared Data Associa-tion (IrDA) was formed by a group ofcompanies, including HP, IBM, andSharp. The goal of the association wasto promote the ubiquitous deploymentof infrared appliances that interoperatewith each other.

For this to happen,both the physical layerand protocols for com-munication needed to beestablished. Much to thecredit of the companiesin the IrDA, these speci-

Figure 1 —There are three majorlayers needed in a basic IrDAapplication—physical, protocol, andapplication. A basic IrDA linkrequires a reliable physical layer andIrLAP/IrLMP layers. What’s loadedon top of those layers is up to you.

fications were adopted and ratified inless than a year.

By 1995, laptop PCs and IrDA PCadapters that adhered to the standardmade their appearance and Microsoftreleased IrDA support for Windows 95.Since then, in fits and starts, IrDA hasbeen adopted in almost all laptops andis being used in consumer devices(e.g., digital cameras, cell phones, andpagers). However, the breadth of thetechnology and its applications hasleft even seasoned industry watchersand engineers a bit dazed and confused.

My goal here is to dispel some ofthe confusion and provide an overviewof IrDA technology. I want to focusspecifically on physical-layer imple-mentations, which will be the focusof Part 2 next month.

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 between PDAs and desktopPCs, cell phones, and IR watches.

For the IrDA’s goals to be reached,a number of key technical hurdlesneeded to be overcome. First of all,the physical-layer specification had tobe ratified. These specifications in-cluded wavelength, transmissionpower, communication 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Next, a robust reliable data com-munication protocol had to be estab-lished. The protocol needed to takeinto account the ad hoc nature of awireless connection as well as supportpoint-to-point connectivity and theability for devices to negotiate capa-bilities like data frame size and maxi-mum communication transfer rate.

And last, in order for devices tocommunicate, application layers forcommunication between 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 sectionsshown in Figure 1.

At the lowest level, the physicallayer specifies the physical character-istics of the infrared medium, the data-modulation scheme used, and thestructure of an IrDA frame. Generally,the physical layer comprises a UART,a modulator/demodulator ASIC, andan 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 to zero inverted(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 schemeshown in Figure 3 relies on a clock todrive the modulation engine. This clock(16XCLK) is set to 16× the communi-cation transfer rate.

For example, if communication at115.2 kbps is required, 16XCLK is set to:

16 × 115200 = 1.8432 MHz

A space or 0 TXD value is encodedas a single pulse (IRTX) of duration (3⁄16)of the bit time or:

1115200

× 316

= 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, which outlines a practi-cal microcomputer-based SIR physi-cal layer solution.

The key building blocks are 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] encodingscheme as described in Figure 3), andDallas’ 80C320 (8051 CPU derivate).

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 µs0.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 theirradiance specifications outlined in (b). b—Matching the transmission/receiver power of an IrDA optoelectronicpairing is critical. The IrDA protocol allows multiple devices to be “discovered,” so a device that transmits too muchenergy 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/cm2)Minimum irradiance <_ 115.2 kbps 4.0 — in angular range (µW/cm2)Minimum irradiance 115.2 kbps + 10.0 — in angular range (µW/cm2)Half-angle, degrees All ±15 —Receiver latency allowance (ms) All — 10

a)

b)

Page 50: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Listing 1, written in 8051 assemblylanguage, demonstrates how to set upboth the Dallas 80C320 as well as theHSDL 7001 to send out the character“h” repeatedly.

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 accommodate this situationby clearing the receive buffer aftersending 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 betweenthe send and receive channels. Duringtransmission, the sender sends out abyte to the responder device, whichcauses the 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 will most likely be corrupted.The trick is for the responder to holdon for 10 ms after receiving beforeattempting to send any data to thesender. In IrDA terminology, this timelag 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 (Dt), 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 Dt period works outto two data bits (Dt = 500 ns= 2 × 1⁄4 Mbps). During aspecific Dt, only one chipcan be a logical one.

Despite the relativesimplicity of the 4PPMmodulation scheme, build-ing a practical 4-Mbpshardware scheme is non-trivial. Simply put, the4-Mbps datastream is fast!In addition to a 4PPM

modulation engine, you need a serialcommunication controller that handlesDMA if you’re going to build a practi-cal 4-Mbps hardware scheme.

Figure 5 outlines a relatively low-cost 4-Mbps hardware scheme. Let’slook at the key modules for this solu-tion. The HP HSDL 1100 FIR trans-ceiver supports communication allthe way from 9600 bps to 4 Mbps.

The NS 87109 UIR controller en-compasses the 4PPM and RZI modula-tion schemes (supports 9600 bps to4 Mbps). It also functions as a serialcommunication controller, and handlesdata integrity, bit stuffing, and CRCcalculations (which, at 4 Mbps, aretoo complex to do in firmware).

The ’87109 also supports DMA,which is another critical performancefactor. Though a polled I/O approachcan be used to receive 4-Mbps data, itrequires too much CPU overhead.

Because effective communicationwith the ’87109 using regular polledI/O is usually not workable, I chose theNEC V850E/MS1 single-chip processor.It supports up to 128-KB internal flashmemory and up to 4 DMA channels, soit’s ideal for I/O-intensive applications.

PROTOCOL LAYERSOnce a stable physical-layer imple-

mentation is put in place, the nextstep 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, modified to take intoaccount the ad hoc nature of wirelessconnectivity.

The IrLAP layer controls discoveryof devices within 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 management protocol(IrLMP) layer, which allows the singleIrLAP channel to be shared acrossmultiple logical channels. This way, asingle IrDA device can support multiplefunctions (e.g., faxing, printing, andLAN access) through different logicalchannels while using the same physi-cal layer (a single IrLAP connection).IrLMP is like a switchbox that routesdata to and from the IrLAP layer.

INFORMATION ACCESS SERVICEBecause the IrDA protocol is in-

tended to be used with a variety ofappliances, we need a way to 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 the IAS databasethat indicates that it is acamera and includes infor-mation about an externaldevice that can connect toit. The first thing a connect-ing device does is send a“query IAS” command todetermine what the deviceis and what it can do.

Finally, on the protocollayer, is the tiny 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 internaltimer “times” seven of the CLK16X pulses before pulling IRTX high for three clockcycles 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 blocksare what’s required for a basic SIRphysical-layer implementation. You’llneed an IrDA-compliant optoelec-tronic device, an SIR encoder/decoder chip, and a microprocessorwith a built-in UART.

SIRencoder/decoder(endec)

IrDAcompliant

optoelectronicsUART/

microprocessor

IRRX RXD

IRTX TXD

CLK16X

Page 51: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

start:; Do some intialization before proceeding.

lcall Setup_HSDL7001 ; setup HSDL 7001lcall SetBaud115200 ; set data rate to 115.2 kbps

; Keep looping and sending out h's @ 115.2 kbps

doit: mov a, #68h ; send out an 'h'lcall PutByte ; call PutByte to send out datamov a,#ffh

waitsend: djnz a,waitsend ; delay a bit before continuingljmp doit ; continue looping

PutByte: ; sends byte out through UARTmov r1,a ; data is stored in the accumulatormov SBUF,r1 ; send the byte out

waitTI: jnb TI,waitTI ; wait till it's sent outclr TI

ret

SetBaud115200:;Program serial control registers & relevant timer registers; to enable required data rate.

mov SCON, #50hmov RCAP2H,#0FFhmov A,#RCAP2L_115200mov RCAP2L,A ;0DCH -9600 bps- #0FDh 115200 bpsmov T2CON, #34Hclr RIclr TImov IE,#0setb REN

; Select HSDL-7001 signaling rate - for 115.2 kbps, select:; A0 = 0 -> tied to P1.0; A1 = 0 -> tied to P1.1; A2 = 0 -> tied to P1.2;

clr P1.0clr P1.1clr P1.2ret

;Setup_HSDL7001 sets HSDL-7001 into the following operational mode:; CLKSEL -> Internal oscillator; PULSEMODE -> Set to 1.6-µs mode; POWERDN -> Set Low (powerdown not active)

Setup_HSDL7001: ;Test hardware has been configured as follows:; CLKSEL -> P1.3 LOW=> Internal Clock HI=> External 16XCLK; PULSEMOD -> P1.4 LOW=> 3/16 modulation HI=> 1.6-µs pulse mode; POWERDN -> P1.5 LOW=> Normal Operation HI=> Powered down;; POWERDN mode only deactivates internal analog oscillator block within HSDL-; 7001. If CLKSEL is set to high and external 16X clk is provided,; the chip should continue to work.

clr P1.3 ; CLKSEL = Internal oscillatorsetb P1.4 ; PULSEMODE = 16 usclr P1.5 ; POWERDN = normal moderet

Listing 1 —The code I used to implement a simple 115.2-kbps communication link uses the hardwareconfiguration from Figure 4 and programs the UART of the 80C320, sets up the 7001 for 115.2 kbps, andsends 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 which one chan-nel hogs the IrLAP/IrLMP channel. Ituses a credit transaction scheme tocontrol (or buy) access to the channel.

APPLICATION LAYERSAfter the physical and protocol

layers are built up, the next step is tobuild application support for thedevice(s) you want to communicatewith. I’ll just give a preliminary sum-mary of the application layers here.

Page 52: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

The main methods of exchanging datathrough an IR connection are IrCOMM,IrOBEX, and IrTRANP.

IrCOMM is intended for legacy-wiredserial or parallel port applications thatare to be converted to support IrDA.For instance, if you want to replacethe RS-232 wired connection betweena modem and a PC, you need to con-nect an IrDA adapter to your PC andbuild an IrDA modem adapter.

If the IrDA stack on your PC andmodem adapter contain the IrCOMMextensions, both your PC and modemcontinue to operate as if the RS-232cable was connected. You can continueto use the PC modem application as ifyou were using a virtual COM port.

If you install the Windows 95 IrDAdrivers, the IrDA protocol is exposedas virtual COM and LPT ports on yoursystem. The IrCOMM layer essentiallyopens up the IrDA protocol through aseries of communication API look-alikecommands, so changes to the 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 andconverting 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 NTTfor the Nagano Olympics enabled usersto beam their images onto a personalweb page via an IrDA kiosk. IrTRANP

Hari Ramachandran is the managingdirector and founder of Parallax Re-search, a design company focused onproviding IrDA solutions. He designedthe HP HSDL 7001 and HP HSDL 7000IrDA chips, and developed IrDA proto-col stack software for numerous com-panies and specific applications. Youmay reach him at [email protected].

Figure 4 —This design uses a Dallas 80C320,the HP HSDL 7001 (encoder/decoder), andHP HSDL 1001 (IrDA optoelectronics) and isall that’s necessary to build a working IrDA(SIR) hardware implementation. To completethe full IrDA implementation, you’ll need tocode the IrDA protocol stack, which can be themost 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 SIRsolution. This practical building block uses an NEC V850E/MS1CPU 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-munication session, and binary ftpcommands to exchange images.

SAMPLE COMMUNICATION SESSIONNow you’ve been introduced to a

set of incredibly poetic-sounding acro-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 betweena PDA and an IrTRANP camera.

The user selects an image 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 queries whetherthe PDA supports IrCOMM services.

The PDA responds, “Yes. I supportIrCOMM, go ahead and connect to chan-nel x, which is my IrCOMM channel.”The camera disconnects from the IASchannel (channel 0), connects to theIrCOMM channel (channel x), and sends

an IrTRANP connect commandthrough the IrCOMM channel.

After the PDA acknowledgesthe IrTRANP command, thecamera executes an IrTRANPput command 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 find it easier to implementyour own IrDA solutions. I

SOURCES

80C320Dallas Semiconductor(972) 371-4448Fax: (972) 371-3715www.dalsemi.com

HSDL7001, ’1001, ’1100Hewlett-Packard(408) 435-4303Fax: (408) 435-4303www.hp.com

PLX7001Parallax Research Pte Ltd.+65 791 7388Fax: +65 793 0086www.parallax-research.com

NS87109 UIRNational Semiconductor(408) 721-5000Fax: (408) 739-9803www.national.com

V850/MS1NEC Electronics(408) 588-5008Fax: (408) 588-5017www.necel.com

Page 53: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

66 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 like to introduce you to thechip’s features. The Rabbit-80 is builtaround an enhanced Z80-compatibleCPU and contains a set of on-chipperipherals designed to address typicalembedded-control applications.

Note that no on-chip memory isincluded. The majority of applicationsserved by Z-World controllers requiremore flash memory and RAM than wecould include on-chip at a reasonableprice, especially given the low pricesof individual 256K × 8 flash memoryand 128K × 8 RAM devices.Let’s look at each of theblocks of Figure 1.

THE CPUFor the most part, the

CPU in the Rabbit is Z80-compatible. We madechanges to the instructionset to provide a greater

degree of support for the C language.Several seldom-used instructions (seeTable 1a) were removed in favor of thenew instructions listed in Table 1b.

Many of the new instructions pro-vide 16-bit operations that weren’treadily available in the Z80. Theseadditions provide a big performanceboost in the math libraries, especiallywith the new 16 × 16 signed multiply.The MUL instruction requires just 12clocks to provide a full 32-bit result.

Operations such as the stack-rela-tive load and store, and the ability 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 that requiredspecific registers and addressing modes.Instead, the Rabbit uses two prefixbytes, which precede an instructionintended to access I/O.

The prefix bytes identify whetherthe desired I/O location is internal orexternal, and change the timing andcontrol signals appropriately to provideaccess to the peripheral. This setupgives greater flexibility when access-ing peripherals because the prefixescan be used with any instruction thataccesses memory.

A similar approach provides accessto the Z80 alternate register set. TheALTD prefix switches the destinationregister to the corresponding registerin the alternate register set, which cutsdown on the bank switching necessarywhen using the alternate registers.

The final additions support thelarge physical address space. Loads

Design Application with the Rabbit-80

Figure 1— This is what the Rabbit-80looks like on the inside. Only externalmemories 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

Par

t

of22

Page 54: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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 stores use a direct 20-bit physicaladdress instead of the usual 16-bitlogical address. The program flow-control (jump, call, and return) in-structions load one of the MMU 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 another bank regis-ter and the ability to bank-switch thememory chips for even more programand data space. The MMU addresstranslation algorithm is shown inFigure 2.

The MMU uses the upper four bitsof the logical address to select one ofthe bank registers to use for addresstranslation. The exact boundary whereone bank ends and another begins iscontrolled by another register.

The exception is a newly addedbank register, which is always usedfor translation when the logical ad-dress is between E000h and 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 works for accesses using oneof the bank registers and allows execu-tion out of RAM while accessing datain flash memory. Address bits 16 or19 (or both) can be inverted for dataaccess, so data can be accessed at either64 or 512 KB above or below the code.

At this point, the address goes tothe chip-select decoder, which uses theupper two bits of the 20-bit address togenerate three chip-select signals, twowrite-enable signals, and two output-enable signals. Each memory quadrantcan use any combination of a singlechip select, an output enable, and awrite enable. Figure 3 shows a typicalsystem configuration.

The chip-select signal typically usedfor RAM can be forced continuallyactive to circumvent the delay inherentin routing the signal through an exter-nal power controller for battery-backedapplications. Each memory quadrantcan be individually write-protected.

The final address modification allowsthe two most significant bits of theaddress to be flipped (individually foreach memory quadrant) after the chip-select decision is made. This arrange-ment allows a 1M × 8 memory chip tobe bank-switched within a 256-KBquadrant of the physical memory space.

BUS TIMINGThe basic instruction time and bus-

cycle time are both two clock cycles.Memory-write cycles have one waitstate automatically added. The basicread cycle is shown in Figure 4a, andthe basic write cycle, in Figure 4b. Foreach of the four memory quadrants,there is a choice of zero, one, two, orfour automatic wait states.

Separate strobes are provided forI/O transactions and up to eight I/Ochip-select signals can be output onPort E. The 64-KB external I/O addressspace is evenly divided for the eightI/O chip selects. Each I/O region canbe programmed for 1, 3,7, or 15 automatic waitstates and can be write-protected.

Internal I/O addressesare separate from externalI/O addresses. Of course,most of the time a Rabbitsystem won’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. Thisbyte-wide port is a bidirec-tional communications chan-nel between the code on theRabbit and a master system.To the master, the Rabbitlooks like a combination of

three write registers, three read registers,and a status register. The Rabbit CPUhas the same view of the slave port.

Figure 5 shows the slave-port hard-ware interface. Since the chip select isdesigned into the slave-port interface, anumber of Rabbit slaves can be simul-taneously used in a system.

The master writing to the slaveport can generate a Rabbit interrupt,and a Rabbit writing to the slave portcan activate the interrupt signal to themaster. 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 small Rabbit sys-tem would look like a group of “smart”peripheral devices to a master system.

SERIAL PORTSThe Rabbit has four independent

serial ports: two are async-only, and twoare combination async/clocked serial.

Table 1a—These Z80 and Z180 instruc-tions were removed to make room fornew instructions. They can all still beemulated in software. b—These newRabbit-80 instructions provide higherperformance. The main additions are the16-bit math operations and long addressoperations.

Figure 2— The MMU translates logical addresses to physical addresses. Italso 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Parallel Port C is the primary serial-port interface, but the combinationserial ports can also be connectedthrough parallel Port D. This multi-plexing allows the combination portsto be used in both modes, with sepa-rate line drivers, although not both atthe same time.

The async capabilities don’t includeall of the seldom-used options oftenfound in serial ports, but everythingyou need for 99% of the possible ap-plications is there. The ports require a16× clock and automatically includestart and stop bits.

They can also be programmed tosend and receive an extra address bitfor multidrop applications. There’s asingle byte of buffering for both thereceiver and the transmitter.

The clocked-serial capabilitiesallow communication with SPI and I2Cdevices using an internal or externalclock. External A/D and D/A devicesoften communicate using these types

of serial transfers. Although it wouldrequire software to do the frame format-ting, these ports could be used to sendand receive HDLC messages.

TIMERSThe first set of timing resources on

the Rabbit, Timer A, contains fiveseparate 8-bit counters. Four of theseare used to supply the clocks for theserial ports. The fifth can be used totime outputs on the parallel ports.

The counters can be cascaded if slowtransfer rates are necessary. Of course,a programmable interrupt is availablefor the terminal-count condition onall five counters.

The second set of timing resources,called Timer B, is significantly morepowerful than Timer A because it wasdesigned to facilitate PWM outputs onthe parallel ports. Timer B consists ofa 10-bit counter, a pair of 10-bit matchregisters, and a pair of 10-bit bufferregisters. Timer B is shown in Figure 6.

The counter is free-running and isclocked by the system clock dividedby two or eight, or by the output of oneof the counters in Timer A. Each matchregister generates an output pulse whenthe counter matches its contents. Thispulse can be used by two parallel portsto precisely time output transitions.

Whenever a match occurs, the corre-sponding match register is loaded fromthe buffer register and an interrupt isgenerated so the buffer can be reloaded,which allows PWM to be accomplishedwith little CPU overhead. Using thetwo match registers in tandem makesit easy to create the quadrature signalsnecessary to drive a servo.

PARALLEL PORTSThe five parallel ports on the Rabbit

can be used individually or programmedto provide inputs and outputs for theother on-chip peripheral devices.

Port A is a byte-wide port that canbe used for simple byte-wide I/O or asthe data bus of the slave port. Port Bconsists of two outputs, four inputs,and two I/O. Port B is mostly used forthe control signals for the slave port,in addition to the two clocks for theclocked serial ports. No special timingoptions are available in output modefor these two ports.

Port C consists of four inputs andfour outputs, and serves as the primaryI/O for the four serial ports. Port Cinputs are always reported in the dataregister (even when being used as serialport inputs) to allow the timing of areceived break signal. Port C outputscan be individually selected as simpleoutputs or serial port outputs.

Four bits of Port D provide alternateI/O for the two dual-function serialports, but all eight bits of Port D are

Figure 3— In a typical Rabbit system, only external memory chips are required and they connect without any glue logic.

256K × 8 RAM

From power controller

VDD1RESETB

*CS *WE*OE

1M × 8 FLASH

*CS *WE*OE

1M × 8 FLASH

*CS *WE*OE

D[7:0] D[7:0] D[7:0]A[19:0] A[17:0] A[19:0]

ADDR[19:0]

DATA[7:0]

MEMCS2B

MEMCS1B

MEMCS0B

MEMOE0B

MEMOE1B

MEMWE1B

MEMWE0B

20 MHz 32768 Hz

PORT_A

PORT_B

PORT_C

PORT_D

PORT_E

Slave port interface

Four async ports

Four Interrupt inputs

Four simple inputs

Four PWM outputs

Four LED drive outputs

RTXCI/OXTALI/O

Rabbit-80

DATA

MEMCSxB

MEMOExB

T1 T2

Valid

CLK

ADDR

Valid

Valid

CLK

ADDR

DATA

MEMWExB

T1 TW T2

Valid

MEMCSxB

Valid

Valid

Figure 4a— Memory readtiming fits perfectly withSRAMs or flash memory.Access time is two full clockcycles. b—Memory writetiming looks a little different.The extra clock cycle allowsfor a wider write pulse andsome data hold time.

a) b)

Page 56: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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 drive capability than theother ports for driving LEDs, optoiso-lators, solid-state relays, and more.

As outputs, the two nibbles of PortD can be clocked independently byTimer A’s output or by either Timer Boutput. Any data written to the port’sdata register isn’t clocked to the pinuntil the selected signal is active, 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 programmed to provide the I/Ochip selects and the chip-select inputfor the slave port. Four Port E pins canalso be used as CPU 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 whether or not an interruptis accepted, thereby allowing only inter-rupt requests with higher priority tobe accepted. As well, the CPU keeps astack of the four most recent prioritylevels, which allows preemption.

Every interrupt source can be pro-grammed to request an interrupt atone of the four levels. Of course, aninterrupt requested at level 0 wouldnever be accepted because it isn’thigher than anything. This is howindividual interrupts are disabled.Similarly, when the CPU is at level 3,no interrupts will 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, simulating a nonmaskableinterrupt. Then the normal CPU prior-ity would be level 0, enabling all in-terrupts. Of course, if there are criticalsections of code that can’t be inter-rupted, then they should be run whilethe priority is temporarily set to level 3.

All accepted interrupts cause anautomatic branch to a fixed location inmemory, as shown in Table 2. Inter-

Figure 5— The Rabbit looks like an I/O device whenusing the slave port. This feature allows the Rabbit tobe 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. Thedouble buffering reduces time-critical overhead.

10-bit counter

Buffer register 1

Buffer register 2

Match register 2

Match register 1

ComparatorMatch 2Match 1

Page 57: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

a battery-backed system can keep timewhen the main power fails. Both the32-kHz oscillator and the RTC areoptimized for power consumption. Ifthe main power is absent, a 150-mAhbattery powers the RTC, so the Rabbitcan keep time for about a year.

CLOCKING AND POWER OPTIONSThe 32-kHz oscillator is accompa-

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 power inthe 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 ultimate power savings.

BOOTSTRAPA primary design goal was to allow

for remote bootstrap (i.e., to make itpossible to have RAM-only systemsusing the Rabbit). In this mode, theCPU fetches instructions from a small(12 byte) internal ROM containing thecode in Listing 1. At each internal I/Oread instruction, the internal logic holdsthe CPU in a wait state until a byte isavailable from the selected peripheral.

Two 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(when the PC address is 0000 in thefour least significant bits) to enablethe boot ROM.

Thanks to everyone at Z-World, espe-cially Norm Rogers for conceiving theRabbit-80, and Pedram Abolghasemfor running the project (and doingmuch of the work) there.

Monte J. Dalrymple has been design-ing ICs for more than 20 years. Hecurrently has his own company, whichdevelops intellectual property. You mayreach him at [email protected].

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 the Z80.

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 example, the four serial ports canuse identical code, as long as the portaddresses and data-table pointers areset up in these 16 bytes before branch-ing to the common routine.

The Rabbit has one other interrupt—the periodic interrupt, which occursat a rate of 2.048 kHz. This interruptis useful for time-slicing or low-speedstatus monitoring and is generated fromthe 32-kHz oscillator, which also clocksthe watchdog timer and real-time clock.

WDT AND RTCThe watchdog timer (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 thenext timeout period. Any other byteswritten to this register are ignored, andif one of these four bytes isn’t writtenin time, the Rabbit is reset.

The RTC doesn’t keep hours/min-utes/seconds time; it’s a 48-bit counterclocked at 32 kHz. It can be set to aspecific count by software before itstarts counting up. If the software startscounting from zero, that’s 272 years oftimekeeping (yes, it’s Y2K compliant).

The Rabbit contains a completelyseparate power plane for the RTC, so

SOURCERabbit-80Rabbit Semiconductors(530) 757-8400www.rabbitmicro.com

The bootstrap mode assumes datatransfers in groups of three bytes. Thefirst two bytes are the address for thedata, followed by the data itself. Thisarrangement allows data to be loadedanywhere in memory.

To select between external memoryand internal peripheral control regis-ters, the Rabbit uses the most signifi-cant bit of the downloaded address.Once the peripherals are accessible,the MMU can be programmed, provid-ing full memory access.

To exit bootstrap mode, write 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 location that disables it isaccessible during bootstrap.

ROLLING ALONGNow that you know how the Rabbit

was designed and what it contains, whatcan you do with it? Anything a Z80 orZ180 can do, and more. Plus all thedevelopment software is available. I

ORG 0hLD L, n ;n = 0C0h for serial, n = 020h for parallelIOIPLD D, (HL) ;fetch the address msbIOIPLD E, (HL) ;fetch the address lsbIOIPLD A, (HL) ;fetch the dataIOIP or NOP ;IOIP if D(7) = 1, NOP if D(7) = 0LD (DE), A ;store the dataJR 0h ;loop back

Listing 1 —Just 12 bytes are needed for the bootstrap loader. The hardware automatically modifies thebytes 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 beforejumping into the main service routines.

Page 58: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

72 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 SmartMedia flash-

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 much to the interface. A microcon-troller handles both the SmartMediainterfacing as well as a serial commu-nications channel.

One of the important points of thiscircuit is that it can run at either 3.3or 5 V. The SmartMedia device in-serted into the SmartMedia socket indi-cates the necessary voltage throughthe output pin 17. (If you missed lastmonth’s column, now might be a goodtime to go back and read it because I’mgoing to assume that you’re familiarwith the signals of the SmartMedia.)

SmartMedia products cover such alarge range, you must be able to sensethe type and size of the device insertedinto your equipment. If you don’t recog-nize the SmartMedia, you should makeaccommodations to reject or at leastnot corrupt the data held in the device.

Therefore, it’s recommended thatyou follow certain steps to determinewhether the device is compatible withyour equipment: the detection of inser-tion, operating voltage, type and size,physical format, and logical format.

INSERT HERE Many SmartMedia sockets have an

internal microswitch which enablesyou to determine if a device has beeninserted into the socket by the physi-cal operation of the switch’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 the device is not fullyinserted into the socket, the pullupregisters a logic high with the inter-face. When fully inserted, pin 11, whichis physically connected to the VSS (pins1 and 10) contacts of the SmartMediadevice, grounds the pullup and registersas a logic low to the 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-switches can be used to determineoperating voltage (at the same time asinsertion).

Besides the fact that the operatingvoltage is written on the SmartMedia,the packaging has either a left-clippedcorner, indicating 5-V operation, or aright-clipped corner, indicating 3.3-Voperation. So, two switches strategicallyplaced at either corner of the socketcould be used to mechanically iden-tify the proper operating voltage. TheSmartMedia’s clipped corner would notengage one of the two switches, thusindicating which media was inserted.

Determining the proper voltage canbe done electrically as well, via pin18. This time a pulldown is used. On5-V devices, pin 18 floats (internallyunconnected), whereas on a 3.3-V device,pin 18 is connected to VCC.

So, once inserted, a 5-V SmartMediadevice will not affect the logic lowread by the interface, indicating theneed for a 5-V supply. On the otherhand, a 3.3-V device with pin 18 con-nected to VCC raises the interface to alogic high, which indicates the needfor a 3.3-V supply.

Personally, I think a pullup makesmore sense here. This way, the inter-face would see the need for a 3.3-V

l

Part 2: Hands On

Page 59: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

ing PCMCIA memory cards. When aSmartMedia card is inserted into aPCMCIA ATA adapter card, the PCM-CIA slot looks for this information asif it were a PCMCIA memory card.Voilà! Instant device recognition basedon a previously designed standard.

The 16-byte redundant area holdsinformation pertinent to the validityof the previous 512 bytes of the page(see Figure 2). This area is broken downinto seven pieces of information. Thefirst 4 bytes are reserved for extensioninformation.

The next byte is the page data valid-ity marker. If the data written is notcorrect, a 0 indicates that the usershould not consider this page to begood and should proceed to the nextpage for CIS/IDI information.

The next byte is fixed at FF, whichis normally the bad block marker. Thenext two bytes are fixed at 00 and 00(the physical block number). Follow-ing those two bytes are three bytes oferror correction code (ECC) data.

The ECC’s 22 bits are calculated fromthe first 256 bytes of the page. Finally,the physical block number, in this case

a fixed 0000, is repeated followedby an ECC on the second 256 bytesof the page.

So, not only is the CIS/IDI datarepeated twice within this page,but separate ECCs are calculatedand saved in the page’s redundantarea. The ECC values enable a

In addition to testing and markingbad blocks, the manufacturer does someadditional housekeeping to comply withthe physical format specifications. Thefirst physical page (or first good physi-cal page) must have card informationstructure and/or identify drive infor-mation (CIS/IDI) data written to it.

You should note that, although earlySmartMedia devices used a 256-bytepage (with an 8-byte redundant area),the larger devices made today use a512-byte page (with a 16-byte redun-dant area). For the remainder of thisdiscussion, however, I’ll only talkabout the 528-byte (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-byte data area, which can be usedby the ATA-interface-equipped hostsystem.

As a precautionary measure, theCIS/IDI data is repeated in the secondhalf of the page (see Figure 2). TheCIS/IDI format is defined by PCMCIA.

The PCMCIA slots on most laptopsinterface to many peripherals, includ-

supply when no device is insertedand it would prevent the interfacefrom thinking it should supply 5 V,which would be a bad thing duringa 3.3-V device insertion. Anyway,using pin 18 enables the device tobe probed at the lower voltage andraised only if necessary (and safe).

SHOW SOME IDAt this point, the proper opera-

tional-voltage parameter can be set,the media type and size identified,and we can begin to communicatewith the SmartMedia device. AReadID command regurgitates botha maker ID and device code. Themanufacturer’s ID may be 98H(Toshiba), ECH (Samsung), or anothercode registered with the SSFDC.

You’d think that with so feworiginal players creating the standard,device type and size codes would bestandardized throughout manufactur-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 indicates parameterslike device size, operating voltage, andmemory type. If you find ID and devicecodes that you don’t recognize, it onlymakes sense to reject the device. Afurther operation on an unknown deviceruns the risk of damaging the data heldwithin the device.

PHYSICALLY FITSmartMedia manufacturers pretest

every page of flash memory for stuck(bad) bits. If a bad bit is detected inany page within the block, every pagein that block is marked as bad.

Remember that this indicator byteis flash memory and when the blockis erased, so is the bad block byte. So,when erasing a block, the user mustremark it as bad either from a user-compiled list of bad 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 isnot shown. However, the PIC can operate at either voltage. The VCNT1 connection is used to control the appropriateoperating voltage, depending on the device inserted into the SmartMedia socket.

Page 60: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

CIRCUIT 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 (23) row parity, six bits(2 × 3) of ECC data are required.For the 256-byte (28) columnparity, 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 bytes of all eight bits.

The ECC data is writteninto the page’s redundant areaalong with the page data.When the page is read from thedevice, the ECC data can becompared to newly calculatedECC data. A good comparewill ensure good data integrity.

What happens when a badbit occurs somewhere? If thebad bit is in the data area, everyECC data bit that uses thebad bit in its calculation willbe affected and will show upin one of each pair of ECCbits. From this pattern youcan determine which data bitis at fault and correct it.

If two data bits are bad, theECC data will reflect 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,it shows up as a single ECC biterror. This kind of error cannot becaused by any combination of baddata-area bits. So, it can be ignoredand filed in the proverbial bitbucket.

The 22 bits of ECC data is inthe following format: most signifi-cant byte of the 16 line-paritybits, followed by the least signifi-

single bit error in the 256-byte pagearea to be repaired. Multiple 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 parity).

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 with 1024 physical blocks,only 1000 logical blocks are used. Theremaining blocks are spares (or in thecase of blocks with bad bits, unusable).But, as you will 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 significant bitsfilled with 1s.

Calculating the ECC data can bedone ahead of time where the parityequivalent of each data 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 column parity(CP) data.

ECC calculations can be handledby hardware or software. The programlisted in the Software section is aBASIC program that calculates the22-bit ECC for a half page of data(256 bytes).

This program runs on a PC underQBASIC and will respond with theLPHigh, LPLow, and CP bytes for thearray D(1)–D(256). You can plug valuesinto 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 friendly” devices, it often takesmany layers of complexity to simplifyits use.

Although we could stop here anduse the SmartMedia in an application,the data in the flash-memory devicewould be unreadable elsewhere (un-less you wrote drivers for every pieceof equipment that needed to access the

Figure 2 —With a serial terminal, the SmartMedia interface can beused to investigate SmartMedia devices. Here’s the boot record of adevice.

1 - Sequential Data In2 - Read 13 - Read 24 - Read ID5 - Reset6 - Page Program7 - Block Erase8 - Read Status0- Quit

3Enter the page # to readA page is 512 bytes of data + 16 spare byte

32Reading page #32000 01 03 D9 01 FF 18 02 DF 01 20 04 00 00 00 00 21010 02 04 01 22 02 01 01 22 03 02 04 07 1A 05 01 03020 00 02 0F 1B 08 C0 C0 A1 01 55 08 00 20 1B 0A C1030 41 99 01 55 64 F0 FF FF 20 1B 0C 82 41 18 EA 61040 F0 01 07 F6 03 01 EE 1B 0C 83 41 18 EA 61 70 01050 07 76 03 01 EE 15 14 05 00 20 20 20 20 20 20 20060 00 20 20 20 20 00 30 2E 30 00 FF 14 00 FF 00 00070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00090 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000A0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000B0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000C0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000D0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000F0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

100 01 03 D9 01 FF 18 02 DF 01 20 04 00 00 00 00 21110 02 04 01 22 02 01 01 22 03 02 04 07 1A 05 01 03120 00 02 0F 1B 08 C0 C0 A1 01 55 08 00 20 1B 0A C1130 41 99 01 55 64 F0 FF FF 20 1B 0C 82 41 18 EA 61140 F0 01 07 F6 03 01 EE 1B 0C 83 41 18 EA 61 70 01150 07 76 03 01 EE 15 14 05 00 20 20 20 20 20 20 20160 00 20 20 20 20 00 30 2E 30 00 FF 14 00 FF 00 00170 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00180 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00190 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 001A0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 001B0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 001C0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 001D0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 001E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 001F0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

200 FF FF FF FF FF FF 00 00 0C CC C3 00 00 0C CC C3

Figure 3— Line parity and column parity data bitscan indicate and correct for single bit errors. Thisfigure shows how each half page of data is usedto create the 22 bits of ECC (error correctioncode) 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 3

Byte 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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

data). Formatting the physical formatwith a DOS file 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 theproper 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 consists 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 the device. If you re-member back to the physical format,the CIS/IDI also resides there. Thereis no conflict because the first parti-tion info starts at offset 1BEh with theboot ID 80h. Table 2 lists the rest ofthe partition parameters.

Offset 1C6h–1C9h indicates wherethe partition boot sector islocated (in this case, logicalsector 37h). Given one pageper sector, the PBS is oncylinder 0, head 1, andsector 17h.

The final piece is thepartition boot sector. Again,there are a number of pa-rameters here, as well asthe FAT and the directory.Table 3 gives you all thepertinent information.

The FAT follows thepartition boot sector, whichindicates how many sectorsare required for the FAT andthat there are two 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 name, extension,

and attribute, along withthe last edit time/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 minimum number of sectorsthat can be allocated to a file.

From the starting cluster number,the starting logical sector of the file’sdata can be determined. If the file’slength exceeds the cluster size, addi-tional clusters can be allocated throughthe FAT.

SECTOR MANIPULATIONRemember when I mentioned how

not all of the physical blocks were givenlogical addresses, and that some extrablocks were left unallocated? Well, thefirst time the block is written with

data, the data merely gets programmedinto the erased logical blocks.

When a block needs to be changed,the block must be read from the device(including the redundant area), thepertinent data changed, and the blockwritten back to any unused block inthe same zone. The redundant area isalso written, identifying it as the samelogical block that was just read. Now,the original block is erased, removingit from service. If you are keeping a tableof which physical block is which logi-cal block, you must correct the table.

I’ve purposely not mentioned thislogical-to-physical tableuntil now because it 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 wholedevice, 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 thedevice.

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 00h1C2h 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 isformatted, the boot sector providesinformation about the device,including where to find the firstpartition.

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 partition 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 thedirectory and FAT.

Page 62: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

data for a single page and its redun-dant area.

What I can do is enable the user touse the basic operations available withSmartMedia by dumping data read fromthe device to a serial port. By using aCOMM program like PROCOMM (oreven HyperTerminal) the user canfully investigate SmartMedia.

But, you’ll be required to preparepage data manually, including theredundant area (ECC calculation,block address, etc.). Figure 3 illus-trates a dump of the directory area of

000 49 4D 30 31 54 4F 53 48 20 20 20 10 00 00 00 00010 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00090 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000A0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000B0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000C0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000D0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000E0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000F0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

Figure 3— After I took a single picture with my digital camera, thedirectory holds a single entry. The file name is IM01TOSH.

one of my digital camera’sSmartMedia cards.

Using a SmartMedia cardtakes some work to be able tofully handle all the necessaryformatting. But, only a fewroutines are necessary if all youwish to do is save some data.You can get away with a mini-mum amount of RAM, butthere 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 justwritten comes up with an error. Cor-recting the data (reading, correcting,and rewriting) is impossible withoutenough RAM to hold the page. In thiscase, you might just keep going. If it’sonly a one-bit error, it can be cor-rected using the ECC when 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“BAH-key-AH-key”) is an electrical engineer onCircuit Cellar’s engineering staff. Hisbackground includes product designand manufacturing. He may be reachedat [email protected].

Thanks to Doug Wong, Toshiba, for hisSmartMedia expertise and documenta-tion, and to Jeff Schmoyer, microEngi-neering Labs, for the PIC BASIC Pro.

SOURCESSmartMediaToshiba(408) 737-9844Fax: (408) 737-9905www.toshiba.com

Samsung Semiconductor, Inc.(408) 544-4000Fax: (408) 544-4907www.usa.samsungsemi.com

SOFTWAREThe BASIC program used to calcu-late the 22-bit ECC is available viathe Circuit Cellar web site.

Page 63: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

w hen it comes togetting embedded

gadgets onto the I-way, designers have

quite a few options to choose from,with more emerging all the time. Thechallenge is picking one that bestmatches your apps requirements.

If circumstances allow, why notrely on a standard off-the-shelf PC asyour ’Net gateway? Thanks to themarch of silicon (and some might say,the death-wish pricing tendencies ofPC suppliers), you can get a perfectlyadequate PC for well under $1000.

And besides, even the cheapest PChas plenty of horsepower, comes with

the software to accomplish ’Net trans-actions, and has an unparalleled quiverof development tools.

More power to you if the PC ap-proach works for you, but desktop PCscarry a lot of baggage. They’re big,consume a bunch of power (considergoing with a laptop), take a long timeto boot, and neither the hardware norsoftware is especially robust.

Embedded PCs, whether Compact-PCI, PC/104, or a stand-alone SBC,can easily address the packaging andpower concerns raised by their desk-top brethren. Another option is to useLinux instead of Windows, exactly thetack taken by Stanford University’sWearable Computing Lab.

They built a tiny, Linux-based webserver using a miniscule EPC [1]. Re-fer to the lab’s web page or back toIngo’s articles on embedding Linux(Circuit Cellar 100–104) if you’reinterested in this approach.

Note that I didn’t include price inthe list of concerns. The fact is, EPCscost hundreds of dollars (the EMJ boardused at Stanford lists for over $400)and at best are just competitive withdesktop 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 (’x86 orRISC) running an RTOS or WindowsCE, fully loaded with protocol stacks,Java, and all the rest. You still need ahefty amount of silicon, 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

T06

T05T04T03T02

T16

VDD

T15

T14

T01

T07

T17

RS

CS

C86

RE

AD

XV

SS

NT

1

WR

ITE

X

NT

2X

BU

SY

X

PS

X

TI3

NT

CT

RL

RT

SX

DT

RX

DC

DR

XDRI

CLK

CT

SX

TE

ST

RE

SE

TX

DS

RX

TX

D

VS

S

SD1

SD2SD3SD4SD5

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 handlesall the details of TCP, UDP, IP, and PPP.

PPP

IP

UDP TCP

Serial port

Ser

ial p

ort

CPUinterface

SRAM interface

To

CP

U

SRAM (10 KB)

Network stack

Page 64: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

together all the pieces isn’t trivial, butpackaging, power consumption, andprice challenges are easier to over-come without the Wintel baggage.

One of the best of this breed is theNET+ARM from NETsilicon. It com-bines a high-integration ARM CPUwith networking hardware (Ethernet,UART, etc.) under the supervision ofan RTOS that includes all the requi-site networking software. NET+ARMpricing ranges from $10 to $40 depend-ing on version and volume, and in-cludes a glueless interface to (EP)ROM,SRAM, DRAM, SDRAM, and so on,making for a quick and easy minimalchip count design.

As an interesting aside, NETsilicontipped me off to the formation of theIndustrial Automation Open Network-ing Alliance by several embedded Inter-net players, including big guns likeGE Fanuc, Siemens, Cutler-Hammer,Andover Controls, and Sun [2].

It’ll be interesting to see how theIEEE 1451 standard (Circuit Cellar 103)and its prime proponent HP fit in.There’s always been an interest inbridging the gap between office andfactory automation. Now, the ’Netprovides a way.

’NET UARTWhichever way you cut it, embed-

ded ’Net solutions call for a 32-bitCPU and a fair amount of memory.Cutting more fat can get interesting.

Consider Myron Lowen’s approachin “Internet Appliance Interface”(Circuit Cellar 108). He got on the

’Net with little 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-ware,” Circuit Cellar 106), I describeda nontraditional solution offered byiReady. The i1000 protocol engineoffloads a host CPU by handling allthe details of TCP/IP, HTTP, SMTP,POP, and so on. Because it works withany CPU, the i1000 is a potentiallyeasy and inexpensive way to add net-work capability to existing designs.

I say “potentially” because, as Ilamented then, the i1000 isn’t actu-ally offered as a chip but as a bunch ofIP (i.e., Verilog) from which you aresupposed to build an ASIC—a fire drillthat’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 known as the iChip (seeFigure 1). Packed in a tiny 48-pin QFPand under $10 in volume, the ’7600Ais a networking solution that won’tbog down efficient embedded designs.

On one side is a generic processorinterface. On the other is a conventionalRS-232 port. In between is the network-ing know-how and silicon (protocolengine and SRAM) to handle two 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 whether to use a serial orparallel host interface and, if the lat-ter, whether Intel or Motorola flavor.The Intel convention features separateread and write strobes, but Motorolauses a read/write status line and adata strobe. The appropriate functionsare mapped to READX and WRITEX.

SD7–SD0 make up the parallel databus. In serial mode, SD7–SD5 becomethe serial data in, clock, and out, respec-tively. Chip select (CS) enables accesswhen asserted and tristating outputswhen deasserted so the ’7600A canshare the bus with other peripheral ICs.

The ’7600A uses the BUSYX outputto handshake with the host. The ac-tive-high and active-low interruptrequest 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 addresslines for direct access,so getting at a specificregister is a multistepprocess (see Figure 2).

First, the host writesthe desired address withthe register select (RS)pin low. Then, it issuesa read or write commandwith RS high to initiatethe 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-stepprocess—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 aworthy contender for “world’s smallest web server”bragging rights.

Page 65: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

Once connected (i.e., two socketstalking via TCP/IP), the ’7600A han-dles all the 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 incorporate hardware sup-port for higher layer protocols such as

ets the ’7600A supports. The value (0or 1) set in the Index register (0x20)defines which is accessible.

In Internet-speak, a socket is a full-duplex port uniquely identified by theconcatenation of IP address and asocket number. 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 software to open a socketand establish a connection as shown inFigure 3. Instead, the ’7600A handlesall the grunt work. All you have to dois set an activate socket bit and waitfor a connection established bit.

0x00

0x01

0x02

0x04

0x08

0x09

0x0A

0x0B

0x0C–0x0D

0x10–0x13

0x1C

0x1D

0x20

0x21

0x22

0x23

0x24

0x26

0x28

0x2A

0x2B

0x2C

0x2D

0x2E

0x30

0x30–0x31

0x32–0x33

0x34–0x35

0x36–0x37

0x38–0x39

0x3A

0x3C–0x3F

0x60

0x61

0x62

0x64

0x6F

Revision Major revision number Minor revision number

General_Control

General_Socket_Location

Master_Interrupt

Serial_Port_Config

Serial_Port_IntSerial_Port_Int_MaskSerial_Port_Data Serial port data register

Baud rate divider registersBAUD_Rate_Div

Our_IP_Address Our IP address

Clock_Div_Low

Clock_Div_High

Index

TOS*

Socket_Config_Status_Low*

Socket_Status_Mid*Socket_Activate

Socket_Interrupt

Socket_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_String

PPP 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 DSINT

PINT_EN DSINT_EN

Low byte for 1-kHz clock divider

High byte for 1-kHz clock divider

Socket index

Type of service field

Protocol_TypeData_Avail/RST

Data_Avail_En

Buff_Full

Buff_Full

Buff_Empty

Buff_Emp_En

TO

Data_Avail

Buff_Full

Buff_Empty

TO

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 sent

Buffer out length

Buffer in length

Urgent data offset pointer, UDP datagram sizeTarget port address

Our port address

Snd_Bsy

Target IP address

PPP_IntPPP_Int_En

Con_Val

Use_PAP

TO_Dis

KickPPP_En

PPP_Up / SR

Interrupt codePPP maximum retry

Pap user name and password

Test Bypass LoopBack

Register Bit definitionsAdd

Table 1—The host controls the ’7600A operation and transfers data through various registers. A number of theregisters in the range 0x21–0x3F (marked with an asterisk) are duplicated for each socket and selected with theIndex register (0x20).

’7600A asserts BUSYX while it per-forms the data transfer. For a read, thehost retrieves the data with a thirdaccess after BUSYX is deasserted.

The network connection is a simpleUART. There’s a 16-byte receive FIFO,optional RTS/CTS handshaking, 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 ’7600Aimplements protocol processing withhardware state machines. The mini-mum clock rate depends on the datarate demands of the physical channel,but it’s only on the order 1 Hz per bpsof physical channel bandwidth, so amere 100 kHz could handle any mo-dem. The low-speed clock and opti-mized hardware also make for lowpower consumption (i.e., milliamps inoperation and microamps in standby).

PROTOCOL POWERIn Figure 2, after RESET, the host

initializes the ’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 ATD commandto a connected modem and dial anISP. Here’s where it gets interesting.

After the modems establish com-munication, your software flips theserial control (SCTL) bit in the con-figuration register (0x08) and theonchip PPP logic (registers 0x60–0x6F)takes control of the serial port andstarts yacking with the ISP’s software.The ’7600A handles the back-and-forth of options, passwords, and suchthat otherwise call for a lot of code.

Once PPP does its thing, 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, which front the TCP/IPservice. Note that this set of registersis duplicated for each of the two sock-

Page 66: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

e-mail (i.e., SMTP and POP3), web(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 actual chip but rather a col-lection of know-how to enable you todesign your own ASIC. Thus, eachi1000-based chip should only includethe functions required by an applica-tion (e.g., a chip designed to handle e-mail doesn’t need web 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 say TCP/IP andPPP are the sweet spot.

First, of the alphabet soup of proto-cols that abound, TCP/IP and PPP areamong the most complex. A quickway to illustrate the situation is tocheck the file sizes of the variousRFCs (Request for Comments; i.e., theseminal I-way specs from the DARPAdays). TCP/IP and PPP comprise about300 KB (that’s just the main RFCs, notall the embellishments and add-ons)compared to 150 KB for FTP, 120 KBfor SMTP, and a mere 35 KB for POP3.

Furthermore, TCP/IP and PPP arethe common denominator for all theother protocols. By contrast, higher

level functions such as e-mail, web, and file are de-signed to functionindependently. If you justneed FTP, there’s no need tobother with HTTP, SMTP,POP3, and so on. Whicheverprotocol(s) you choose, you’llneed TCP/IP and PPP underthe hood.

Finally, many embeddedInternet apps, such as secu-rity, data logging, mainte-nance, and inventory, require

minimal ability to communicate. So,it’s likely that a particular app won’trequire all the frills of a full-blownserver. In fact, if you strip away abunch of the fat you’ll find that the

software to handle simple web, e-mail,and file duties isn’t that hard at all.

However, if the ’7600A put thesehigher 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 with a PIC to create aminimalist web server (see Photo 1).Add a modem and you’re on the air.

Don’t believe that such a measlyamount of silicon can push your bigbad browser around? See for yourselfat http://xsmall.mycal.net.

Mike was kind enough to send mea copy of his code, which demonstra-tes the ’7600A’s power to turn a lowlymicro into a web warrior. Remember,the PIC (’16F84) has a 1024-instruc-tion (14 bits each) code memory thatleaves little room for bloat.

Even the limited 1-KB instructioncapacity overstates the software’s

00133 look_table00134 web_page1

343C 3468 3474 00135 DT "<html>" 346D 346C 343E 343C 3474 3469 00136 DT "<title>Worlds Smallest Webserver</title>" 3474 346C 3465 343E 3457 346F

; Open a socket to listen on port 80 writex SOCKET_OUR_PORT,.800297 3038 M movlw 0x380298 008D M movwf address0299 3050 M movlw .80029A 008E M movwf dbyte029B 219F M call writeb writex SOCKET_OUR_PORT+1,0x00029C 3039 M movlw 0x38+1029D 008D M movwf address029E 3000 M movlw 0x00029F 008E M movwf dbyte02A0 219F M call writeb writex SOCKET_CONFIGURATION,SOCKET_TCP_SERVER_MODE02A1 3022 M movlw 0x2202A2 008D M movwf address02A3 3006 M movlw 0x0602A4 008E M movwf dbyte02A5 219F M call writeb writex SOCKET_ACTIVATE_REG,102A6 3024 M movlw 0x2402A7 008D M movwf address02A8 3001 M movlw 102A9 008E M movwf dbyte02AA 219F M call writeb

Listing 1 —When it comes to web service, it’s much easier to give than receive. To create the page, the PICjust spits out hardwired HTML (a). Otherwise, the software mainly just talks to the ’7600A with register accessmacros (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 SYN

x

rcv SYN, ACK

snd 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 TCBsnd SYN

Figure 3 —As this diagram, duplicated fromthe original 1981 Request For Comment(RFC793) shows, babysitting TCP isn’teasy. Don’t worry, the ’7600A handles allthe details. If you’re curious, find out whatstate you’re currently in by checking theTCP State field in register 0x23.

Page 67: CIRCUIT CELLAR - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

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

CIRCUIT CELLAR Test Your EQProblem 1—The circuit shown in the figure is builton a standard FR-4 PCB. It is mounted in a NEMAenclosure on a factory floor. The temperature inthe NEMA enclosure is 30oC. The thermocouple,an E-type, is mounted on the housing of a three-phase synchronous motor. The motor housing is75oC.

The IA’s offset voltage is a +125 µV. The IA’sintended gain is 1000 V/V, but there is a 2% gainerror that produces an actual gain of 1020. Assumethe E-type thermocouple is linear and has tempera-ture coefficient of 60 µV/oC. What is the outputvoltage of the IA?

Problem 3—Can you rewrite this function to significantly increaseits speed, without changing the basic algorithm?

Problem 2—Given the same pressure andtemperature conditions, is a cubic meter ofhumid air more or less dense than a cubicmeter 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 month, TestYour EQ presents some basic engineering problems for you to test your engineering quotient. What’s your 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 Z-World.You may contact the quizmasters at [email protected].

complexity. The HTML for the homepage (stored in the PIC’s code memory)chews up nearly half the space asshown in Listing 1a, and a significantportion of the code handles routinetasks such as macros to bit-bang readand write ’7600A registers.

The guts of the server is less than100 lines of real code, not countingmacro 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 offthe shelf, which opens the door forspecialized applications and garageshops that would never be able tojustify an ASIC.

Also, I like the idea of stickingwith PPP and TCP/IP and leaving thedecisions about higher level servicesto be determined by the needs of spe-

cific applications. I suspect time willshow this to be the right decision.Few customers need all the protocolswith all the trimmings, and most willbe glad they don’t have to pay forfeatures they don’t need.

I expect the ’7600A to spawn anexplosion of embedded ’Net gadgetsbecause it makes networking simpleand inexpensive, which it reallywasn’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 weren’t contemplat-ing putting it on the ’Net, better thinkagain anyway because the ’7600Amakes it real easy for you, and foryour competitors. I

Tom Cantrell has been working onchip, board, and systems design andmarketing in Silicon Valley for morethan ten years. You may reach him bye-mail at [email protected], by telephone at (510) 657-0264,or by fax at (510) 657-5441.

REFERENCES[1] Stanford University Wearable

Computing Lab, Information onembedding Linux, www.wearables.stanford.edu

[2] Information about IA OpenNetworking Alliance, www.iaopennetworking.com

SOURCESiChipiReady Corp.(408) 330-9450Fax: (408) 330-9451www.ireadyco.com

Seiko Instruments, Inc.Semiconductor Products Group(408) 433-3208Fax: (408) 433-3214www.seiko-usa-ecd.com/intcir/

html/whatsnew

NET+ARMNETsilicon, Inc.(781) 647-1234Fax: (781) 893-1338www.netsilicon.com

void bbs (int *numbers, int count)

int i, j, temp;

for /9i=o; i<count; i++)

for (j=count-1; j>0; j--)

if (numbers[j-1] > numbers[j])

temp = numbers[j-1];numbers[j-1] = numbers[j];numbers[j] = temp;

Problem 4—What does this circuit do?

Cold Junction

x1000

+

_Ref

AD620

Vout

+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 - s1.nonlinear.irs1.nonlinear.ir/epublish/magazine/Circuit_Cellar/Circuit Cellar... · limitations of the standard remote control. His ’16F84-based IR remote puts

96 Issue 111 October 1999 CIRCUIT CELLAR ®

PRIORITY INTERRUPT

[email protected]

Spreading the Wealth of Knowledge

i ’d like to say Circuit 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 around Circuit 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 of Circuit 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 printf 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 of Circuit 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 continuing Circuit Cellar message. Students, regular subscribers, and Internettechies can now enjoy even more applications each month through Circuit 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 on Circuit 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.

Finally, our motto says this is a magazine by engineers, for engineers. I contend that engineers aren’t just born. They are createdthrough a process of technical understanding. The really smart ones typically choose a route around all that trial and error and tend tohang out at Circuit Cellar where we like to be the somebody who just “tells you.”