E MBEDDED

PC CIRCUIT MONTHLY SECTION CELLARINK®

T H E C O M P U T E R A P P L I C A T I O N S J O U R N A L # 9 5 J U N E 1 9 9 8 GRAPHICS AND VIDEO Steve & Jeff Turbocharge a Security System

Wearable Multimedia

Designing Low-Power Systems

HTML and Hand-Held Devices

$3.95 U.S. $4.95 Canada TASK MANAGER

A Mind is a Terrible Thing... INK®

ow often do you get the opportunity to T H E C O M P U T E R A P P L I C A T I O N S J O U R N A L influence and shape tomorrow’s design EDITORIAL DIRECTOR/PUBLISHER ASSOCIATE PUBLISHER h engineers? If you’re involved in education, you’re Steve Ciarcia Sue (Hodge) Skolnick already there. I’m not talking to you. I’m talking to the engineers who sit in a lab or in front of a computer all day EDITOR-IN-CHIEF CIRCULATION MANAGER Ken Davidson Rose Mansella and whose community involvement may extend to playing softball with the town’s rec program. MANAGING EDITOR BUSINESS MANAGER One of our local universities (Eastern Connecticut State University) is Janice Hughes Jeannette Walters exploring the possibility of building upon their already-established computer TECHNICAL EDITOR ART DIRECTOR science program by adding one or more new majors and/or minors. One of Elizabeth Laurençot KC Zienka the steps school officials are taking is to get feedback from the local community about what programs should be offered and how they should be WEST COAST EDITOR ENGINEERING STAFF Tom Cantrell Jeff Bachiochi structured. The Computer Science Advisory Board asked Circuit Cellar to select a representative to join the group, and I was elected. Other members CONTRIBUTING EDITORS PRODUCTION STAFF include representatives from insurance companies, computer vendors, Ingo Cyliax John Gorsky primary and secondary schools, community colleges, and nearby nationally Fred Eady James Soussounis Rick Lehrbaum known universities. At our first meeting last night, I was amazed at how well such a NEW PRODUCTS EDITOR diverse group could work together to discuss a common goal: what can we Harv Weiner offer today’s college students to best prepare them for the changing world Cover photograph Ron Meadows – Meadows Marketing of MIS and computer engineering. Being able to tap into my own educa- PRINTED IN THE UNITED STATES tional background coupled with over a decade of work experience, I hope ADVERTISING I’m able to offer some useful feedback and suggestions in the coming ADVERTISING SALES REPRESENTATIVE months. Bobbi Yush Fax: (860) 871-0411 As a magazine, I like to think we have some influence over (860) 872-3064 E-mail: [email protected] tomorrow’s engineers as well. Many dyed-in-the-wool engineers begin ADVERTISING COORDINATOR experimenting with computers and electronics long before entering college. Valerie Luster Fax: (860) 871-0411 We have many readers who fit that category and who benefit from articles (860) 875-2199 E-mail: [email protected] written by engineers in the field. We also have our college program in which CONTACTING CIRCUIT CELLAR INK we supply professors with free copies of the magazine for all the students SUBSCRIPTIONS: in their engineering classes. INFORMATION: www.circuitcellar.com or [email protected] TO SUBSCRIBE: (800) 269-6301 or via our editorial offices: (860) 875-2199 So what’s my point? I want your help. We’ve been doing some work GENERAL INFORMATION: on our Web site, and are going to start offering perks to subscribers. Among TELEPHONE: (860) 875-2199 FAX: (860) 871-0411 those will be short application notes. If you have a favorite tip or technique INTERNET: [email protected], [email protected], or www.circuitcellar.com EDITORIAL OFFICES: Editor, Circuit Cellar INK, 4 Park St., Vernon, CT 06066 that you’d like to share, send it along and perhaps we can use it on the AUTHOR CONTACT: Web site. Our published articles are a technical source for these college E-MAIL: Author addresses (when available) included at the end of each article. students. Supplemental application notes and technical tips can only add to ARTICLE FILES: ftp.circuitcellar.com their total understanding. For information on authorized reprints of articles, At the same time, I want to encourage you to become involved in your contact Jeannette Walters (860) 875-2199. local school system. Students need to be exposed to computers as early CIRCUIT CELLAR INK®, THE COMPUTER APPLICATIONS JOURNAL (ISSN 0896-8985) is published monthly by as possible if they are going to come out ahead in today’s high-tech Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at society. Teachers have enough to do without having to figure out what’s 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 wrong with a PC’s configuration or why they can’t see the server on the possessions $39, Canada/Mexico $55, all other countries $85. All subscription orders payable in U.S. funds network. Our readers possess an incredible wealth of computer knowledge, 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 INK Subscriptions, and just a fraction of that applied to the schools could benefit dozens of P.O. Box 698, Holmes, PA 19043-9613 or call (800) 269-6301. young minds. Postmaster: Send address changes to Circuit Cellar INK, Circulation Dept., P.O. Box 698, Holmes, PA 19043-9613.

I look forward to continued work on the Advisory Board. And when my Circuit Cellar INK® makes no warranties and assumes no responsibility or liability of any kind for errors in these oldest daughter starts kindergarten in a few months, I plan to check with her programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in school to see if I can do anything to help. the quality and condition of materials and workmanship of reader-assembled projects, Circuit Cellar INK® disclaims any responsiblity for the safe and proper function of reader-assembled projects based upon or from plans, descriptions, or information published in Circuit Cellar INK®. Entire contents copyright © 1998 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar INK is a registered trademark of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit [email protected] Cellar Inc. is prohibited.

2 Issue 95 June 1998 Circuit Cellar INK® Gotcha! 11 Alarming the Alarm System Steve Ciarcia & Jeff Bachiochi

WearCam: Personal Imaging System 18 Steve Mann Design Embedded Systems for Low Power 26 Brian Kurkoski Design98—PIC of the Lot 33 Janice Hughes

Digital Attenuators 68 Brian Millier

I MicroSeries 74 FreeDOS and the Embedded Developer Task Manager 2 Part 1: Kernel Design Ken Davidson Pat Villani A Mind is a Terrible Thing...

I Silicon Update Reader I/O 80 Fabulous ’51s 6 Tom Cantrell New Product News 8 edited by Harv Weiner INSIDE Advertiser’s Index 65 Priority 96 Steve Ciarcia Darwin Couldn’t Have ISSUE Done Better

38 Nouveau PC edited by Harv Weiner PC 9595 41 Building Web-Enabled Mobile Devices Greg Bergsma 48 ’ Processor Survey Part 1: ’386-Class Embedded CPUs Pascal Dornier

54 RPC Real-Time PC Multimedia in Real Time Ingo Cyliax 61 APC Applied PCs A New View MBEDDED Part 2: Data Acquisition with Virtual Instruments www.circuitcellar.com E Fred Eady ★June’s Password is Gotcha★

Circuit Cellar INK® Issue 95 June 1998 3 READER I/O

MORE THAN JUST THE BOTTOM LINE • Unix man pages used to have a section on bugs, which I enjoyed Steve’s April Priority Interrupt (“What You was more of a comment on how to do it right the next Get with a Handshake,” INK 93). Over the years I’ve time. But, no one admits to bugs anymore, do they? been a distributor, I’ve seen quite a few changes as well. The most interesting trend is customer reliance on Second, consider year-2000 problems in embedded pre-sales engineering design support. The problems processors. I can’t remember when the common engi- arise when the purchasing department is tasked only neer has had to think so much about project liability, with component cost and cannot justify higher cost, when fear-mongers have predicted so much doom and regardless of the support offered. This is where the fear gloom, and when there has been so little risk assessment. of catalog sales companies comes into play. Sure, there will be problems come Jan. 1, 2000 and I look forward to several more years of change in our Feb. 29, 2000. That’s a given. What I don’t see is a good industry. solid risk assessment in the popular press. Maybe crying wolf sells more paper, or vendors and professional service Chris Kracht providers see an opportunity to make some big bucks. Hamilton Hallmark I’m looking forward to the day INK runs an April Fools’ [email protected] article. Steve could always write it under a pseudonym.

Larry Pajakowski Gurnee, IL MICROPROCESSORS IN TOASTERS? YES! As an engineer in charge of designing electronic controls for appliances, I read Steve’s May editorial (“Design98—A Marketer’s PICnic,” INK 94) with glee. STOP THE PRESSES Yes, in answer to his question, there are plenty of Thanks for Jeff’s interesting article, “Proprietary toasters that use microprocessors. Rival has had one on Serial Protocols” (INK 92). I’d like to comment on one the market for two years, Proctor-Silex has one, and so small point. He says a stop bit is used to “signify the do many others. I’m working on a PIC-based toaster- end of the single character transmission”. Not so. oven controller, and the microprocessor design ends up As far as I understand it, a stop bit doesn’t signify being cheaper than a thermostat, because we can anything. Its presence (an electrical “high”) merely eliminate some peripheral components. ensures that, whatever the state of the preceding data or I put a microprocessor into a steam iron to imple- parity bit, there is always a high-to-low transition for ment a new automatic shut-off mechanism (patent the start bit of the next data byte. This transition noti- pending). That’s the least complex appliance I know of fies the receiver that a new data byte transmission is that uses a micro. about to begin.

Lawrence Lile Terry Koh [email protected] Singapore

What I meant was the end (or last part) of the data words protocol. You are correct. Without the stop, we AND HOW MUCH MORE HAS CHANGED? could only see a start bit about 50% of the time. Steve’s editorial about manufactures reps and dis- tributors (“What You Get with a Handshake,” INK 93) Jeff Bachiochi reminded me of two other changes worthy of note. First is humor—or rather, where has it gone? Com- mercial publications have “matured” so much, they’re basically humorless. Remember what used to be: PICARO CORRECTION AND UPDATE Figure 1 in “Picaro” (INK 93, p. 31) incorrectly shows • the Signetics WOM R9–R16 as 10 kΩ. These resistors should all be 1 kΩ. • Steve’s April article in BYTE one year when he went Also, an updated version (April 14, 1998) of the to “raid” the fridge. The word picture was just great. Picaro software is available on INK’s Web site.

6 Issue 95 June 1998 Circuit Cellar INK® NEW PRODUCT NEWS Edited by Harv Weiner MULTIPLE VIDEO DISPLAY UNIT The SuperView 500 is an advanced display input system that combines up to 10 computer screens and/or video signals on a single monitor or projector. It is compatible with virtually all PCs, workstations, and any monitor or data display projector up to 1600 × 1200 resolution. The SuperView 500 was developed for sophisticated applica- tions where multiple video and computer sources must be displayed simultaneously, such as operations centers, con- trol rooms, and teleconferencing and training facilities. The SuperView 500 is an external stand-alone peripheral that connects between the host computer and display. It combines the multiple signals downstream of the com- puter so it doesn’t burden the host CPU. Input signals may ELECTRONIC COMPASS MODULE come from virtually any source like NTSC, PAL, S-Video, The Navifinder-200 electronic compass module FLIR, or any computer signal up to 1280 × 1024 pixels. is ideal for use in RVs, snowmobiles, motorcycles, Video and computer inputs are shown as windows on the boats, and van/truck conversions. It can easily be main screen. All windows can be positioned, scaled from mounted in a dash or enclosed in a housing. This icon size to full screen, overlaid with computer graphics, module uses advanced calibration algorithms that or overlapped with other windows. Also, each input can be discriminate between the earth’s magnetic field panned and zoomed to emphasize areas of interest. and those generated externally, such as from the SuperView 500 supports software control to manipulate metal and electronics in a vehicle. By electroni- the video windows. X.TV software provides full integration cally compensating for these external factors, the under X Windows, and W.TV software for /NT. Navifinder-200 can provide highly accurate com- Pricing starts at $10,990 for a camera with two NTSC/ pass readings in all vehicle environments. PAL inputs. Additional NTSC/PAL inputs and RGB/FLIR The Navifinder-200 is easily wired to any 12-V inputs are available. battery supply and ignition system or externally mounted on/off switch and battery. It outputs the RGB Spectrum compass heading on a LCD in 5° numeric digits 950 Marina Village Pkwy. and eight cardinal points (N, NE, E, SE, etc.), with Alameda, CA 94501 an accuracy of 2°. To provide different viewing (510) 814-7000 angles, the Navifinder-200 can be mounted with Fax: (510) 814-7026 up to ±30° of tilt without losing accuracy. www.rgb.com #501 The Navifinder-200 uses Precision Naviga- tion’s patented Magneto-Inductive magnetic sen- sor technology to provide high sensitivity, a large dynamic range, low power consumption, and a low price. This compass module sells for $75 in single units and $32 in quantities of 1000.

Precision Navigation, Inc. 1235 Pear Ave., Ste. 111 Mountain View, CA 94043 (650) 962-8777 Fax: (650) 962-8776 www.precisionnav.com

#502

8 Issue 95 June 1998 Circuit Cellar INK® NEW PRODUCT NEWS

PCI CONTROLLER DEVELOPMENT KIT A new Motorola MPC860 development kit simplifies bus. The dual-mode caching controller enables the design efforts to use the Anchor Chips AN3041Q CO- controller’s internal memory to easily interface be- MEM PCI controller to interface between the PCI bus tween the local processor, PCI bus, and host memory. and the Motorola MPC860 family of processors. The kit A design guide shows a step-by-step procedure for features a development board with an AN3041Q device developing a system with the AN3041Q. Other refer- interfaced without glue logic to the MPC860. The add- ence materials are provided in the kit to make a com- in card contains no onboard memory and plugs directly plete development package. into the PCI bus in a desktop PC. The cache memory in The Motorola MPC860 development kit sells for $495. the AN3041Q caches the local processor’s memory needs across the PCI bus to host memory. The designer Anchor Chips, Inc. defines how much host memory (up to 16 MB) is allo- 12396 World Trade Dr. cated to the MPC860 board through software. San Diego, CA 92128 The CO-MEM Mapper software, which runs on any (619) 613-7900 Windows-based PC, defines the MPC860’s memory Fax: (619) 676-6896 map and automatically configures and displays the www.anchorchips.com #503 AN3041Q’s internal registers. Once the AN3041Q is configured, the MPC860 processor can be released from reset to run the application. Map- per software contains debug tools to aid in the integration of the MPC860 processor and its application with the host system. The AN3041Q uses a highly intelligent cache- memory architecture instead of the FIFO/DMA architecture to provide a high-speed communi- cation interface from a local microprocessor or DSP to the PCI bus. It interfaces directly to most 8-, 16-, and 32-bit processors. The bus interface engine in the AN3041Q enables the local processor to have direct access to the PCI

NONCONTACT ULTRASONIC SENSOR The Senix ULTRA-30-VA noncontact ultrasonic This sensor has a resolution of 2 mm (0.078″) and sensor provides a 0–10-VDC output proportional to the accepts 15–30-VDC input. It connects easily with PLCs, measured distance to target materials. The analog out- motor drives, or other controls. put spans easily between any two distances in its 3–80″ The ULTRA-30-VA is designed for motion-control operating range. Packaged in a 30-mm threaded alumi- applications including the measurement of roll diameter num housing, the sensor fea- and free loop positions for the tures push-button operation to purpose of tension, speed, and/or simplify setup and eliminate diameter control. It’s ideally suited potentiometers, target status for medium-volume OEM machine indication to convey target range controls in the pulp and paper, and stability status, and stable printing, and converting industries. output under lost target condi- tions. It offers dual-range opera- Senix Corp. tion for optimum performance 52 Maple St. at different target ranges and a Bristol, VT 05443 user-selectable output response (802) 453-5522 filter for stability under noisy or Fax: (802) 453-2549 poor target conditions. www.senix.com #504

Circuit Cellar INK® Issue 95 June 1998 9 NEW PRODUCT NEWS REMOTE I/O MICRO CONTROLLER MODULE The Model HCON-1 remote I/O microcontroller J-Works, Inc. module accepts commands over the RS-485 serial 12328 Gladstone St., Ste. 4 bus to control output drivers and obtain inputs from Sylmar, CA 91342 quadrature encoders, temperature modules, and (818) 361-0787 • Fax: (818) 270-2413 switch inputs. High-current output drivers directly www.j-works.com #505 control up to 20 relays or LEDs. Applications include remote equipment control, home automation, temperature control, and remote relay control. Up to 256 Dallas DS1820 or DS1821 digital temperature inputs can be scanned over the single-wire interface. Key switching can be from a 5 × 5 switch matrix or 10 discrete inputs. ASCII or binary commands can be sent over the RS-485 interface at a data rate up to 19.2 kbps. The compact board measures 1.8″ × 2.7″. The supplied software includes sample inter- face code under Visual Basic, Visual C++, and ActiveX control. The Model HCON-1 sells for $119. CIARCIA’S FROM THE CIRCUIT CELLAR & BENCH

Steve Ciarcia Jeff Bachiochi Gotcha! Alarming the Alarm System

Alarm companies fall a little short if what you want is entry and exit printouts. Sure, they’ll do them. But only at $20 a pop—or the cost of a new system. So, what do you do? If you’re Steve and Jeff, you add a little electronic sleuthing to the system.

was just about As I ran for the car, I heard her yell, After the appropriate introductions, i ready to pack it in “Be careful…! Call me…!” we trooped into the building—they for the night when Like most businesses, we have a with their guns drawn and flashlights Jeannette called down commercial alarm system. The reason blazing. I don’t know why they didn’t the cellar stairs. isn’t as much to deter crime as it is to just turn on the lights, but they pre- “Steve, the alarm service is on the qualify for discount on insurance rates. ferred to search each room in the dark. phone. The alarm at the office just That’s the good news. I still don’t understand the tactic. went off! They called the police. Shall The bad news is that, because I live Maybe they presumed someone this I say you’re on the way to meet them?” closest to the office, I’m first on the dumb would invariably use tracer As I grabbed my coat and keys, I call list when the alarm goes off. I get ammo or something else that’s easy cast a quick glance back at Jeannette. to greet the police and walk around a to see in the dark. Needless to say, I Her expression said far more than any building with a lot of dark hiding places. waited until the lights were on before verbal exchange. There really aren’t a lot of options. roaming anywhere unescorted. The gist of it was that if anyone If you want the police to treat the call The results of the search were less was going to play hero tonight, it seriously, you better meet them there. than spectacular and somewhat embar- wasn’t going to be her. She’s happy to And, you also have to watch the false rassing. Apparently, workmen had left run a business with me, but gunslinger alarms. an outside door to the furnace room is definitely not in her job description. Everyone had a sense of humor unlocked and nobody checked it. There was a time when sharing the when someone set the alarm while Besides the lock, the door needs a “business experience” might have Ken was still working on the third 3½″ thick wooden bar across the inside prevailed, but after a real break-in at floor. Since then, the last one out is to keep it from opening. Of course, our office when the police actually supposed to page the building or check when someone leaves the door un- dragged a burglar out in handcuffs, she the parking lot. There has to be a bit locked and only puts in a standard 2 × decided this was one event she’d rather of seriousness. After all, the police did 4 (1¾″ thick) instead of the usual 4 × stay away from. Besides, anyone stupid nab somebody that one time. 4, the door can open almost 2″. Guess enough to break into a building at- As I pulled into the parking lot, the what happens when someone pulls on tached to a courthouse and surrounded lights from state and local police cruis- the door from outside? An unlocked by a half-dozen TV cameras probably ers greeted me. All I could think was, door is an embarrassing predicament. isn’t bright enough to listen to reason please, let them find Jeffery Dahmer Needless to say, I apologized pro- anyway. or someone, not another false alarm. fusely. It was a false alarm. If we’d

Circuit Cellar INK® Issue 95 June 1998 11 Domino2A count number, you might think “I suggest you install a new alarm 32-KB 32-KB they’re just down the block. Only system,” he answered matter-of-factly. Domino SRAM EEPROM Processor when you interrogate the auto- “Would a new system be better with ROM BASIC dialer or otherwise see where the than our present ten-year-old hard- call goes do you realize that your wired system?”

2 +5-V 2 I C Coprocessor personal monitoring can be 2000 “Well, sir,” he continued. (Subcon- 2 & Clock/Calendar Reg 2-Channel 12-bit ADC miles away. sciously, I noted that people generally

Serial Parallel I2C Our monitoring company was called me “sir” when they were trying +V I/O I/O Bus ADC Parallel I/O PWM at the other end of the state, but to sell me something. Sometime I’ll most large alarm companies deal have to test the financial limits of Figure 1—Domino2 is a small encapsulated controller with a built-in floating-point BASIC interpreter and 32 KB each of with centralized service monitors this theory. Do they start at $100, EEPROM and SRAM. that cover many states at the $500, $1000…?) “It would have the same time. Regardless of their latest technology and use wireless nabbed Charles Manson, wasting their location, aside from changes to sensors.” time wouldn’t be an issue. I probably the call list, they’re like talking to a “And after I replace the $2 battery could have even gotten away making brick! Their pat response is that you in every sensor each year, would it do police and donut-shop jokes. Under should call your installer. more than provide a contact closure the circumstances, however, my only They usually charge the installer a to an alarm horn and autodial a digital recourse was to thank them, tuck my flat rate based on a specific service code to the monitoring station like tail, and return to the car. level for all his customers. If he only the present one?” I already knew the I dialed the cell phone. When Jean- contracts for alarm calling and none answer. nette answered, I said in a disgusted of the monthly printed reports, it’s “It would use the latest technology tone, “Someone left the damn door tantamount to bringing the mountain to close the contact and autodial the open! The only thing worse would be to Mohammed to get one from the modem, sir…and we could get you if they didn’t set the alarm at all!” monitoring company. Yes, I could get one with a printer output.” Finally, he “Well, Steve, I wasn’t going to tell a report for a specific day—at $20 each! mentioned something we wanted! you, but I’ve had reports from the Calling the installer reminded me I continued, “Do you know if it’s a people who come in early that occa- again why we designed our own home- standard serial printer port? Do you sionally the alarm hasn’t been on.” control system. These people have no have a schematic?” Next morning, I called everyone vision at all. “Well, I’m not sure what it is, sir, with alarm codes together and asked “What would it take to get daily but I can supply you with the printer the pertinent who and when questions. I entry/exit reports?” I asked. (extra cost). There are never any sche- got back mostly blank stares, to be interpreted as, “Not me, man.” Given all the people with independent access to the build- ing, that was hardly reassuring. The obvious answer was the alarm company. We pay them $30 a month to monitor the system and call the appropriate people if the alarm goes off. When it was first installed, we got a monthly opening/closing report that listed the date, time, and access code (these days I suppose we’d call it a PIN) for every alarm set or reset. This was the obvious answer. Calling the alarm-monitor- ing service is an experience. They’re contracted by your alarm installer and not typi- cally selected by the alarm owner. And since they answer the phone “Monitoring station” and use the installer’s name once you give them your ac- Figure 2—This schematic shows the ASDL system and how it connects to the alarm signals.

12 Issue 95 June 1998 Circuit Cellar INK® matics of any equipment, sir. I guess The methodology is quite straight- they’re concerned about liability.” forward. Take a circuit that works the Liability, schmiliability. The only way you’d normally design it, throw reason there are no schematics is that away half the parts (or parts cost), and the alarm manufacturers don’t want then make it do all the same control competition. tasks. These are the guys who make a In the end, it’s just a cost decision. fine art of cycle-stealing, multiplexed “How much?” operation, and hairy-edge qualification. “Well, sir, if we do just the same as Want them to design your next medi- your present system and add the printer, cal product? probably about $3500–4000.” This unit was no exception. The I knew this “sir” thing was going user interface consisted of a 3 × 4 to cost me. “Thanks, I’ll have to get keypad with a green LED (ready), a red back to you.” LED (armed), and a single 7-segment My next stop was Jeff’s desk. LED display (zone). The keypad labels “Jeff, this alarm guy is nuts. You were 0–9, Door, and On/Off. Pressing can’t believe how much it costs for an any button makes an internal beeper alarm-code printout. Worse yet, it sound. Photo 1 shows a close up of only records successful entries. It the alarm’s keypad. can’t tell who punches in a bunch of Similar to the operation of most numbers, never actually sets the alarm, alarm systems, the user looks for a and then just walks out without check- green light indicating the system has ing. That’s the guy I want.” no open doors and punches in a four- I knew telling Jeff about such a digit code followed by the on/off but- ridiculous obstruction would be a ton. The alarm goes on, the red LED technical challenge he couldn’t refuse. lights, and you have about 45 s to They may not know how to produce a vacate the building. The process is daily event record, but somehow we reversed to shut off the alarm. would. We gathered up the ’scope and Jeff and I concluded the way for us headed for the furnace room and the to monitor entry and exit times and alarm-system controller box. codes was to attach a circuit in parallel There was nothing surprising about with this user interface and tap into the system. It was your standard ten- its communication with the system year-old Silent Knight alarm system. box. Punch in 6637 and On, and we’d Documentation was strictly at the log it to a printer. The only sticky installer level. Motion detectors and part was guessing where all these sensors connect to these terminals, signals were so we could tell which the alarm horn connects here, the key was pressed. phone line goes in here. The keypad in the entryway connects The PCB hardware included two to the system via an 11-wire parallel microcontrollers that shared the con- cable. The 3 × 4 keypad has four rows trol tasks. Because they had house labeled 1–3, 4–6, 7–9, and Door, 0, and numbers, Jeff and I concluded they On/Off. were probably ROM-programmed Electrically, we determined that 8051-family devices. And because it the keys are scanned in two separate was ROM coded, we didn’t have a groups of six. Two opposite and alter- prayer of changing any internal opera- nating signals drive the two groups. tion. The best we could hope to do Pressing none of the keys results in a was monitor the external signals. logic 0 on the three column inputs It would have been great if the back at the system board. alarm designers had taken a traditional Pressing a key diode ORs one of the engineering approach. Even a predict- phases with one or more of the column able approach would have been wel- inputs, like this: 1 = 001, 2 = 010, 3 = comed. In the world of high-volume 011. A 7 also creates the 001 combi- consumer-quality electronics however, nation but in step with the opposite nothing works the way you expect it phase. The system knows which key to, and “cute” is a term frequently is pressed based on the column inputs used to describe the design technique. and the phase of the input signal.

Circuit Cellar INK® Issue 95 June 1998 13 Other signals to the entry panel with a built-in floating-point BASIC lines, two phase outputs, and on/off enable the red or green LEDs and drive a interpreter and 32 KB each of EEPROM button are read anytime there’s an piezo beeper when any key is pressed. and SRAM. Best of all, it contains a interrupt. Together, they determine All signals are at the 12-V level. serial port, lots of parallel I/O, and a the physical key combination. real-time clock. Normal entry and exit profiles run PACKAGED SOLUTION Even if you don’t have a ten-year- a total of 10 key presses a day. This Jeff and I now knew there were old alarm, I’m sure you’ll find that plus a 7-byte time and date stamp some logical signals we could monitor. our method of solving the problem amounts to fewer than 20 bytes of The next task was to decide what provides some interesting examples of data-logging space required per day. kind of data-acquisition system we using BASIC-52 in control applications. Our plan isn’t to check this thing had to configure. But unlike our light- daily but to have a record of events ning device (“Ground Zero,” INK 90), ALARM-SYSTEM DATA LOGGER available when we need it. If we have this wasn’t just an illustrative magazine Figure 2 is the schematic of the a good chunk of data storage space project. I wanted to use this thing. alarm-system data logger (ASDL). The available, how often we dump the We could have used anything from circuitry was added to Domino’s proto1 records will never really be an issue. a PIC to a full-blown PC as the hard- board, as shown in Photo 2. The first Six months of data fits easily in less ware. Our logging system needed a task was mating the 12-V level alarm than 5 KB of memory. We have about processor board to acquire and analyze signals with Domino’s TTL input levels. 24 KB available. the data, a real-time clock/calendar to There are lots of ways to do this, Program development started with time stamp the entries, an LCD to but one cute way is to use MC1489 writing the time and date to the LCD. view records, a keypad to direct the RS-232 input level shifters. These Instead of using a couple I2C peripheral logger’s activity, and a printer interface inexpensive inverters can withstand chips to connect the 4 × 20 LCD and for making hardcopies on command. ± 30-V inputs while interfacing directly 4 × 6 keypad as typically described for Beyond the strict hardware necessity, with TTL on the output side. Six Domino, Jeff chose to minimize exter- system selection is always a tradeoff keypad lines connect to the processor. nal hardware and scan the command of competing ideals: The next detail is determining keypad in software. when a key is pressed. We had two Using this number of I/O bits for • time (getting this much software alternatives. We could create a falling- the keypad necessitated using the done quickly enough to meet a maga- edge key-press interrupt by NORing LCD in 4-bit mode rather than the zine deadline typically rules out the three column inputs together. Or, typical 8-bit parallel interface. The assembly language) we could take advantage of the fact 4-bit mode requires two nibble writes • I/O capability (obviously, we needed that pressing any key caused the beeper to the LCD for each printed character, a serial port and a lot of parallel I/O) to sound. which entails eight physical operations • speed (just how fast does this thing Ultimately, Jeff chose to use the for each character—set up the control need to be anyway?) signal applied to the beeper as a key- register, raise the strobe line, set up • cost (are we making a few or is it a press interrupt. The three column the data register, drop the strobe line. volume-production device?) The process repeats for the sec- • political bias (some designers ond data nibble. will jam in a PC even if it can Alarm Cabinet Alarm-System Data Logger The program executes a be done on a PIC) AC short initialization routine and 12-V 12-V 12-V Gel Cell then prints day of the week Charger Gel Cell This analysis pretty much fits (DOW), month/day/year, and half the board ads in INK. Fortu- Silent-Knight hour/minute/second on the nately, I get to apply a little Alarm-System LCD. Using the row and column Board 12-V political bias of my own. Domino2 Serial positioning capability of the Printer While there’s a little fancy Proto-1 PCB LCD (a control register routine), footwork in the interrupt rou- only new data needs to be up- tines, most of the software is a LCD dated. This makes a great idle lot of text shuffling among the screen that also indicates the peripherals (it’s easy for the guy Zone Ready Armed system is running. who doesn’t write the software 123 If the displayed time and to say stuff like this). When we 456 date is incorrect, as it would be looked at the requirements, it 789 on initial powerup, the user seemed like a perfect application 0 enters the present DOW, month, for a Domino—or more precisely, Alarm System Keypad day, year, hour, minute, and a Domino2. second. Maintaining the time Figure 3—The ASDL attaches in parallel with the existing alarm keypad. As Figure 1 shows, Domino2 The Domino2-based monitor program registers and records keypad during a power outage is a is a small encapsulated controller activity and outputs the data to an LCD and printer on command. simple matter of adding a 4.5-V

14 Issue 95 June 1998 Circuit Cellar INK® back-up battery to the To ensure the sample is real-time clock. valid, the program checks Since the alarm system whether there is a high is normally battery-backed level on at least one col- and may be needed during umn input line. If none of a power outage, we de- the first three bits are cided to battery-back the high, we assume it’s the whole Domino2 circuit. wrong phase and take Besides keeping the RTC another sample. Once alive, it maintains any there is a valid sample, collected data that hasn’t the row driver levels (in- been printed yet. Figure 3 dicating the two phases) gives an overall view of can be compared with the how the complete system column inputs to deter- was integrated. Photo 1—The alarm system PIN is entered via a keypad. The ASDL system monitors mine which of the 12 and records the time and date of all key presses. keys was pressed. FANCY FOOTWORK ONEX1 is triggered by a high-to-low Before leaving the interrupt routine, As I mentioned, it’s easy to say it’s transition on Domino’s INT1 input there are two more tasks. First, save just a matter of software when you don’t pin. Obviously, it should be reserved the key-press code into the data-log- have to write it yourself. One of the for a high-priority function. Listing 1 ging buffer and increment the buffer more challenging aspects of the software illustrates the high points. pointer. If the on/off key was pressed, was catching the key presses while The piezo beeper output connects a time/date stamp is added to the log. doing all the other system functions. to INT1. When ONEX1 is triggered, the Finally, we need to make sure the This task was accomplished via the routine samples the I/O port where all physical key-press action has ended BASIC-52 ONEX1 command. This the row and column data is connected (to prevent interrupt on the same key interrupt command temporarily redi- to the Domino. This beeper interrupt press). This is accomplished by re- rects the normal program flow to a can occur during either phase of the peatedly sampling the port and look- special subroutine. row drivers. ing for invalid data (columns all low)

Circuit Cellar INK® Issue 95 June 1998 15 on both phases of the row The final menu selections driver outputs. When RETI is enable the user to clear all executed, the program re- data from the data buffer sumes where it left off. and return from the menu screen to the idle screen GETTING THE GOODS (displaying time/date). Displaying and dumping Since the capturing and the stored data log is a second- logging of alarm codes is a ary function chosen from the security risk, it would be command menu. The ASDL foolish not to try to prevent LCD can show a command unauthorized use. Accessing list, the time and date, or the the menu screen shouldn’t data. The data is printed to be open to just anyone. the LCD in blocks. Any ASDL entry prompts When the log is dumped, the user for a PIN. An incor- all the blocks up to and in- rect entry simply returns to cluding the present time and the idle screen. date are dumped. We didn’t We also specifically chose see the necessity for indi- to store the data log in SRAM vidual date interrogation. Photo 2—The prototype ASDL sytem is physically assembled using a Domino rather than EEPROM. If the You want the data log? development board with an LCD and keypad attached. Domino is removed from Here’s everything, a block at a time. 5″ × 5″ × 3″) next to the Domino, so a the system, the data log disappears. While the data is being sent to the hardcopy of the data could be printed LCD, it is also sent out the console and retained if necessary. GOTCHA serial port. Although this could be A short pause between each block While solving the problem this connected to a PC and logged to a file, lets the printer keep up with the data way gave me the satisfaction of not Jeff mounted a plain-paper 12-VDC– and provides time to study each block having to buy more useless equipment powered serial printer (measures only on the LCD before the next display. from an alarm company, it turns out there was no better alternative. The monitoring station and a com- mercial alarm printer could only give me a list of successful alarm operation. But, my major irritation was with people who didn’t look for a green LED (indicating that the building was clear) before blindly punching in a code (that the alarm doesn’t accept) and blowing out the door. The ASDL stores every key pressed. It only adds the time/date stamp when the on/off key is pressed. If the alarm isn’t set, a quick review of the record should show what code was being entered, even if unsuccessfully. All of our work may have been in vain. We haven’t had any false alarms, and interestingly, there haven’t been any mornings with an unset alarm. Either everyone has become edu- cated by involvement in publishing this article, or seeing Jeff and me con- stantly playing with the alarm system has made them aware that something is going on. Regardless, they seem to recognize the seriousness of it all. Jeff and I just have to be careful that we don’t let on that we really have fun. I

16 Issue 95 June 1998 Circuit Cellar INK® Listing 1—The highest priority was given to the monitoring of the alarm keypad’s key presses. The BASIC ONEX1 command branches to line 20000 to decode a key press and log it.

120 ONEX1 20000 : REM CAPTURE ALARM KEY PRESSED ... 20000 REM INTERRUPT ROUTINE - EXTERNAL BUTTON PUSHED 20010 LED=PORT1.XOR.255 : REM INVERT DATA 20020 IF (LED.AND.07H)=0 THEN GOTO 20010 : REM CHECK FOR DATA 20025 LED=LED.AND.3FH 20026 BUT=LED.AND.37H : REM MASK OFF ALL BUT BUTTON INFO 20030 IF BUT=15H THEN GOTO 21000 : REM BUTTON 0 20035 IF BUT=21H THEN GOTO 21100 : REM BUTTON 1 20040 IF BUT=22H THEN GOTO 21200 : REM BUTTON 2 20045 IF BUT=23H THEN GOTO 21300 : REM BUTTON 3 20050 IF BUT=24H THEN GOTO 21400 : REM BUTTON 4 20055 IF BUT=25H THEN GOTO 21500 : REM BUTTON 5 20060 IF BUT=26H THEN GOTO 21600 : REM BUTTON 6 20065 IF BUT=11H THEN GOTO 21700 : REM BUTTON 7 20070 IF BUT=12H THEN GOTO 21800 : REM BUTTON 8 20075 IF BUT=13H THEN GOTO 21900 : REM BUTTON 9 20080 IF BUT=14H THEN GOTO 22000 : REM BUTTON DOOR 20085 IF BUT=16H THEN GOTO 22100 : REM BUTTON ARM/DISARM 20090 RETI 20100 Z=Z+1 : XBY(Z)=0FFH : REM TAG END OF BLOCK 20110 LED=PORT1.XOR.255 20120 IF (LED.AND.17H)<>10H THEN 20110 : REM WAIT FOR NO DATA 20130 LED=PORT1.XOR.255 20140 IF (LED.AND.27H)<>20H THEN 20130 : REM WAIT FOR NO DATA 20190 RETI 21000 XBY(Z)=30H 21010 GOTO 20100 ... 22000 XBY(Z)=ASC(D) 22010 GOTO 20100 22100 REM ARMED? 22101 IF (LED.AND.08H)=0 THEN GOTO 22200 22110 XBY(Z)=ASC(N) : REM NOT ARMED 22111 GOSUB 23000 22120 GOTO 20100 22200 XBY(Z)=ASC(A) : REM ARMED 22201 GOSUB 23000 22220 GOTO 20100 23000 REM STICK IN TIME/DATE STAMP 23005 Z=Z+1 23006 XBY(Z)=0AAH 23010 Z=Z+1 23011 XBY(Z)=MTH ... 23060 Z=Z+1 23061 XBY(Z)=SEC 23080 RETURN

Steve Ciarcia is an electronics engi- SOURCE neer and computer consultant with experience in process control, digital Domino2 design, and product development. Micromint, Inc. You may reach him at steve.ciarcia@ 4 Park St. circuitcellar.com. Vernon, CT 06066 (860) 871-6170 Jeff Bachiochi (pronounced“BAH-key- Fax: (860) 872-2204 AH-key”) is an electrical engineer on www.micromint.com Circuit Cellar INK’s engineering staff. His background includes product I R S design and manufacturing. He may 401 Very Useful be reached at jeff.bachiochi@circuit 402 Moderately Useful cellar.com. 403 Not Useful

Circuit Cellar INK® Issue 95 June 1998 17 ders—and it is already outfitted with FEATURE two very good imaging devices. EMBODYING HI ARTICLE WearComp, which originated in the 1970s as a tool for exploring vision, offers a new form of human-computer interaction in which the computer Steve Mann exists within the user’s personal space, is controlled by the wearer, and has both operational and interactional constancy (i.e., is always on, ready, and accessible). WearComp typically consists of a body-worn computer system, a visual WearCam: Personal display over one or both eyes with text and graphics display capability, and an input device with five or more push- Imaging System button switches that may be operated by one hand. Other input devices may include microphones and one or more video cameras positioned to view the same subject matter the wearer sees. Because the apparatus is worn on the body, input devices often include con- achine vision and tacts that touch the body to determine m artificial intelligence skin conductivity or heart rate, as well WearCam is a (AI) are problems that as various transducers such as a respi- have challenged research- ration monitor. personal imaging ers for decades. Many easy tasks for To get a better feel for HI, consider humans can only be done by computers this scenario: You’re walking home system that lets you in carefully controlled settings, if at all. wearing your WearCam. It’s measuring Rather than emulating human capa- your heart rate, respiration, footstep capture events as if bilities in a computer, an alternative rate, and so on. (Dividing heart rate by framework, humanistic intelligence (HI), footstep rate serves as a visual saliency the camera sits creates a synergy between human and index for controlling frame rate of machine in which the human is part of video capture and transmission.) behind your eyes. It the feedback loop of a computational Suddenly, an assailant wielding a process, as illustrated in Figure 1. sawed-off shotgun demands cash. You can even manipulate Instead of implementing an image- see him appear on the viewfinder con- processing neural network inside a com- cealed inside your glasses, and the its shots—zooming puter, we need to realize we have a good computer, through intelligent signal in and out. The real neural network sitting on our shoul- processing, recognizes the increase in world gets equal footing with the virtual.

Photo 1—Multiple push-button switches (e.g., microswitches in this data-entry device from the 1970s and early 1980s) are pressed in different combinations to issue different commands.

18 Issue 95 June 1998 Circuit Cellar INK® heart rate and decrease in footsteps WearComp3 was much and sends high-resolution image data less capable than WearComp2. Constant Attentive Computer Communicative to remote locations at maximal frame However, it was smaller and Observable rate. Friends and relatives are automati- could be better integrated cally summoned to see the situation. into clothing (rather than Controllable Human Essentially, the computer presents being worn like a backpack). Unmonopolizing Unrestrictive the image on its viewfinder screen and It also marked the beginning measures the human’s response to that of using the chest area as a Personal image. No high-level machine vision or display space others could see. Figure 1—A camera that embodies humanistic intelligence (HI) AI is used. Instead, the human brain This design choice arose out uses the human operator for its intelligence rather than trying to and human visual system are inserted of the fact that WearComp3 emulate human intelligence directly. Within the HI framework, into the feedback loop of a process put more emphasis on com- camera intelligence arises as a result of the existence of the human in the feedback loop of some computational process. In the case of that determines whether or not the puter-supported collaborative WearCam, the camera ceases to be intelligent as soon as it is no situation is dangerous. photography than on the longer being worn. individual spirit WearComp2 BUILDING WEARCOMP had been based on. tic work. I could keep my eyes on the Most modern cameras contain some WearComp4 returned to a fully work while making measurements. computational capability. The compu- functional general-purpose computer, Isolation is important. You don’t want tational capability in WearCam—Wear- as did WearComp5, which was a much high voltage going through your body Comp—is more than just a micro for more powerful image-processing work- when you display the signal on a high- calculating exposure. WearComp is a station running the OS with X- voltage wire and the ground clip pops off. complete Internet-connected multi- windows (XFree86) and using a PCMCIA media computer system running a video-capture device. BATTERIES Unix-like operating system. In this article, I describe WearComp6 Early versions of WearComp used WearCam is for a technical breed that because it doesn’t require any special lead-acid batteries, whereas later (mid wants the challenge of becoming a nonstandard devices or custom ASICs. 1980s) versions used NiCd batteries. camera and experiencing life through the But, there’s also a WearComp7, a covert For constant operation, I generally screen of an image-processing computer. version of wearable wireless webcam use at least two 12-V batteries. These WearCam6/WearComp6 can be easily that was first completed in 1995, that batteries typically have lugs that con- built from off-the-shelf components. looks like ordinary glasses and clothing. nect to crimp-on connectors. Obviously, since this system is in And, a recently completed Wear- However, in wearable applications, contact with your body, you need to Comp8, a covert version of wearable the lugs are easily broken off or shorted take the utmost care to protect your- wireless webcam, embodies a new kind by materials you might carry in a pocket self from physical risk or danger by of mediated-reality experience with with the batteries. To avoid fire and following careful engineering prac- enough visual acuity so you can engage explosion hazards, I solder wires right tices. As well, extensive wearing of in fast-action activities (e.g., playing to the lugs and insulate them well. the device could cause eye damage as sports) while looking through the Be careful to place a fuse right next well as damage from RF. viewfinder and recording the experience. to one of the lugs of the battery, not in the cord going to the battery. Otherwise, BRIEF HISTORY BUILDING WEARCOMP6 if something wears through the insu- Table 1 gives you a look at Wear- Most of the research issues includ- lation on the cord upstream of the Comp’s evolution, including the micro- ing the mathematical framework for fuse, you’ve got a problem. processor used and its expanding text personal imaging and mediated reality The best fuses are the automotive and graphics capabilities. (MR) are described at . Here I simply describe a fuse right near the positive lug, as specifically designed for controlling how to build WearComp6. Go to the close as possible. experimental body-worn photographic Web site for details on programming and One lug of the fuse can be soldered lighting equipment. They certainly integrating it into a WearCam6 system. to the positive lug of the battery, and weren’t general-purpose computers. WearComp6 is built from standard a red wire soldered to the other end of But WearComp2 was. It could ex- PC/104 modules. The modularity of the fuse. A black wire can go directly ecute a general instruction set, and it WearComp6 makes it easy to change to the negative side of the battery. even had a BASIC interpreter, making the system’s functionality quickly. I wrap both lugs in several layers of it easy to write programs to edit ASCII In a sense, you end up with a wear- fiberglass tape and epoxy. You need to text files, exchange messages (e.g., an able image-processing lab, and you wrap all the way around both the posi- E-mail of sorts), do floating-point might want to add other boards such tive lug and the fuse near it because calculations, and other things that go as an ADC board for an oscilloscope. I general wear and tear on a wearable beyond the kind of functionality you’d implemented an oscilloscope in Wear- apparatus is much higher than for expect in a camera system. Comp2 and found it useful for diagnos- other embedded systems.

Circuit Cellar INK® Issue 95 June 1998 19 rig. Therefore, I chose to use Name Completed Processor Text and Graphics Where on Body a nonisolated integrated WearComp0 1970s electromechanical — back switching regulator. WearComp1 1970s SSI, MSI ATV RS170 back + waist + shoulder I selected the PowerTrends WearComp2 1981 6502 40 × 12, 280×, NTSC back + waist + shoulder PT6302 (3-A ISR), which is WearComp3 early 1980s 8085 7-segment displays waist + chest much more efficient than the WearComp4 late 1980s 80286 80 × 24,640 × 480 ordinary backpack WearComp5 early 1990s 80486/33 80 × 24,640 × 480 large waistbag isolated regulators (e.g. Datel). WearComp6 early 1990s PC/104,80x86 80 × 24,640 × 480 medium waistbag This extends battery life and WearComp7 mid/late 1990s TMS320C3x/4x RS170 underwearable produces much less heat. WearComp8 late 1990s Pentium RS170 underwearable My WearComp6 is built Table 1—As you can see, WearComp has gone through quite an evolution on its way to becoming what it is today. around the Ampro Core- Module, along with various Alternatively, you can buy a battery • it protects against possible damage if other modules that I swapped in and vest for about $600. You then have a battery polarity is incorrect out depending on my plans. ready-to-wear power supply with plenty • mixed brands and types of batteries I connected the power to the Core- of pockets for computational apparatus can be bridged together without Module rather than using a power or additional components. These vests damage resulting from one “charg- header connector. This enabled me to are designed for high-current output ing” the other cut off all the pins on the bottom (e.g., video lights and large cameras), so board, saving considerable space. it’s a good idea to include an additional In my typical usage, WearComp6 It’s worth the extra money to get fuse of lower current rating, consistent forms the basis of a complete Internet- the CoreModule development system, with the use expected of WearCam. connected multimedia video production especially if this is the first unit you facility, ham-radio television station, build. This development system in- LI-ION BATTERIES and various other things. cludes the power connector (e.g., MX40) In the early to mid 1990s, I began Because of the large amount of equip- with a 10 (or 8) pin female connector—2 using lithium-ion (Li-Ion) batteries. Sony ment I have powered up, the diodes rows of 5 (or 4) to mate with the header provided me with camcorder batteries dissipate some heat and must also carry pins on the CoreModule. I generally cut before they were commercially available. the full current of the maximum antici- off the large connector and 12-V wires, Now you can find Li-Ion camcorder pated load. I found that a bridge recti- leaving just the small MX40 connector. batteries almost anywhere. You need fier, by virtue of its larger surface area It’s important to use all three pairs a minimum of four batteries (two sets and the ease with which it may be of redundant 5-V wires in parallel for of two in series) for a constant-running heatsinked, dissipates the heat better system reliability, especially when you 12-V supply. and is easily sewn into my clothing. use video-capture cards because they My version of WearCam, for example, often introduce current surges on startup. is a complete photographic studio and VOLTAGE REGULATORS Otherwise, you may find that, when video editing facility, so it’s not surpris- The weight, for a given energy level, you issue a frame-capture command, ing that it needs more than just one is much less for Li-Ion batteries com- the computer system reboots itself. camcorder battery. These batteries have pared to lead-acid and NiCd batteries. Originally, I built enclosures using built in minifemale banana connectors, But, the output voltage of Li-Ion bat- sheet metal and a metal-bending ma- so they’re easy to connect to the system. teries varies widely and drops signifi- chine. Here, however, I’m putting cantly with usage from a full charge. together a system using a commercial BRIDGING THE POWER GAP Lead-acid batteries exhibit this off-the-shelf enclosure. Ordinarily, when you remove a bat- inconstancy of output voltage to some A suitable choice is the so-called tery from WearComp to insert a new degree (compared to NiCds, which are half cube enclosure. With it, you can one, there is a brief power gap. One or much more self-regulating). But, Li-Ion easily keep the power cables 2″ or less more large capacitors can keep power batteries are far worse, almost certainly in length. to the circuit during this time. needing a voltage regulator. All three pairs of 5-V wires may con- However, a better alternative is to A single 12-V battery can power nect to the various parallel pins of the put diodes in series with each set of most of the apparatus, together with PT6302 ISR. It is a nice coincidence battery terminals, as depicted in Figure an integrated switching voltage regu- that CoreModule’s power connector and 2. This power bridge has the following lator to bring the 12 V down to 5 V for the ISR both have three redundant +5-V advantages over using a single battery: powering the computational portion pins. Connect one of each red wire from of the apparatus. the power cable to each of these pins. • the new battery can be inserted The ISR has four redundant ground before the old battery is removed, so POWER SUPPLY pins. Connect the three black wires the power gap is bridged Isolation from any test probes to the from the CoreModule power cable to • multiple batteries may be bridged rig is required, but I decided not to three of these, which leaves one ground together for increased power capacity isolate the batteries from the rest of the connection for the 12-V input to the ISR

20 Issue 95 June 1998 Circuit Cellar INK® (higher voltage and correspondingly The PT6302 ISR comes in six vari- sufficient strength to reboot the com- less current). ants, with and without mounting tabs puter. If you don’t need it, consider Connect a single twisted pair of wires (select the one with mounting tabs), breaking it off or cutting it short so it to the input (conductors don’t need to and each of these comes in three varia- doesn’t act like a receive antenna. be so thick owing to the lesser current, tions—horizontal mount, surface Note the capacitors on the ISR as well as well as the fact that the ISR makes mount, and vertical mount. as inline right near the MX40 connector. up for line losses). Make sure the twisted The vertical mount is preferable, Sometimes I also insert series inductors, pair has tough insulation because it’s but it’s often out of stock. With surface especially when using the ANDI-FG outside the enclosure and subject to mount, which is most readily available, board, which seems to need them. wear and tear against your clothing. the pins touch the case. But, if you use a I brought the 12-V power leads out of Here, I used a 100-µF output capaci- small aluminum shim, the pins are kept the enclosure and threaded them through tor and a 47-µF input capacitor with sufficiently far away from the case. a ferrite bead (healthy paranoia). Then, I leads soldered to the appropriate pins Install the PT6302 ISR near the front soldered on connectors for the battery. of the ISR for additional filtering. I of the enclosure, facing inwards. Locate selected an input capacitor with a high it so that the power cable emanates HARD DRIVE enough voltage rating to match the range from directly below where the power On the Ampro 100-MHz ’486 Core- of input voltage that the PT6302 could connector is located on the PC/104 Module, it’s best to put the hard drive 1 handle so the rig could run on a wider CoreModule. Note that the ⁄8″ alumi- on the bottom of the case, assuming you range of input voltages. I found this num shim keeps the pins from touch- have three boards or fewer in the stack. useful in the field because I could run ing the case. I normally cover the circuit-board the rig from nearly any battery source Be careful not to locate objects near side of the hard drive with cloth tape I might encounter (e.g., a 24-V system). pin 12 (the sense pin) of the ISR. For (thick gaffer’s tape works best) as an Next, mount the ISR inside the example, if the disk cable comes too precautionary measure. If you place enclosure. This prevents it from being close to pin 12, stray emissions will the hard drive on the bottom of the jostled around where it may touch and affect the ISR or set up a feedback loop case, put it upside down in the case short out other components or obstruct that makes the whole system unstable. and wire-tie it down. air flow. It also helps with heat dissipa- Touching pin 12 when the computer With the hard drive underneath, you tion (i.e., heatsinking it to the case). is running generally causes a spike of can make a straight run to the header

Circuit Cellar INK® Issue 95 June 1998 21 I usually wear the computer in a waist a) Battery 1 + bag or lumbar pack. The Mountainsmith

Battery 2 + daypack or tourpack is appropriate for the computer itself and leaves room for a good collection of other peripherals. To Computer + Side Battery n + KEYBOARD b) Not Connected Data entry is typically through the camera (e.g., you can color mark each finger and track them using a PC/104 machine-vision system like Cogna- Battery 1 + Battery 2 + chrome [“Robots with a Vision,” INK 92]). That way, you can use your finger to outline an object and select it by

To Computer pinching two fingers together. + Side Alternatively, I use a collection of push-button switches. A few switches, Figure 2a—A large number of batteries may be com- appropriately arranged, may be con- bined, and in this way, there is also protection from nected to the parallel port of the com- accidental polarity reversal. b—Where only two batter- puter and serve as a data-entry means ies are needed, a commercial bridge rectifier may be (see Photo 1). used. In this case, only two of the four internal diodes are used. If you decide to use the switches as your keyboard, you need to write a small on the CoreModule. Therefore, you can program that takes input this way. But if shorten the ribbon cable appreciably, you write a device driver for both DOS making the insides of the rig neater and Linux, don’t use LiLo (Linux Loader). and resulting in greater reliability and Use loadlin instead because there is improved air circulation. no control of the computer at the LiLo prompt since your program or device ASSEMBLING WEARCOMP6 driver which needs to accept input from The Ampro VGA board doesn’t the switches hasn’t run yet. So, you properly support 24-bit true color, or at can’t use the keyboard to select oper- least the color fidelity was not as good ating systems at the LiLo prompt. as I needed. Having a full 24-bit color Photo 2 shows the completed Wear- display was essential for photographic Comp6 on my workbench, next to a work because the display ultimately VGA-to-NTSC scan converter. became the camera’s viewfinder. Therefore, I generally use a VGA TELEVEYES board from another vendor. The Advan- By connecting WearComp to a head- tech board uses the Tseng4000 chip, mounted display and plugging in some which is fully supported in Linux. I use sort of keyboard, you have a complete Linux in WearComp because Microsoft computer system you can use while Windows isn’t sufficiently reconfigur- walking around doing other things. able to adapt to completely new para- The limited availability of reasonably digms in computing. priced, small, VGA head-mounted Traditional computing is a primary displays as well as their poor tonal range task, but WearComp makes it secondary. suggest NTSC as an alternative. Indeed, I frequently respond to an E-mail mes- early versions of WearComp used sage, type a manuscript, and shoot a NTSC, and there is a long history of personal documentary video, while availability of NTSC displays. walking. Windows cannot be easily In particular, you can often salvage used through a teletype interface be- camcorder viewfinders and build them cause it forces its GUI on the user. into eyeglasses. I usually find these The beeping speaker annoys others, units for under $20, and it’s clearly the so use an earphone jack instead. Alter- lowest-cost solution. Larger tubes natively, I use a step-up transformer (like the ones I have from 15 or 20 years (e.g., to generate a mild electric shock) ago) last for years and provide good or a silent vibrotactile device. resolution and excellent tonal fidelity.

22 Issue 95 June 1998 Circuit Cellar INK® Photo 2—The completed www.wearcomp.org/wearhow/ WearComp6 is sitting on index.html workbench next to the VGA-to-NTSC scan www.pc104.org converter. www.tapr.org www.radio.org SOURCES CoreModule Ampro Computers, Inc. 4757 Hellyer Ave. San Jose, CA 95138 (408) 360-0200 Fax: (408) 360-0222 There is a common misconception SET TO GO www.ampro.com (due to cheap game displays and con- Describing the full details of Wear- PT6302, ST105VC sumer television) that NTSC resolu- Cam is beyond the scope of this article. Power Trends, Inc. tion is significantly less than VGA. However, if you want more informa- 27715 Diehl Rd. However, good NTSC camera view- tion about the algorithms and theory Warrenville, IL 60555 finders often use CRTs with 1000 verti- behind it, check the Internet sites (630) 393-6901 cal lines of resolution that adequately listed in the References section. Fax: (630) 393-6902 display VGA-resolution images or text. The pictures in this article were www.powertrends.com Some experimentation is needed since taken with another WearCam system text modes in VGA are often not 60 Hz, I wore while building this unit. The Enclosures but many camcorder viewfinders will visual record of this assembly is an- Tri-M Systems sync at 60 or 72 Hz. other example of the utility of per- 1301 Ketch Ct., Ste. 6 If you choose to use a low-cost wear- sonal imaging. Much of my work in Coquitlam, BC able television set (e.g., VirtualVision), this area is documented from the Canada V3K 6X7 you may want to run XFree86 with first-person perspective of the appara- (604) 527-1100 increased font size (e.g., 30 × 12). tus I wear. I Fax: (604) 527-1110 www.tri-m.com NTSC OUTPUT Thanks to Kodak, Xybernaut, ViA, Kopin, VGA board If you know Linux, you’ll probably be DisplayTech, Liquid Image, HP labs, Advantech America able to rewrite the XF86Config file to Thought Technologies, VirtualVision, 750 E. Arques Ave. output a signal that can drive an NTSC Compaq, Sony, and Antonin Kimla, Sunnyvale, CA 94086 display directly. Unfortunately, such a for making this work possible, and to (408) 245-6678 display only works inside XFree86 and Robert Kinney and Rich Landry of Fax: (408) 245-5678 not in DOS or while booting to change Natick for updating my ThinkTank/ www.advantech-usa.com the BIOS settings. VibraVest version of my personal www.advantek.com. A simpler approach, which gives you imaging apparatus. Pocket Scan Converter a display that works outside XFree86, AITech is to use a VGA-to-NTSC converter. Steve Mann, is a faculty member at the 47971 Fremont Blvd. Begin by purchasing a Pocket Scan University of Toronto, Department of Fremont, CA 94538 Converter from AITech. This unit, Electrical and Computer Engineering. (510) 226-8960 which costs about $129, consumes a His present research interests include Fax: (510) 226-8996 lot of power because of its inefficient quantographic imaging, lightspace www.aitech.com regulator. However, you can roughly rendering, and wearable, tetherless double its efficiency by replacing its computer-mediated reality. He is Battery vest regulator with a PowerTrends ST105VC currently setting up a new Humanistic NRG Research, Inc. integrated switching regulator. Intelligence lab to invent the camera 840 Rogue River Hwy., Ste. 144 Connectors on most devices, in- of the future. Steve may be reached at Grants Pass, OR 97527 cluding the AITech scan converter, [email protected]. (541) 479-9433 tend to be unreliable. So, I connected Fax: (541) 471-6251 the red and black wires for 12-V input REFERENCES www.nrgresearch.com and a coaxial cable for video output genesis.eecg.toronto.edu/research.html directly to the circuit board. Routing www.hi.eecg.toronto.edu/hi/index. I R S these through the case, I installed html 404 Very Useful locking inline connectors, which are www.wearcam.org/historical/ 405 Moderately Useful much more reliable. index.html 406 Not Useful

24 Issue 95 June 1998 Circuit Cellar INK® designer’s control. Pstatic is associated with the IC’s quiescent current and FEATURE depends on the characteristics of the die, temperature, and supply voltage. V is ARTICLE the supply voltage, f is the operating frequency, and C is the capacitive load.

REDUCING SUPPLY VOLTAGE Brian Kurkoski That the power consumption follows a square law is good news: great power savings are realized for small reductions in supply voltage. Compare a system operating at 5-V Design Embedded supply versus 3.3 V. Reducing the voltage supply from 5 to 3.3 V reduces the dynamic power consumption to:

Systems for Low Power 2 3.3 =43% 52

of the original, which is a power savings of 57%. Figure 1 shows this graphical square relationship. To reliably run a system at a reduced ou’re ready to supply-voltage level, you must have ICs y begin work on your specified for operation at the level in When it comes to latest design: a hand- question. A few years ago, your compo- held measurement and nent selection may have been restricted battery management, data recorder. The unit must run off because the part you wanted wasn’t batteries for a reasonable length of time, offered in a low-voltage version. conventional tech- so you want the design to use as little Today, many parts are available for power as possible. A quick calculation 3.3-V ±10% power-supply operation. niques don’t always shows that conventional techniques (3.3 V ±10% is usually taken to be yield a battery life of only a few hours, 3.0–3.6 V; in fact, this is a JEDEC cut it. Brian shows but the system must run for several standard for 3.3-V supply voltages.) times that on a single charge. By reducing the power consumption, how to get around Dynamic Power Consumption however, you extend the battery life. traditional restrictions In this article, I show you exactly Normalized Power (P) that—how to reduce power consump- and still reduce tion in embedded systems.

Advances in IC technology make it P ∝ V2 power consumption. possible to create practical low-power designs with relative ease. The power Find out how to get your board consumes is determined mostly by the design’s supply voltage the most out of and operating frequency. However, 1.00 there are a number of other consider- battery life. ations for a successful low-power design.

0.43 THE POWER EQUATION A reasonably accurate approxima- tion of power consumption in an IC is: 3.30 V 5.00 V IC Supply Voltage (V) P = V2 × f × C + P static Figure 1—The dynamic power consumed by an IC is proportional to the square of the supply voltage, so 2 × × where V f C is the dynamic power reducing the supply 5.0 V to 3.3 V results in a 57% consumption and is largely under the power savings.

26 Issue 95 June 1998 Circuit Cellar INK® You can also find 3.0-V ±10% parts (often referred to as 2.7-V parts; 3.0 V – 10%), but they’re less common, which makes designing a 2.7-V system difficult.

FAST CLOCKS Power consumption is proportional to operating frequency. As the operating frequency goes to zero, the dynamic portion of the power consumption also Figure 2—The National Semiconductor NDS332P (a p-channel FET rated for operation at 3.3 V) gates the power supply to most of an embedded system under the control of a real-time clock with a power-control pin. approaches zero. This situation leaves only the static power consumption, AMD’s Élan 386) have an internal PLL core is not clocked. In mode 2, the oscil- which typically is in the microwatt that can step up the frequency from a lator is off, but the micro is still pow- range for CMOS ICs. 32.768-kHz watch crystal to megahertz ered. And in mode 3, power to the Because power consumption depends speeds. The PLL permits a good deal of processor is removed completely. heavily on clock speed, choose a pro- control over the operating frequency, The advantage of mode 1 is that it cessor speed as fast as your applica- enabling complex power-management can respond quickly to a stimulus event, tion needs, and no faster. Running the schemes. An external 32.768-kHz crys- even though current consumption is clock at a frequency higher than nec- tal requires lower quiescent current high for a sleep-type mode (~1 mA, essary wastes valuable battery power. than megahertz-speed crystal oscilla- depending on frequency). Also, substantial power savings can tor circuits. In mode 2, current consumption is be realized from intelligently managing The 32.768-kHz crystal also drives reduced to the quiescent current of the the CPU clock speed. If your CPU clock the real-time clock, eliminating a crys- microprocessor and other components, is fixed at a blazingly high speed to tal from the system. A low-frequency but it takes a lot of time to restart the accommodate a compute-intensive task reference clock also has much lower processor. It’s usually controlled by (e.g., data processing), then considerable electromagnetic emissions than a high- the reset generator, which has a 50- or battery power is lost when the system speed one. 200-ms pulse. That’s a generous amount performs a less CPU-intensive task If your microprocessor doesn’t have of time for the oscillator to restart, but a (e.g., acquiring data). a scalable clock, design an external long time for a real-time event. Enter a solution: the scalable clock. clock divider. The circuit should not In mode 3, the quiescent current of The microprocessor can program the output glitches when the frequency is the upowered components is elimi- frequency of its own clock to match the switched as this causes improper opera- nated entirely by disconnecting power processing speed of the task being per- tion of the micro. If your application to the system via a switch like a p- formed. Thus, for a minimal amount uses internal timers or counters driven channel FET. However, some addi- of additional hardware and software, by the scaled clock for precise timing, tional circuitry is required to switch the programmer can improve battery writing code is more difficult. power. Also, power-supply bus isola- life by dynamically scaling the clock tion becomes a problem. based on the computational load. SLOWING THE CLOCK Modes 1 and 2 rely on the features Simple on-chip scalable clocks, such In many applications, you want to of the microprocessor, but the power- as those found on Zilog’s Z180, divide be able to stop the clock completely, and savings mode 3 can be implemented the crystal frequency to derive the CPU most microprocessors have this feature. using any microprocessor and it affects clock. Although this scalable clock is Modes that turn off the clock (referred the entire system. simple, the oscillator still operates at to as sleep, doze, snooze, shutdown and In modes 1 and 2, the restart depends the nominal frequency, consuming a halt) are usually invoked by writing to on the microprocessor. In mode 3, the steady current. an internal I/O register or executing a restart is implemented in hardware Some larger microprocessors (e.g., special instruction. Normal operation controlling your switch. Motorola’s MC68328 DragonBall and is restored by a stimulus event such as Figure 2 shows an implementation an interrupt (external, or inter- example of mode 3. Power is controlled nal if onboard peripherals are by the real-time clock, a Dallas Semi- permitted to operate) or reset. conductor DS1685. The microprocessor Let me describe three pos- can set a bit in a DS1685 control register sible zero-frequency clocking that tristates the *PWR pin, which modes based on their technical disables the FET, effectively shutting differences. I use generic labels off power to the system core. because processor datasheets If so configured within the RTC, the Figure 3—A series shunt is an alternate to a low drop-out reference use no consistent terminology. *PWR pin is pulled low by a real-time since the selection of the latter is limited. The series resistor must be small enough to permit the shunt reference to be biased to a region In mode 1, the oscillator clock event (e.g., a preprogrammed where the output is stable. continues to operate, but the alarm) or an external stimulus on the

Circuit Cellar INK® Issue 95 June 1998 27 dreds of kilohertz range. Power con- COMPONENT SELECTION a) sumption at these clock frequencies Using a 3.3-V supply and reducing may be comparable to sleep-mode the clock speed to a minimum gets the operation and the problems of oscilla- biggest reduction in power consumption. tor restart time are avoided. While in However, careful IC selection, use of slow-speed mode, the micro performs shutdown modes, power-supply design, a simple sampling task, like monitor- and analog design also help you squeeze b) ing the keypad for user input or sam- extra life out of the systems’ batteries. pling the real-time clock to wake the As opposed to 5 V, with low-power system at a specified time. design, you must be concerned with the availability of 3.3-V parts and the speci- CAPACITANCE fied power consumption. These two Power dissipation is also proportional considerations make IC selection for a to capacitance. The term C from the low-power design trickier than conven-

Figure 4a—When a 5-V–powered output drives a 3.3-V– power equation is the sum of CPD and tional 5-V design. powered input, a large current flows through the input- CIO. CPD is the effective, lumped inter- Not all ICs specified for operation protection diode into the 3.3-V supply rail. b—When a nal capacitance that is associated with at 3.3 V are appropriate for a battery- powered output drives an unpowered input, current flows into the unpowered rail, turning on ICs that were the power dissipated internally by the powered system. Compare the speci- intended to be off. IC. CIO is the capacitance associated fied current consumption for parts with power dissipated outside the IC. you are considering for your design.

*KS (kickstart) input (e.g., the On but- CPD depends completely on IC Sometimes IC manufacturers are ton being pressed). The p-channel FET characteristics and is beyond your inconsistent about the conditions

Q1 must be specified to be on with a control. You have control over CIO. power consumption is specified in.

VGS of 3.0 V or less. A few FETs are However, it’s usually a function of PCB When you compare power-consump- available, such as National’s NDS332P. traces loading and other IC loads, tion figures, make sure the clock fre- As a novel alternative to putting the which are constrained by other aspects quency, supply voltage, and temperature unit to sleep as in mode 1, consider of the design. Keep excess capacitive are similar. Some PLD manufacturers slowing the clock to the tens to hun- load to a minimum where possible. specify current consumption at 0°C. But, this is not meaningful for most systems since CMOS power consumption increases with increasing temperature.

POWER SUPPLY Choosing a power supply is critical in a low-power system. Although you may think of linear regulators as inef- ficient, they’re often a good choice for a battery-powered system, particularly because the difference between the input (your battery supply) and the output is typically low. Some recent offerings by IC makers include low-dropout (LDO) and low- quiescent current parts. LDO linear regulators may remain in regulation

when the Vin to Vout difference is 100 mV or lower, depending on the current. If your system supply voltage is 3.3 V, the input voltage from your batteries can drop as low as 3.4 V and the sys- tem operates normally. The apparent efficiency of a linear regulator can be comparable to that of a switcher. For example, if your power source is three alkaline batteries, the nominal battery voltage is 4.5 V, and the nominal supply is 3.3 V, then the initial efficiency is:

28 Issue 95 June 1998 Circuit Cellar INK® 3.3 V =73% op-amps, keep an eye on the specified 4.5 V current draw. Generally speaking, op- (The calculated efficiency increases as amps trade off power consumption the battery discharges and voltage de- with frequency response. creases.) A typical switching power To minimize op-amp power con- supply is 60–80% efficient and needs sumption, select one with the lowest more components than a linear supply. possible frequency response that your Many LDO regulators require a high- design can accommodate. Table 1 lists value, low equivalent series resistance some op-amps that trade current con- (ESR) capacitor on the output, such as sumption with frequency response. Figure 5—When a 3.3-V–powered output drives a 5-V– powered input, both input stage transistors conduct, µ a 4.7- F tantalum, to stabilize the inter- Another critical parameter for op- forming a current path between +5 V and ground and nal feedback. A noteworthy exception amps is maximum and minimum out- dramatically increasing power consumption. is the anyCAP line of LDOs (ADP330x) put voltages. With rails of only 3.3 V from Analog Devices. According to the and ground, the op-amp must swing as age reference with a maximum quies- manufacturer, the ESR of the filter close to the rails as possible to have a cent current of 15 µA at 25° C. capacitor is unrestricted and its value useful output voltage range. Fortunately, An alternative to sole-source buff- can be as low as 0.47-µF. newer op-amps specified for lower volt- ered output voltage reference is a shunt An LDO regulator may not neces- age operation can also drive their output reference. With shunt references, a sarily have low quiescent current. If voltage within 10 mV of the rails. series resistor supplies the reference. your design requires the availability of A reference is a critical part of the Careful selection is important here regulated power in sleep mode, pay analog subsystem. For a low-voltage because some shunts require higher attention to the quiescent current. If design, you may select a reference volt- current to maintain the output volt- the power supply has high quiescent age of 2.5 V. When operating from a age within tolerance. current and is continuously on, the 3.3 V supply ±10%, the reference must For example, National Semicon- batteries could have a shorter-than- tolerate VCC as low as 3.0 V, so a drop- ductor’s LM4040 needs an external expected shelf life. out of more than 0.5 V is unacceptable. resistor. The forward current across the If your design requires a battery sup- Analog Devices offers the ADR291, IC is specified to be 100 µA to achieve ply voltage that is lower than the supply a 2.5-V, 5-mA output precision volt- a flat output voltage over temperature. (e.g., two alkaline cells in series provide 3.0 V when fresh, less than the typical 3.3 V), a boost-topology switching power supply is your only choice. Given your design requirements, it may not be possible to operate strictly at 3.3 V. A 5-V power supply may be needed for some subsystems. Compo- nents such as LCDs and certain analog ICs are not easily found at 3.3 V.

SHUTDOWN MODES Many ICs providing I/O functions (e.g., RS-232 level shifters or ADCs) have shutdown modes that reduce the power consumption to microamps. Some ICs have a pin dedicated to this function. In others, shutdown mode is engaged by writing to a specific register. Thus, the micro intelligently controls the use of power in the system by shut- ting down a subsystem not in use.

LOW-POWER ANALOG Design of analog sections can be tricky with a reduced supply voltage. Component selection plays a signifi- cant role in your design. Op-amps specified to operate from a single 3.3-V supply abound. With

Circuit Cellar INK® Issue 95 June 1998 29 With a minimum VCC of supplies) can be fairly 3.0 V, the series resistor Typical Current tricky. It offers no in- Consumption per Gain Bandwidth value should be: Op-Amp Op-Amp at 25°C (µA) Product (MHz) herent advantages, and single-supply systems 3.0V– 2.5V= 5000 Ω Analog Devices OP193 15 0.035 100 µA are easier to design. Burr-Brown OP336 20 0.1 But, when component Ω National Semiconductor LMC6462 20 0.05 (but use 5100 ; see Fig- Analog Devices OP191 220 3 selection dictates you ure 3). Burr-Brown OPA340 750 5.5 must have a 5-V rail, you Also, a p-channel FET need to think about can turn off the reference’s Table 1—With op-amps, you can tradeoff current consumption with frequency response by way mixed-rail interfacing. power when it’s not in of part selection. Both 3.3 V to 5 V and 5 V use. An op-amp buffer provides suffi- even if the supply is 3.3 V, which is a to 3.3 V have interfacing difficulties. cient current to drive the analog signal help when interfacing to 5-V logic. When a 5-V output drives the input conditioning and converter. You may be tempted to use a PAL or of a 3.3-V–powered part, unnecessary An LDO linear regulator can be used EPLD in your design. However, most current flows from the 5-V output pin as low-accuracy alternative to a conven- programmable logic has high power into the 3-V supply via the input pro- tional reference, although you have to consumption. tection diode (see Figure 4a). Although program the output voltage using “Quarter power” and “zero power” solutions using open-drain outputs, series external using feedback/sense resistors. PALs are available from some IC ven- resistors, or diodes exist, a clean solution A variety of 3.3 V-only ADCs and dors, but since these have microamp is to use a logic family such as 74VHC, DACs are available from Texas Instru- static power consumption, the dynamic which can tolerate inputs as high as ments, Analog Devices, Linear Technolo- power consumption can be quite high 7 V independent of the supply voltage. gies, and others. The TLV2543 from (see Table 2). Some PLDs are designed The same problem is encountered Texas Instruments is a low-cost, 12-bit to improve power consumption, but when interfacing between powered ADC with 11 input channels as well sometimes specifications are ambigu- and unpowered parts. If a powered part as a serial interface and a software- ous or only specified at 0°C. with a high output drives an unpowered programmable shutdown mode. Table 2 compares manufacturer’s part, then current conducts through specified power consumption for various the input protection diode, powering DIGITAL LOGIC logic parts, operated at 3.3 V. It gives the supposedly unpowered rail (see Almost every design needs some logic a rough comparison of the power con- Figure 4b). to glue the processor and subsystems sumption for different types of logic. Interfacing a 3.3-V output to a 5-V– together. Modern CMOS discrete logic Table 2 doesn’t accurately compare powered input, as in Figure 5, is also a families have low dynamic power con- logic implementations because each problem but for a different reason. When sumption and almost immeasurable entry doesn’t have an equivalent amount the input to the 5-V–powered part is static power consumption. Various logic of logic and PLDs are not programmed ~3.3 V, the input stage transistors are families are available, but they usually with the same logic functions. Note: both in their linear region and a current ° trade power consumption for speed. Pay Philips specifies at 0 C, making their path from VCC to ground is formed attention to the specified supply voltages. current consumption figures appear within the part. This results in current The 74VHC family, available from more favorable than the competition. consumption 10 or 100 times worse National Semiconductor and Motorola, And, AMD PALs are now sold under than the quiescent current. is a nice choice. It has low power con- the Vantis name. In some cases, this current of 1–2 mA sumption (see Table 2), it’s fast enough per pin may be acceptable. A solution for many microprocessor applications MIXED-RAIL INTERFACING is to use an open-drain output with a (~15 ns for buffers and latches, ~10 ns Mixed-rail interfacing (i.e., interfac- pull-up resistor, but speed and current for gates), and it tolerates 7 V on inputs ing logic driven by both 5- and 3.3-V drain through the pull-up resistor may still be unacceptable. Probably the best approach to 3.3 V Typical Supply Current Typical Supply Current Temperature at 0 MHz (µA) at 15 MHz (mA) Specified (°C) to 5 V interfacing is to use dual-supply interface ICs designed for this purpose. National Semiconductor 4 1.5 25 These include some of the 74LVX line 74VHC373 from National Semiconductor. Philips 32-Macrocell EPLD 10 3 0 Atmel 32-Macrocell EPLD 3000 30 25 (5 with shutdown pin) MEMORIES Atmel Zero Power PAL 5 55 25 If your micro needs external memory, ° Vantis Zero Power PAL 30 (85 C) 30 25 there’s good news and bad news. The Vantis Full Power PAL 40,000 45 25 good news is that SRAMs are widely Table 2—Although there’s a large amount of variation in the power consumption of programmable logic, it does available and specified for 3.3-V opera- consume more power than discrete logic. tion, even at access speeds of 70 ns.

30 Issue 95 June 1998 Circuit Cellar INK® The bad news is that this is not Brian Kurkoski is the hardware engineer- 3.3-V ADCs and DACs true for ROMs. Low-voltage EPROMs ing manager for Z-World. He developed Linear Technology and flash memory are easy to find, but many of the ideas in this article when 1630 McCarthy Blvd. the fastest access speeds aren’t on par designing the LP3100, a C-program- Milpitas, CA 95035 with their 5-V brethren. You may have mable embedded controller with low (408) 432-1900 to use a slower microprocessor clock power consumption. You may reach Fax: (408) 434-0507 or insert wait states to meet timing Brian at [email protected]. www.linear-tech.com requirements for low-voltage nonvola- 74VHCxxx, MC68328 DragonBall tile memory. REFERENCES Motorola Literature Distribution Ctr. ON TIME National Semiconductor, National P.O. Box 20912 Phoenix, AZ 85036 It’s difficult to predict the length of VHC Advanced CMOS Logic (602) 244-6900 time your device will operate on a single Databook, 1996. Fax: (602) 332-3944 battery charge. First, estimate the C. Small, “Batteries Explode into New www.mot-sps.com system’s power consumption. Applications and New Chemis- Usually, the maximum rated power tries,” EDN, 13 October 1994. 74VHCxxx, LMC6462, NDS332P consumption that you find in the data- J. Williams, “Low Voltage Embed- National Semiconductor sheet is much worse than what you ded Design,” Intel Corp., App. P.O. Box 58090 measure on the bench. Remember that Note 272324-001, February 1993. Santa Clara, CA 95052-8090 the datasheet rating usually applies over (408) 721-5000 the full temperature range and your SOURCES Fax: (408) 739-9803 bench measurement is performed at Élan 386 www.nsc.com room temperature. Advanced Micro Devices, Inc. EPLDs The other consideration is the amount One AMD Pl. Philips Semiconductor of power available from your batteries. Sunnyvale, CA 94088-3453 811 E. Arques Ave. But, the capacity of the system’s batter- (408) 732-2400 Sunnyvale, CA 94088-3409 ies can vary fairly widely, even between Fax: (408) 732-7216 (408) 991-3737 batteries in the same manufacturing lot. www.amd.com Fax: (408) 991-3773 The best way to predict time of www-us2.semiconductors.philips. com operation is to measure the length of OP191, OP193, ADCs, DACs operation under a variety of different Analog Devices 3.3-V ADCs and DACs, TLV2543 operating conditions with different One Technology Way Texas Instruments, Inc. batteries. Norwood, MA 02062-9106 34 Forest St.,MS 14-01 Battery capacity increases with (781) 329-4700 Attleboro, MA 02703 decreased drain current. The lower Fax: (781) 461-4261 (508) 699-5269 the current draw from a battery, the www.analog.com Fax: (508) 699-5200 more total power is available from EPLDs, PALs www.ti.com that cell. Thus, as your design draws Atmel Corp. AMD PALs less and less current, the application 2324 O’Nel Dr. Vantis Corp. runs even longer. San Jose, CA 95131 995 Stewart Dr. (408) 441-0311 LIVE LONG AND PROSPER Sunnyvale, CA 94088 Fax: (408) 436-4300 (408) 616-8000 Many designs are constrained to use www.atmel.com Fax: (408) 616-8010 batteries because the application re- OP336, OPA340 www.vantis.com quires portability or is located remotely. Burr-Brown Corp. To maximize battery life, the system Z180 6730 S. Tucson Blvd. shouldn’t squander power when it Zilog, Inc. Tucson, AZ 85706 isn’t needed. 210 E. Hacienda Ave. (520) 746-1111 If the application is a hand-held Campbell, CA 95008-6800 Fax: (520) 889-1510 instrument, lower power consumption (408) 370-8000 www.burr-brown.com means that batteries can be smaller, Fax: (408) 370-8056 lighter, and last longer. If the application DS1685 www.zilog.com is a remote data logger, the batteries Dallas Semiconductor do not have to be serviced as often. If 4401 S. Beltwood Pkwy. you are designing a robot, more avail- Dallas, TX 75244-3292 I R S able battery power can be allocated to (972) 371-4448 404 Very Useful motors, resulting in a faster or higher Fax: (972) 371-3715 405 Moderately Useful torque device. I www.dalsemi.com 406 Not Useful

32 Issue 95 June 1998 Circuit Cellar INK® Design98 Contest PIC of the Lot

“The designs submitted were quite professional and far more complex in nature than my wildest imagination. It was clear to me that all of the contestants in this contest are winners.” Contest Judge John Martinelli, Director of Advanced Development, Interlink Electronics Inc.

Your response to Design98 made this contest more enjoyable And then, to top it all off, I got a rabbit colony full of entries. than any of the others that I’ve coordinated to date. I received a Entries were bursting out of the corners. I was swimming in ton of E-mail with questions ranging from “How do I get an entry emptied FedEx envelopes. form” to “I designed this cool for my company. May I enter it?” made all of the difficulties of putting a contest together worth it. I got phone calls, “Hello, this is Alvin Tan from Singapore. Can Thank you for stepping up to the plate and making this the very internationals enter your contest?” My response, “Can you cash best Circuit Cellar INK contest we’ve ever had. You are what an American-currency check?” made it work. I received letters. “Thanks for running such an interesting contest!!” “Thank you for promoting such a contest.” “Thank you —Janice Hughes for running a great contest. I had fun designing this entry and Very Proud Contest Coordinator seeing it finally work.”

BEST OVERALL

$5000, HP Mixed Signal Oscilloscope, $500 for using PIC16F84 XY LCD Graphing Data Logger—Alberto Ricci Bitti, Lugo, Italy

Do you need sophisticated graphical display of data immediately The entire circuit is assembled using a prototyping board that fits regardless of whether you’re in the lab, on the production line, or in the inside a small plastic box as large as the calculator. While operating, field? If so, you need to check out the XY LCD Graphing Data Logger. the box is affixed to the bottom of the Casio calculator via removable Alberto brings us a hand-held data logger that is capable of displaying biadhesive strips. This arrangement keeps the calculator stable and on data graphically on a 64 ×128 LCD screen and of performing analytical a comfortable slope. (e.g., integration and derivation) and statistical (e.g., linear, exponen- On the software end of things, he discovered the tial, polynomial regressions, mean, and deviation) math processing. At Casio used a 9600-bps, half-duplex serial up to eight inputs, its voltage is read with 1-mV resolution in the 0–4096- stream with single-character mV range through a 12-bit ADC. ACK/NACK hand- How does he do it? By using a Casio graphing calculator that sells for shake terminated about the same amount as an LCD and interfaces through a miniature by checksums. jack, a PIC16F84, and a MAX186 ADC. The software manages the The logger collects communication protocol over a serial line while also combining sleep data and passes mode and watchdog techniques to achieve minimal power consumption, tables of variable in- low-power ADC operation, and data conversion to the Casio format. formation to the But first, let’s talk about why he chose the PIC16F84. The chip supports Casio, which per- data tables as long as the program memory thanks to its RETLW forms the necessary instruction. It is cheap and powerful enough to handle serial communi- mathematical analyses cations entirely in software. and graphically illus- The next most important chip was the MAX186 A/D converter. He trates the functions. realized that to get stable readings of the least significant bits, he had to Is the XY LCD Graphing keep the digital ground and analog ground separate, joined only at one Data Logger a success? point near the regulator. The MAX186’s good pin layout helped divide You bet. It rings in as 20 input lines from data lines, making a stable reading easily obtainable. times cheaper than any com- To maximize battery life, Alberto used a low-voltage power regulator. parable PC-based solution. By putting the micro and ADC in sleep mode, he found that the unit only You may reach him at requires 50 µA. [email protected]. PIC12CXXX

First Place $3000, HP LogicDart, $500 for using PIC12C508 Guitar Effects Controller—Hank Wallace, Fincastle, Virginia

Hank is an avid guitar player as well as supply of the transmitter. While this may an electronics addict. With this project, sound like a problem, it’s not since the he’s able to bring both his hobbies together. transmitter output is AC coupled to the guitar The problem: when playing live, one of audio path. the most frustrating tasks for guitarists is As the guitarist touches a pad, the contact controlling their sound. Typically, the conducts enough current to turn the transistor problem is solved by placing an array of on and awaken the PIC12C508. After a foot switches on the stage. But, that 120-ms debounce delay, the processor restricts the player to one spot—an unac- qualifies the three inputs, produces a 50-kHz ceptable constraint for rock and roll. pulse train, and sends it along the guitar Instead, Hank mounted three cable to the receiver mounted inside a inexpensive aluminum-tape pads to commercial DSP-based guitar-effects the pick guard. A small transmitter processor. under the guitar’s phone jack senses The receiver decodes the databurst, touches on the three metal pads. A determines which key pads were activated, transmission is triggered by the and then connects one or more foot-switch resistance of the body from the pad to ground. terminals in the processor to ground for 250 ms, Notably, the “ground” of the transmitter is actually the VCC of thereby simulating the foot-switch operation. the microprocessor since the reference for the pads is not ground, but the +3-V He may be reached at [email protected].

Second Place—$2000 Third Place—$1000, $500 for using PIC12C508 Internet Appliance—Myron Loewen, R/C Brakes—Greg Mrozek, Niverville, Canada New Hope, Minnesota Lots of companies today like to boast about having the smallest Even when you’re racing radio-control cars, you can’t forget to use the Internet server, and while theirs are impressive, Myron puts all them turning signal. And, woe betide the car that tailgates if your brake lights all to shame. aren’t up to snuff. With an 8-pin PIC12C672, Myron handles all the tasks of dialing But, Greg fixes all that with R/C Brakes, a brake light and/or turn-signal an ISP, negotiating PPP configuration and compression options, controller for radio-control cars. The device takes input and power from the negotiating IP configuration options, authenticating itself with PAP, servo outputs of a standard radio-control receiver and uses these signals to finding its IP address, implementing PING protocol, and implementing control the brake lights and turn signals mounted on the body of a radio- TFTP. control car. On the hardware end of things, the only real difficulties came in The RX signal from the servos is normally low with a high-going pulse length determining which port to use for which functions so that the number of 0.8–2.1 ms. A software capture algorithm captures this pulse width and of analog inputs was maximized. then uses the information to control the tail lamps. And in the software department, you’ll find a lean-mean state As well, R/C Brakes is completely configurable, enabling it to operate machine. As packets arrive, they are examined to see if a reply or state correctly on almost any radio-control car. You can program the device change is required. And, if nothing arrives within a set amount of time, through a single push button, and the configuration data is stored in a serial each state has its own job to do. EEPROM. He may be reached at [email protected]. You may reach Greg at [email protected]. PIC16CXXX

First Place

$3000, HP Logic Dart, $500 for using PIC16F84 BitScope Mixed Signal Capture Engine—Norman Jackson, Stanmore, Australia

The BitScope Mixed Signal Capture Engine is an RS-232 peripheral device intended provide an analog bandwidth close to for data-acquisition applications where a digital sampling oscilloscope 100 MHz, so you can use subsampling or logic analyzer would be used. It is capable of techniques to reconstruct repetitive wave- complex triggering and simulta- forms above Nyquist’s sampling frequency. neous recording of analog BitScope is programmed via scripts from data and digital logic states a host attached to the serial port. The as well as time/frequency scripts are virtual machine instructions that measurements. This 50 MS/s synthesize the required functionality. digital signal oscilloscope The PIC communicates with the host via and logic-analyzer capture en- a standard serial communications link, so gine is constructed using a anything from a palmtop to a workstation PIC16F84, a Lattice 1016 PLD, can interface to it. According to Norman, two 32-KB cache RAMs, and a this excessive computing power should flash ADC. enable the construction of a complex vir- A PIC-controlled synchronous tual instrument from a small set of capture clock circuit allows single-step or primitives implemented in the BitScope free-running operation of sample microcontroller. RAM. High-performance op-amps You may reach Norman at bitscope@ and a wide-bandwidth ADC chip discrete.net.

Second Place—$2000 Third Place—$1000 Hydrocare Hydrotherapy System—Troy Harvey, Mobile Environmental Control from a Wheelchair— Provo, Utah Dan Leland, Coquitlam, Canada Feeling a little tight and achy? Troy has the bed for you.The hydrocare Dan wants to enable people with little or no limb function to access Hydrotherapy system is a therapeutic massage bed that provides a full body common household appliances without assistance. His goal: to design massage via high-pressure warm-water jets without getting the user wet. A and build a simple scanning input device using the PIC16C84 that gel-filled sound-dampening waterproof membrane fully relays the water would serve as the front end for a versatile universal IR remote. With pressure and keeps the user dry. the device, the user could access a variety of TV and stereo components Hydrocare’s electronics are controlled by a PIC16C74A. The chip as well as X-10-enabled devices from anywhere in the home. coordinates many functions: a hand-controller keypad and LCD, a real-time Dan first built a Scanning User Interface (SUI) with a 4 × 10 LED session timer, an external timer interface, a token-vending interface, a user- array, corresponding to the buttons on the remote. The device has a definable menu with hardware lockout and EEPROM backup, water-jet variety of ability control switches and operating modes that let the user pump control, a variable-speed PWM water-jet drive motor control, a water- make a selection. jet position LCD readout, a water-jet memory setting, a multilevel water-jet The user scans up, down, and across the LEDs via a sip-and-puff pressure control, a water temperature control, water-tank level sensing, and pneumatic switch (other switches—blink, finger-, head tilt, or a nonvolatile EEPROM-based machine-use odometer. oversize button/paddle—can also be used). Once a selection is With a PIC, the cost of the electronic subsystem fell from $562 to $143. made, the SUI sends the appropriate serial control command through What I want to know is how much would it cost to adapt it to my waterbed? a three-wire cable to the IR remote. You may reach Troy at [email protected]. You may reach him at [email protected]. PIC17CXXX

First Place $3000, HP LogicDart, $500 for using PIC17C756 PIC’Spectrum—Robert Lacoste,Chaville, France What is PIC’Spectrum? It’s an auto- and a log/lin switch, which switches the nomous device able to display the spectrum amplitude display between frequency decomposition of an audio band logarithmic and linear scales. signal. And, there’s no PC. Apart from a voltage PIC’Spectrum is a small box with a regulator and a quad op-amp for signal microphone or audio line input at one amplification, the only other active end and a standard VGA output component is the PIC17C756. The PIC has connector on the other. It displays on enough internal resources to do everything the video monitor the spectrum of an from signal acquisition to video generation incoming sound and updates it in real through real-time FFT. The PIC replaces the time (e.g., 10 refreshes per second). ADC, DSP, and video generator, which Of course, PIC’Spectrum is a digital make up the classic design of a digital spectrum analyzer. The incoming spectrum analyzer. signal is first digitized and its spectrum The PIC17C756 may not have an computed with a 256-point Fast integrated video controller, but it does Fourier Transform. The correspond- have enough horsepower and program ing video image is software- memory to do software-generated video. generated on-the-fly. All by itself, PIC’Spectrum directly drives This compact device has only the VGA CRT at a high level of quality. three controls: a signal-level potentiometer, You may reach him at rlacoste@ a run-hold switch, which freezes the display, nortel.com.

Second Place—$2000 Third Place—$1000 Sky Scanner—Adam Lyness, Christ Church, Spectra Post Processor—Reid Wistort, Westford, Vermont New Zealand Reid made this project not to win a contest, but to hear better. In 1989, he received So just where does the sky meet the ground? a cochlear implant, which consists of a body-worn speech processor and a surgically With Sky Scanner, you can find out. Adam uses a miniature implanted receiver/stimulator that includes an electrode array placed in the snail- CCD camera and logic to capture a video image of the shaped cochlea, deep in the skull. Essentially, a microphone in the earpiece picks up horizon. Based on the slope and offset of this line, the a sound, which the processor analyzes, digitizes, and encodes into an RF signal, PIC17C44 determines the attitude of the sensor. which is then passed through the skin to the implanted receiver. While conventional tilt sensors can do essentially the same But despite many adjustments, Reid’s speech recognition was sporadic and he thing, Sky Scanner has a distinct advantage. It’s immune to could not use the phone. He realized that the EEPROM settings on his implant were acceleration. It uses the horizon, not gravity, as a fixed wrong. reference. It measures 360° of roll, 70° of pitch, and processes The solution: he uses a three-processor system (PIC17C44, ‘17C42, and ‘16C74), about 25 updates per second. which intercepts, decodes, and modifies the RF datastream from his bodyworn implant Its relative accuracy stands at ±1° and its absolute accuracy speech processor before reconstructing a modified datastream that is applied to the is limited only by the presence of obstructions. implanted portion of the cochlear implant. You may reach Adam at [email protected]. He may be reached at [email protected]. Photo courtesy of QNX Software Systems, Ltd. 61 Applied PCs 54 Fred Eady Part2:Data AcquisitionwithVirtual Instruments A NewView Real-TimePC 48 Ingo Cyliax MultimediainReal Time ’x86ProcessorSurvey 41 Pascal Dornier Part1:’386-ClassEmbeddedCPUs 38 BuildingWeb-Enabled Greg Bergsma MobileDevices NouveauPC edited byHarvWeiner PCI DATA-ACQUISITION BOARDS The PCI-6110E and PCI-6111E are high-

NPC speed, simultaneous-sampling, multifunction plug-in data-acquisition boards that have a 12-bit ADC. The boards are PCI-bus masters and sustain 5 MS/s per channel without burdening the CPU. They’re ideal for applications requiring high-speed, simultaneous acquisition, such as vibration analysis, transient captures, phase measurements, spectral analy- sis, and electronics testing. Both boards are compatible with a wide variety of industry-standard application software, including LabVIEW, LabWindows/CVI, ComponentWorks, Measure, and VirtualBench. The PCI-6110E and PCI-6111E feature four or two differential analog inputs, respectively, with a 12-bit ADC per channel. The voltage input range is bipolar and software-configurable up to ±42 V. Software-programmable gains include 0.2, 0.5, 1, 2, 5, 10, 20, and 50. Both boards feature two 16-bit analog output CompactPCI-COMPLIANT BACKPLANE channels, eight lines of TTL-compatible digital I/O, and two up/ VERO’s new family of 10-layer cPCI backplanes consists of down 24-bit counter timers. All of these features can be user four versions in 3U and 6U formats. All models support geo- synchronized for precise timed acquisition and generation. The graphic addressing, hot-swap pin sequencing, and 32-/64-bit boards use a custom-programmable instrumentation gain ampli- interoperability, with pin allocations and lengths defined for future fier to ensure high-quality measurement and excellent accuracy. insertion (currently at Draft 0.5 status) and with clock routing The PCI-6110E and PCI-6111E sell for $2995 and $2195, changes according to V2. Standard models operate at 33 MHz respectively. and are selectable for operation at 66 MHz. Models are user- selectable for operation between 5 and 3.3 V. Power can be National Instruments brought onto the board using power bugs, a bus bar, Fastons, or 6504 Bridge Point Pkwy. a standard ATX psu–format connector header. Austin, TX 78730-5039 The entry-level backplane is a 3U, 32-bit, eight-slot unit, which (512) 794-0100 reduces cost by limiting the power-on option to Fastons only. For Fax (512) 794-8411 powerful computing needs, a 64-bit backplane is available in 3U www.natinst.com and 6U formats without support for rear plug-up modules. This unit, which offers bandwidths up to 264 MBps, is useful for semicustom #510 applications where additional space is useful in combining a proprietary bus into the standard cPCI on a monolithic backplane. The development systems, which can be fitted with any of the cPCI backplanes, consist of a VEROtec half-width case, a KM6-RF subrack, and an ATX psu. Thermal management and EMC screening are available. The systems also feature a power- sequencing module to ensure that power rails are presented and removed in the correct order at powerup and shutdown. Fully specified cPCI backplane and development systems start at $400.

VERO Electronics, Inc. 5 Sterling Dr. Wallingford, CT 06492 (203) 949-1100 • Fax: (203) 949-1101 www.vero-usa.com #511

NouveauPC edited by Harv Weiner 38 CIRCUIT CELLAR INK JUNE 1998 NPC

PC MODULES WITH NEW FORM FACTOR Adaptive Systems has designed a set of off-the-shelf 2″ × 3.5″ power, and small form-factor applications. printed-circuit assemblies that can be combined to offer a custom Passthrough connectors enable modules to be inter- PC “motherboard” in a variety of physical configurations. This connected by stacking them onto an array of pins in four patented interconnect strategy provides unparalleled mechanical basic orientations. The nC52 interface chip senses the flexibility and improved system reliability by eliminating orientation and automatically configures itself to properly swap backplanes, internal cables, and complex mounting assemblies. signals in order to present a consistent interface to the remaining The nC52 provides increased performance over PC/104 mod- circuitry on the module. This technique keeps signal lines short, so ules in a quarter of the space, while reducing power consumption. the bus can operate at high speeds without termination concerns. The nC52 product line features highly Available products include ’586 and ’486 processor modules, integrated components for building a VGA interface module, an I/O module supporting serial and PC-compatible engines for parallel ports, two IDE devices, and two floppy drives. Also portable, low- available is a 8051 system-management module, a Sound Blaster-compatible audio subsystem mod- ule, and a dual-port PC Card interface module. Prices start as low as $80 per module.

Adaptive Systems, Inc. P.O. Box 1150 Niwot, CO 80544 (303) 247-1317 Fax: (303) 247-1318 www.adaptivesystems.com

#512

FLAT-PANEL LCD DRIVER BOARD Arcom has introduced the AIM-104-LCD-3, a PC/104-format module that runs either VGA CRT monitors or VGA LCD flat-panel displays. The board drives a wide range of commercial flat-panel display types like analog CRT monochrome single- or dual-scan STN, dual-scan color STN, and color TEF. The AIM-104-LCD-3 interfaces through a standard 50-way box header ribbon-cable connector. The board is supplied with 512 KB of video memory that provides the user with video formats up to 1024 × 768 in 16 colors and 640 × 480 in 256 colors. A supplied utility disk includes standard drivers supplied by Cirrus, including CLMODE and a TSR (terminate and stay resident) application that allows the user to swap between CRT, flat panel, and simultaneous mode. The AIM-104-LCD-3 sells for $220.

Arcom Control Systems, Inc. 13510 S. Oak St. • Kansas City, MO 64145 (816) 941-7025 • Fax: (816) 941-7807 www.arcom.co.uk #513 NouveauPC JUNE 1998 EMBEDDEDPC 39 PENTIUM II SBC WITH VIDEO OR CREATIVE SOUND Interlogic has introduced a Pentium II SBC The boards are available for $495 quantity one, no video, that comes in two versions: Creative Sound and for $595 with video.

NPC Blaster 16 and Roland MPU 401 UART mode- compatible audio or ATI 264VT 64 bit PCI Graphic Interlogic Industries Accelerator with 2 MB of display DRAM. Both versions 85 Marcus Dr. • Melville, NY 11747 include full support for the Pentium II processor at speeds up (516) 420-8111 • Fax: (516) 420-8007 to 333 MHz. They also feature 512 KB of onboard L2 cache, www.infoview.com #514 memory up to 256 MB of fast page mode EDO or BEDO DRAM, and the 440-series chipsets with dual bus-master PCI EIDE controller interface for fast data transfer. The Award flash BIOS with plug-and-play is auto- configurable and provides a full selection menu for custom setups, including master/slave interface, watch- dog timer, page mode, and mode-4 timing. Also included is support for USB and IrDA, two high-speed 16C550-compatible serial ports, and one bidirectional parallel port with EPP/ECP functions. As well, these SBCs feature a PS/2 mouse port; BIOS support for LS- 120, ZIP, and CD-ROM drives; and a socket for a Disk- On-Chip flash disk. NouveauPC

40 CIRCUIT CELLAR INK JUNE 1998 EPC 41 could include “stock running low,” Each vending machine will support remote Since DVI has some pretty big custom- Each machine will automatically report Each delivery person will carry a hand- contact the head office directly print service details for the customer gather restocking information, then trans- instantly retrieve stock details from any fer that information to DVI’s central data- base and invoicing system vending machine • • ers, the system must also provide remote • queries, whether from head office or from any delivery truck. As a result, delivery staff can get detailed, up-to-the-minute informa- tion on how many candy bars—and how much cash—is in each machine. problems to DVI’s head office. These mes- sages “out of change,” and “tilt.” (You never know when Homer Simpson will attempt brute force to elicit candy from the machine.) held computer (HHC) that can: • PC MBEDDED E 1998 1998

reg Bergsma JUNE G Here’s the scenario: I’ve been asked to Similar issues apply to any embedded What kind of tools do you need to build

design a new delivery solution for a highly successful—and entirely fictitious—vend- ing machine company, Dynamic Vending Inc. (DVI). Management at DVI has de- cided that the next generation of vending machines and delivery systems will be highly functional and Web based. Web server a browser-enabled HHC might talk to. It has to be small and configurable, and it needs to let you easily change the form and content of your dynamic HTML without having to recode and retest the Web server itself. this kind of Web technology? To get an idea, follow along as I build the Web into a vending application. well, browse. One browser works much like the next. But if you build a browser into a hand-held medical device, that browser DYNAMIC VENDING, INC. needs to look and behave quite differently. Mobile Devices uilding Web-Enabled uilding B ll of us have used the Web on our But what about using the Web in embed- Many embedded devices use Web These devices display information, so But, there’s a problem. On the desktop, desktops. It’s become a standard part of the way we work. technology today—phones, PLCs, PDAs, TVs, photocopiers. At the same time, mo- bile computing is on the rise. Hand-held devices are finding their way into healthcare, telecommunications, manufac- turing, security, banking—you name it. they’re prime candidates for browsing technologies, be it to download informa- tion from a remote database, send E-mail to the head office, or troubleshoot a black box. From the embedded developer’s per- spective, the opportunities are endless. a Web browser is something that lets you, able to readily customize the technology for your embedded application. ded devices? It can fit anywhere you need to serve up or display data using classic client/server architecture. The key is being retesting the Web server. He predicts it’ll be a boon for the vending industry. retesting the Web server. A Want Want to a hand-held unit? If so, Greg shows you how design a Web appliance into and and content of your dynamic HTML without recoding to easily change the form from aremotebrowser.Ofcourse,the HTML toanyonequeryingthemachine HTML. TheWebservercanthenservethat levels, etc.)andformatthatinformationin status ofthemachine(stocklevels,cash mechanism forgeneratingdynamicHTML. 42 machine needsamodemornetworkinterface. with anembeddedWebserver,along vending machine.Ineedtoequipeachone OFF-THE-SHELF TECHNOLOGY each HHCneedsaWebbrowser. vending machinesfromtheirHHCs.So server soDVIcanremotelyqueryeach is—particularly theWebtechnologies. shelf. Well,atleast,mostofthesoftware only waytodothisisifeverythingoff-the- company name). outstanding lawsuitovertheirswipingthe Vending DynamicsInc.(there’sstillan customer’s URLby searchingviathecustomer’s name inthedatabase. coding changes made tothefunction a customername andotherappropriateoptions. Theprogramlistingintheforefront showsthe tion Builder(PhAB).Herethelabels inthemenuhavebeenchangedsothatusercanenter Photo 2—Customizationofthestandard VoyagerbrowserisdonethroughthePhotonApplica- months togetajumponDVI’sarchrival, This mechanismwillretrievethecurrent The deliverystaffneedstoquerythe To start,IneedanembeddedWeb Three months!Aretheseguysnuts?The

One morething—Ihavethree machine separately. EPC DVI todialupeachvending And thesystemshouldn’tforce dreds ofvendingmachines. access tositeswithhun- fmenu_url() a • • vending machineshould: on thedeliveryperson’sschedule. other things,keeptheheadofficeupdated The E-mailclientintheHHCwill,among transmit anyproblemstoDVI’sheadoffice. of menusandbuttons. time tomesswithlots staff doesn’thave face—the delivery the browserinter- need tocustomize display. I’llprobably from apen-sensitive and easilycontrolled need somethingsmall the vendingmachinewillautomatically chine andintheHHC.TheE-mailclient in thevendingma- ded E-mailclientboth browser won’tdo.I ventional desktop optionallyconnecttothecustomer’sE- beabletotakeadvantageofthe mail server(toreportproblems) sible viamodem mit data)ifpossible,otherwisebeacces- customer’s Ethernetbackbone(totrans- . Withthis,itis possibletoretrievethe In additiontothesetechnologies,each I’ll useanembed- CIRCUIT CELLAR INK JUNE CIRCUIT CELLAR Obviously, acon- shows on-linecontentfromaflash-residentdemonstrationunit. Photo 1—Beforecustomization,theQNXIn-Handdemobrowser 1998 BUILDING THEHHC • ton andiscustomizable throughPhAB flash memory. used tobuildthedemosthat ship inthe the toolsanddemoapplications thatwere QNX RTOS,thePhotonmicroGUI, andall on thedesktopPC.TheCDincludes the on theCD,whichIinstalled apartition display showninPhoto1. flash memory—andpresto!There’sthe power, thesystembootsfromonboard reference designfromAMD.Pluginthe CD andtheµforCE,anewhand-held the HHC. ware andhardwarethatletsmecustomize Toolkit offersasuiteofoff-the-shelfsoft- tomized. Fortunately,theQNXIn-Hand browser softwarethatcanbereadilycus- software designfortheHHC. challenge istoadoptahardwareand with thisschedule,anyway?),thebiggest like Figure1. bar-code readerandreceiptprinter. dard PDAcomponentsaswella fice systems.And,ithastosupportstan- database cansynchronizewithhead-of- database withODBCfunctionalitysoits machine modems.Itshouldhavealocal phone technologytoconnectvending- For onething,itneedssomecellular- permittheheadofficetogatherstatistics of machines on individualmachinesandgroups The Voyagerbrowser runsunderPho- The wholedevelopmentenvironmentis The kitprovidesasuiteofsoftwareon Perhaps themostdifficulttaskisgetting Given thetimeframes(whocameup When Iputeverythingtogether,itlooks The HHChassomerequirements,too. EPC 43 forCE board, pictured on the forCE board, pictured µ cover (p. 37), includes all the hard- cover (p. 37), includes

The EPC can develop custom can develop a matter of browsers in took hours. The modifications an hour, including me about code and a caffeine the database In- any other QNX break. To modify E-mail (e.g., the Hand applications dialer), you can client and Internet use the same environment. µforCE HHC HARDWARE So how exactly can you implement So what technology is needed for the The circuitry for all these devices can The machine needs to track stock quan- As the system overview in Figure 1 shows, QNX features a low-overhead sendmail Just plug a bar-code scanner into the vending machine? It has to support several be readily driven from a PC-based hard- ware design—something in a PC/104 form factor, for example. tities for each product, the coin levels in collection and change canisters, and any machine-specific status values. generator. The same API and development tools work for both the HHC and the vending machines, which saves precious development time. IMPLEMENTING DYNAMIC HTML dynamic HTML in something like a vending need. Next, submit your design to a custom PCB/board manufacturer and they’ll make a swag of them to spec (see Figure 2). BUILDING A VENDING MACHINE interfaces. It needs an LCD or an LED display. It should accept and return coins and let users select the products they want. And, of course, the products have to get to the user. server to provide status values, an E-mail client to report problems, mechanisms for generating dynamic HTML, and Ethernet and/or modem connections. client, a Web server called Slinger (only 14 KB of code), and a dynamic HTML offers audible notification for delivery staff. a serial interface (to scan candy bars), add parallel interface (to support a receipt printer), and leave out anything you don’t each machine also needs an embedded Web ware components you need—a pen-sensitive ware components you slot, and the Élan- LCD screen, a PCMCIA specifically for SC400, which was designed Its audio support also power-sensitive devices. rel- fect) PC . Next, fmenu_ PtWeb- widget. HHC server executes. resource, Browser Delivery Database Head-office E-mail server Browser E-mail client Browser environment, you in the TCP/IP stack local database TCP/IP stack Once you get used Once the code re- MBEDDED , which tells the Bar-code scanner service printer Modem Cellular E to this ized browser looks like Photo 3. As you see, entering the customer name “QNX” retrieves a page from a vending machine’s Web server. the widgets (so resource updates take ef evant components of the application. You see the PhAB envi- ronment in Photo 2. compiles, the custom- and recompiles all Modem sets a widget resource fmenu_url() PSTN customer_text 1998 1998 PtGetResources() Modem widget through another function, . The user types their customer JUNE Pt_ARG_WEB_GET_URL These changes are made through PhAB. Next, I want to retrieve the appropriate fmenu_url() To retrieve the text entered by the user, Changing the File menu so users can This system overview shows the various compo- This system overview look up the URL in the database that corre- sponds with the customer’s name and then set the which causes the browser engine to retrieve the Web page. The modified callback code appears in the forefront of Photo 2. Once the code is modified, it regenerates enter a customer name consists of two steps. To make an intuitive interface, I change the title of the “File” menu to “Customer” and rename “Goto URL” to “Customer Name.” URL when the user enters a customer name. To do this, I make a simple modifi- cation to the callback function url() name into the enter a URL. When the user hits Enter, a C enter a URL. When the callback function send a call to Pt_ARG_WEB_GET_URL Client PtSetResources() browser engine to retrieve the Web page. Vending Vending Vending Machine Machine Machine Web server Web E-mail client TCP/IP stack . Figure 1— nents needed by vending machines, HHCs, and head-office nents needed by vending data can be via mo- servers. Access to vending-machine and optionally via the customer’s dem (including cellular) Ethernet backbone. PtWebClient . In turn, the engine informs The browser is actually two programs. The browser is actually The interface (client) talks to the engine All graphical demo applications that All graphical demo applications The default browser expects the user to When you bring up the browser’s “File” With an architecture like this, customiz- Widgets can have code attached Widgets can The interface has been separated from the a underlying browser engine to create client/server architecture. (server) through a GUI widget called Photo 3—After customization, the browser shows typical Web content supplied by the Web server in the vending machine. without having to understand the com- plexities of the browser engine. enter a URL. But DVI users are too busy to enter a URL for each customer and each machine. Instead, I’ll let them simply enter the customer name. The HHC database can look up the appropriate URL. menu under PhAB and choose the “Goto URL” item, you see a dialog that lets you You can freely modify the browser interface information. The interprocess communication between the two programs is handled by a callback mechanism in PtWebClient the interface of progress, status, and other ing the browser becomes straightforward. THE HHC BROWSER come in the flash memory are custom- come in the flash memory Let me give you izable through PhAB. done by custom- an idea of how this is this DVI HHC. izing the browser for (Photon Application Builder), an inte- Builder), Application (Photon lets development tool that grated GUI buttons, labels, windows you add objects known as widgets. and other result is executed as a to them, which mouse of event (e.g., a of some sort code is a com- click). This callback plete C function. physical HTMLfile onpermanentmedia. quent fileI/O requests withouthavinga “pathname” space andhandlingthesubse- mented throughadoptingaportion ofthe Figure 3—UnderQNX,dynamicHTML isimple- 44 system doesn’tsupportwritingtotheHTMLfile. are which thegeneratorreplies.Themainrequests messages withastandardformat,through quests ( 1.html tion call,specifyingthefile with the is responsiblefor.Inthiscase,I’mdealing know whatpartofthepathnamespaceit tor andseehowitworks(seeListing1). that reflectsthecurrentstateofsystem. vending machineandgeneratesHTML generator probesthehardwareof Whenever thenamedfilesareread,this runs separatelyfromtheWebserver. tions toanHTML-generatorprocessthat flash memory,thenamedfilesexistasconnec- message withatypeof a bufferforthedata,andthencalls quent I/Orequestsarebased.Itallocates becomes the“handle”withwhichsubse- allocates anOCB(opencontrolblock)that sions ofthecallingprocessand,ifOK, the filepermissionsagainstpermis- ered tothegenerator.Thegeneratorchecks to bedirectedtheHTMLgenerator. write() space (seeFigure3). filenames inthefilesystem’spathname implement thedynamicHTMLpagesas modification oftheWebserver.Youcan flexible approachthatdoesn’trequireany In-Hand toolkitimplementsauniqueand generates newHTML. First, thegeneratorletsOSkernel Let’s lookatthedynamicHTMLgenera- When theWebserveropensfile,a These requestsaredeliveredasstandard Rather thanbeingstoredondiskorin The Web-servertechnologyintheQNX cessed, itqueriesthehardwareand open() Embedded Web Server Embedded Web

dynamic HTMLpageisbeingac- EPC . ThisactioncausesallI/Ore- open() qnx_prefix_attach() , etc.)for ded Webserver.Whena HTML File , tion directlyintoyourembed- read() Requests File I/O approach istoaddafunc- , /usr/httpd/1.html machine? Theclassic close() , and IO_OPEN HTML Generator /usr/httpd/ Dynamic close() , read() isdeliv- func- . My , program tryingtowritethefile. passed backthroughin ENOTSUP allocated asaresultofI/Ocallsonthefile. So, youshoulddeallocateanyobjects offset memberoftheOCBstructure. you areuptointhebufferbyupdating time youretrievedata,keeptrackofwhere HOW ITALLFITS be supported,butthisisthegutsofit. equipped thedelivery staffwithmyspiffy works inpractice. them. Now,let’sseehowthewhole scheme well ashowImightimplement someof components requiredforthis projectas data isremaining(whicheversmaller). amount ofdatarequestedorwhatever exhausted. Ifitisn’t,wereplywiththe the data.Simplychecktoseeifdatais ceived whentheWebserverisretrieving that buffer(seeListing2). fill_buf() associated chipsetsthatyouwouldfindinmostHHCdesigns. Figure 2—TheµforCEdemonstrationincludestheAMDÉlanSC400microcontrollerandall IO_WRITE IO_CLOSE CIRCUIT CELLAR INK JUNE CIRCUIT CELLAR It’s threemonths later,andDVIhas So far,I’veshownyousome ofthe There areafewotherfunctionsthatneedto Data isreturnedvia Messages oftype Matrix Scan isreturned.Itendsupbeing Keyboard 480 toputtheHTMLcontentinto tellsyouthefileisclosing. × 320 isnotsupported,so Row/Column Keyboard Replymx() LCD Ctrl LCD Data IO_READ errno Addr/Data Mem 1998 1 MB Buffer arere- DRAM Serial tothe Port Microcontroller . Each ÉlanSC400 × Control Mem 16 Module Infrared Control 2 MB ROM for thecustomer. uses theHHCto printoutaservicereceipt HHC’s database).Beforeheleaves, Dave bedded Webserverandthensaved inthe (provided bythevendingmachine’s em- custom browsertogatherthestatus details moves themoney,anduses the HHC’s status. Hethenrestocksthemachine, re- gates eachmachinetocheckthelatest to stockhistruck. tions hecancoverinasingletripandhow mation, Davedetermineshowmanyloca- across allmachines.Basedonthisinfor- chine, aswellanoverallsummary much productisrequiredforeachma- and getsdetailedinformationonhow (using hisHHCoraremotedesktopPC) out, hequeriesthemachinesateachsite overworked engineers.Beforehestarts of super-caffeinatedcolatohundreds business park,wherehedeliverscartloads bers onthedeliveryteam. workday forDave,oneoftheseniormem- the newsystem?Let’slookatatypical jor locations. enabled vendingmachinesatseveralma- new HHC.IthasalsodeployedtheWeb- Am29F016 × At eachlocation,Daveagaininterro- Dave’s firstdeliveryrunisinahigh-tech But, exactlyhowdodeliverystaffuse Digitizer Controller 8 Flash Controller Intelligent 32-Hz ALXT Power .Wav Audio 10-bit A/D

Crystal

Tritech PCMCIA Control Sys. Data Sys. Address Batteries AA AA Card Mini Card PC Listing 1— The dynamic HTML generator has four main types of I/O requests to handle— open(), read(), write(), and close(). These requests are handled through a well-defined message structure already in place for regular file-system I/O. void main(int argc, char *argv[]){ struct _mxfer_entry mx_entry[2]; int devno; off_t endmem; pid_t pid; msg_t type; int nbytes; mode_t mode; struct ocb *ocb; int size; if (qnx_prefix_attach("/usr/httpd/1.html", NULL, 0)){ perror("prefix_attach"); exit(EXIT_FAILURE);} for (;;) { pid = Receive(0, &msg, sizeof(msg)); type = msg.type; msg.status = ENOSYS; nbytes = sizeof(msg.status); switch (type){

case _IO_OPEN: // check access permissions are OK mode = perm_mode[msg.open.oflag & O_ACCMODE]; __get_pid_info(pid, &psdata3, fd_ctrl); mode &= (mode & 077) | /* reuse lower 6 bits for handle */ (psdata3.euid == 0) ? S_IRWXU : (psdata3.euid == fstat_reply.stat.st_uid) ? (fstat_reply.stat.st_mode & S_IRWXU) : (psdata3.egid == fstat_reply.stat.st_gid) ? (fstat_reply.stat.st_mode & S_IRWXG) << 3 : (fstat_reply.stat.st_mode & S_IRWXO) << 6; if ((mode & S_IRWXU) == 0){ msg.status = EPERM; break;} // permission check OK—allocate control block if (msg.open.path[0] != '\0' { msg.status = ENOENT; break;} if (!(ocb = (struct ocb *) malloc(sizeof(struct ocb)))){ msg.status = ENOMEM; break;} memset(ocb, 0, sizeof(struct ocb)); ocb->mode = mode; ocb->count++; // attach a handle (fd) to the ocb for use later on if (qnx_fd_attach(pid, msg.open.fd, 0, 0, 0, 0, (unsigned) ocb) == -1){ free(ocb); msg.status = errno; break;} if ((ocb->buf = malloc(BUFLEN)) == NULL){ free(ocb); msg.status = errno; break;} ocb->offset = 0; fill_buf(ocb->buf); // fill data buffer with HTML data msg.status = EOK; break;

case _IO_CLOSE: // release all allocated objects - ocb/buffer/fd ocb = (struct ocb *) __get_fd(pid, msg.close.fd, fd_ctrl); if (ocb == (struct ocb *) 0 || ocb == (struct ocb *) - 1) { msg.status = EBADF; (continued)

JUNE 1998 EMBEDDEDPC 45 Listing 1— continued

break; } if (--ocb->count == 0){ free(ocb->buf); free(ocb);} qnx_fd_attach(pid, msg.close.fd, 0, 0, 0, 0, 0); msg.status = EOK; break;

case _IO_READ: ocb = (struct ocb *) __get_fd(pid, msg.read.fd, fd_ctrl); if (ocb == (struct ocb *) 0 || ocb == (struct ocb *) - 1){ msg.status = EBADF; break;} if ((ocb->mode & S_IREAD) == 0){ msg.status = EBADF; break;} if (ocb->offset == -1){ // Already at end of file msg.read_reply.status = EOK; msg.read_reply.nbytes = 0; msg.read_reply.zero = 0; _setmx(&mx_entry[0], &msg, sizeof(struct _io_read_reply) – sizeof(msg.read_reply.data)); Replymx(pid, 1, &mx_entry); nbytes = 0; break; } // reply with the minimum of either the size of data request // or size of data remaining in buffer size = min(msg.read.nbytes, strlen(ocb->buf) - ocb->offset); _setmx(&mx_entry[1], ocb->buf + ocb->offset, size); msg.read_reply.status = EOK; msg.read_reply.nbytes = size; msg.read_reply.zero = 0; _setmx(&mx_entry[0], &msg, sizeof(struct _io_read_reply) – sizeof(msg.read_reply.data)); Replymx(pid, 2, &mx_entry); nbytes = 0; // update data offset and access time ocb->offset += size; if (ocb->offset >= strlen(ocb->buf)) ocb->offset = -1; fstat_reply.stat.st_atime = *timep; break;

case _IO_WRITE: msg.status = ENOTSUP; break;} if (nbytes){ Reply (pid, &msg, nbytes);}}}

When the vending machine has problems, the network, which then transfers the data they automatically dial the DVI head office via ODBC. (or an ISP, for that matter) and send an appropriate E-mail message. Now, you might A SWEET ENDING be wondering, what if there are dozens of As you can see, adopting off-the-shelf machines at one site? You need modems Web technologies can significantly reduce and phone lines for each one, right? development time for hand-held devices. With inherent distributed networking, In fact, deciding you can use Web technology a network of machines looks like a single is probably the biggest hurdle to overcome. logical machine. So if I network the machines Having the flexibility to customize both together, they can all share the same browser and server opens Web technologies modem and even the same IP address. to a myriad of embedded applications. So, Finally, Dave drives back to the ware- keep an open mind and ask yourself house and updates the central database. whether you could use Web technologies To do this, he simply hooks up his HHC to in your next implementation. EPC

46 CIRCUIT CELLAR INK JUNE 1998 Listing 2—The dynamic HTML content is written into a data buffer through a series of sprintf() function calls. The data is retrieved from the buffer through I/O_READ messages.

void fill_buf(char *buf){ char *p = buf; int i;

// set up HTML header p += sprintf(p, "\n\nDynamic Vending Inc.\n"); p += sprintf(p, "\n"); p += sprintf(p, "

Dynamic Vending Inc."); p += sprintf(p, " - Machine Summary

\n"); p += sprintf(p, "
"); p += sprintf(p, detail->customer_name); p += sprintf(p, "

\n"); p += sprintf(p, "
Machine Number : "); p += sprintf(p, "%d", detail->machine_number); p += sprintf(p, "
Location : "); p += sprintf(p, detail->location); p += sprintf(p, "\n
Date of last service : "); p += sprintf(p, "%d/%d/%d", detail->day, detail->month, detail- >year); p += sprintf(p, "
\n");

// set up table header p += sprintf(p, "

\n"); p += sprintf(p, "\n"); p += sprintf(p, "\n"); p += sprintf(p, "\n"); p += sprintf(p, "");

// set up each row for (i=0; i < detail->number_of_products; i++) { p += sprintf(p, "

", detail->product [i].product_name); p += sprintf(p, "", detail->product [i].capacity); p += sprintf(p, "", detail->product [i].current_level); p += sprintf(p, "");}

// page trailer p += sprintf(p, "

"); p += sprintf(p, "Product"); p += sprintf(p, "Capacity"); p += sprintf(p, "Current

"); p += sprintf(p, "%s

"); p += sprintf(p, "%d

"); p += sprintf(p, "%d


"); p += sprintf(p, "
© Dynamic Vending Inc. "); p += sprintf(p, "1997
\n\n");}

Greg Bergsma serves as senior technol- SOURCE ogy analyst at QNX Software Systems. QNX In-Hand QNX Software Systems He has also worked on real-time trans- 175 Terence Matthews Cres. action processing and embedded gam- Kanata, ON Canada K2M 1W8 ing terminals, as well as developing a (613) 591-0931 variety of demanding real-time applica- Fax: (613) 591-3579 www.qnx.com/inhand tions from plastics injection molding systems to children’s television game IRS shows. You may reach him at gbergsma@ 410 Very Useful 411 Moderately Useful qnx.com. 412 Not Useful

JUNE 1998 EMBEDDEDPC 47 48 greatly lowerthe overallcost.Embedded reduced design timeandcomponentcount tured inrelativelylowvolume, andthe Many embeddedproductsare manufac- market hasreadilyacceptedintegrated CPUs. O weaknesses of’386sfromAcerLabs,AMD,andIntel. tion? TakesomecuesfromPascalasheexaminesthestrengths and How doyouknowwhichCPUisbestsuitedtoyourembedded-PC applica- ductivity” software. increasing resourcerequirements of“pro- in thevolume-PCmarketduetosteadily functionality intotheCPUhasn’thappened MediaGX), furtherintegrationofchipset market. Withsomeexceptions(e.g.,Cyrix abled thehigh-volume,low-costPC-clone simplified motherboarddesignanden- quite highlyintegrated. (e.g., theCommodore64)werealready Even mosthomecomputersatthattime This constructionalwaysmystifiedme. controller basedon(shudder)delaylines. DMA controllers,nottomentionamemory packages fortheinterrupt,timer,and sisted ofapileTTLsandseparate ten yearsago—PCmotherboardscon- On theotherhand,embedded-PC Then alongcamePCchipsets,which

nce uponatime—oratleastabout EPC ’ x 86 Processor Survey 86 Processor Part 1:’386-ClassEmbeddedCPUs ALI M6117C CPU inthegroup. TheDRAMcontroller easiest ofthegrouptodesign with. this partisquitesimpleandshould bethe controller. Comparedtoitscompetitors, controller, real-timeclock,and keyboard see inFigure1,itincludes aDRAM Laboratories ’386SXCPUcore. Asyou M6117, adevicebasedontheAcer select therightpartforyourapplication. present, Ihopeyou’llbebetterableto offs tobemade,sowiththeinformationI class ofCPUs.Asalways,therearetrade- facturers. Nextmonth,I’llcoverthe’486 review ’386-classCPUsfromseveralmanu- decide whichonebestsuitsyourneeds? strengths andweaknesses.Howdoyou turers tokeeptheiroldfabsbusy. ogy, whichisanicewayforchipmanufac- CPUs areusuallybasedonmaturetechnol- CIRCUIT CELLAR INK JUNE CIRCUIT CELLAR At 40MHz,the M6117isthefastest To getstarted,let’stakealookattheALI In thefirstofthistwo-partseries,I But ofcourse,eachCPUhasparticular P ascal Dornier 1998 to executethe significant. power savingsdon’tturnouttobeallthat to slowdownorstoptheCPUclock, unit, butunlessyouaddexternalcircuitry the market. more flexiblethanotherCPUoptionson assigned arbitrarily),buttheM6117isstill True, it’salittledated(e.g.,bankscan’tbe supports fast-pagemodeandEDODRAM. requires atedious sequenceofconfigura- update sequence. Clearingthewatchdog mentation, itmustbestopped duringthe misses themark.Accordingto thedocu- external superI/Ocontroller. ports onchip,soyouneed to addan ever, itdoesn’tfeatureserial or parallel grammable watchdogtimeronchip.How- controller, anIDEinterface,andapro- *SMI, NMI,oraregularinterrupt. The power-managementunitcangenerate For mostdesigns,itshouldbesufficient The M6117hasapower-management Unfortunately, thewatchdog timer The M6117hasakeyboard/mouse HLT instructionwhenidle. EPC 49 Given the Élan In doze mode, the Figure 1a—ALI’s M6117 makes this PC/104- based single-board computer tick. ler, a PCMCIA control- ler, one serial and one parallel port, and a real-time clock. Every- thing runs off a single 32,768-Hz crystal. SC300’s hand-held- computer legacy, its power-management unit is very complex. This processor has multiple PLL clock generators for the CPU clock—both high and low speed. Depending on system activity, the CPU can run at full (33 MHz)or low (4.6/2.3/1.15/ 0.57 MHz) speeds. CPU stops completely and wakes up after grayscale LCD control- On reset, M6117 On this design isn’t The IDE interface in is off, RTC power When system power Another ’386-class processor—AMD’s As Figure 2 illustrates, the SC300 features strobes the power-on value strobes the the XD bus into the (pullup) of register, U2, which flash page of the to the top 64 KB enables access up, it can the BIOS comes device. Once and repro- to shadow memory copy itself to access the gram the page register memory for disk remainder of the flash emulation. be used with a very buffered, and it should I/O decoding is short cable only. The done by the M6117. lithium battery BT1 (VBAT) is supplied by R22 (current limit through series resistor required by safety standards) and diode D2. When power is on, VBAT is powered from +5 V through diodes D3 and D4. Élan SC300—was originally designed for hand-held computers. This one includes just about everything but the kitchen sink. a ’386SX-33 CPU core, a CGA-resolution AMD ÉLAN SC300 PC MBEDDED E 16 EDO DRAM chips × 1998 1998 JUNE The 80-MHz CPU clock and 14.31818- The 80-MHz close to the Series resistors are placed includes a key- The ALI M6117 also The M6117 is a 5-V device. Therefore, One or two 1M and 128–512 KB of flash memory. This memory. KB of flash and 128–512 me if final, so please contact design isn’t in any updates. you’re interested by clock clock are synthesized MHz OSC U7, using a 14.31818-MHz generator reset is a time base. Power-on crystal as packaged in generated by U1, a DS1811 real-time clock re- a SOT-23. The built-in crystal. quires a 32,768-Hz DRAM, and ISA-bus driver for all clock, on layout, strobe signals. Depending able to eliminate though, you may be DRAM signals. series resistors for the keyboard signals board controller. The are connected to a four-pin header. Ferrite beads minimize EMI on the signal and power lines, and keyboard power is fused to comply with safety standards. it doesn’t require any additional voltage regulators. can be used for a total of 2 or 4 MB of DRAM. The 512-KB EPROM, U3, is orga- nized as a paged flash disk. pherals don’t require refresh. The M6117 pherals don’t require refresh. My sample design is for a PC/104 Despite any of these hassles, however, Another problem: accesses to internal Another problem: accesses Memory refresh is a performance leak is a performance Memory refresh module with a CPU, 2–4 MB of DRAM, the pluses of the M6117 definitely out- weigh the minuses. The M6117 is found on PC/104 single-board computers, and it forms the core of the ZF Microsystems SMX/386 PC module. registers are not passed to the outside ISA registers are not passed to debug your bus. When you’re trying analyzer, this feature system with a logic can be a real nuisance. DESIGNING WITH M6117C then be read through configuration registers. then be read through configuration uses the refresh to read an optional 16-bit uses the refresh to read bus. This data can input buffer on the SD tion register accesses. The watchdog can watchdog The accesses. tion register a system to generate be programmed interrupt NMI, or regular reset, *SMI, plans to out. I hope ALI when it times feature. improve this is used for ISA-refresh timing in this design. which wastes more DRAM refresh as well, Modern ISA bandwidth than necessary. peri 50 time clockconnectstothesamepower trollers workbestasbusmasters. is quitestrange.AMD’sEthernetcon- bus mastersofanykind,whichIthink vides manycrossreferences. programmer’s referencemanualpro- the sameregister.Fortunately, functions arecombinedtogetherin switches foreachcardslot. data andaddressbufferspower PCMCIA controllerrequiresexternal nal SRAMasaframebuffer.The The LCDcontrollerrequiresanexter- bus pinsarenolongeraccessible. using theLCDcontroller,manyISA- multiplexed. Forexample,ifyou’re down on doesn’t supportautomaticpower- Also onthedownside,real- AMD’s ÉlanCPUsdon’tsupport Configuration bitsforunrelated Many pinsinthisprocessorare recover. TheAMD’386SXcore

and can take 120–250 ms to ms and cantake120–250 EPC HLT turned offindozemode high-speed PLLisalways . rupt. Unfortunately,the each timerinter- CIRCUIT CELLAR INK JUNE CIRCUIT CELLAR 1998 512 KBofflash. ports 4MBofDRAMand Figure 1b—Thisdesignsup- EPC 51 clock), the × instruction is executed. HLT The ’386EX supports The ’386EX simplicity, the power-man- Despite its The timer and UART can run off a The timer and UART External peripherals can interface to I recommend eliminating the battery- As well, in a worst-case situation of Additionally, the bus turnaround time is Additionally, don’t forget to download the The ’386EX has a integrated watchdog The ’386EX doesn’t include an inte- the full industrial tempera- the full industrial This range can ture range. exceeded if you can even be cooling or a reduced ensure sufficient in your design. duty cycle ’386EX may be the agement unit of the parts I’ve reviewed. most usable of the the part is set up, it Depending on how power-down mode enters either idle or when a separate clock input while the CPU core is separate clock input The ’386EX can’t completely stopped. consumption of the match the low power in standby mode, Élan SC300/SC310 however. And if an external DRAM con- troller is needed (running on 2 situation is likely to be much worse. backed real-time clock if at all possible. Batteries are guaranteed to fail over time. 33 MHz, the data-hold time on write cycles is 5 ns. This timing is likely to cause problems with many ISA peripherals. designs using this part. Be sure to check the Circuit Cellar Web site for schematics of a minimal design using the Intel ’386EX. DESIGN SUGGESTION bus interface. Unfortunately, the timing on this bus interface is too tight. For example, according to the timing spec, there is no set-up time from chip-select valid to *WR low. too short. A data buffer is needed to prevent contention for slower devices like EPROMs. timer. However, it may not work for your application because it stops when the CPU is in idle or power-down mode. grated DRAM controller, so unless your RAM requirements are small enough to live in SRAM, you’re going to have to add an external DRAM controller. This can be implemented in a CPLD or by using the RadiSys R300EX or R380EX controllers. But once you add a DRAM controller, the cost advantage of the ’386EX is gone. ’386EX bus signals or to a simple *RD/*WR “specification update” (a.k.a. bug list) from Intel’s Web site. There are quite a few issues you need to know about that can complicate PC MBEDDED E 1998 1998 JUNE The last ’386-class processor I want to The DMA controller is a 8237 superset discuss here is Intel’s ’386EX. This CPU combines Intel’s ’386SX core with two asynchronous and one synchronous serial ports, a programmable chip-select unit, and some digital I/O. There is no RTC or keyboard interface. The timer and inter- rupt controllers are mostly PC compatible. ing instead of DMA for floppy transfers. INTEL ’386EX (26-bit address counter) but only supports two channels. The DMA signals are multiplexed with one of the serial ports. The DMA control- ler is not fully compatible with standard floppy controllers, so BIOS implementations use poll- SC300. The LCD and PCMCIA controllers are disabled, but everything else is the same. A µ As well, a tricky switch-over circuit is The internal RTC can’t be disabled. An The Élan SC300 has been designed Another AMD processor—the Élan Figure 1c—The M6117 connects directly into the PC/104 and IDE interfaces. Figure 1c—The M6117 connects directly into required to provide battery backup. This doesn’t meet my expectations for a reli- able and economical design. external RTC module must be decoded at a nonstandard address. The BIOS can then copy its contents to the on-chip RTC at powerup. into many portable devices, such as Norand and Symbol hand-held terminals, the Brother Geobook low-cost notebook, and the Nokia 9000 cellular phone. SC310—is a stripped-down version of the plane of the CPU core. This results in a relatively high leakage current of 25 (typical). 52 much externalgluelogictoconnectjust tively slowdevices. write cyclesandreadaccessestorela- to insufficientbusturnaroundtimebetween IMPROVEMENT OPPORTUNITIES cost ofbatteryreplacements. They’re muchcheaperthanthelifetime RTC, IrecommendusinganRTCmodule. buffers. Inthecaseof’386EX,itisdue ’386EX requireexternaldata/address Élan SC300andSC310theIntel at nocost(buskeepersorcurrentmirrors). Most ofthemcouldbeintegratedonchip quire alotofexternalpull-upresistors. and AMD’sÉlanSC300SC310re- many externalcomponents.TheALIM6117 akg 0QP28F 0QP132QFP/144TQFP 208QFP 3.0–3.6V,4.5–5.5V $17.85 @ 100,1k 208QFP Needs external DRAM $30 @ 100,1k 3.0–3.6 V Upto16MB,fastpage External option Upto16MB,fastpage 386SX-33 Intel $38.16 @ 100,1k mW 208QFP 550 V), (3.3 mW 165 $29@100,$25 @1k(ALI) Upto64MB,fastpage Notsupported 73mWdozemode; AMD386SX-33 3.0–3.6 V DRAM support 66-MHz clock Package 73mWdozemode; 0.46W(3.3V,25MHz); Price Notsupported 250mW(5V)inhaltstate 0.86W(3.3V,33MHz) 32,768-Hz crystal 0–70 AMD386SX-33 Temperature range 0.86W(3.3V,33MHz) 4.75–5.25 V Idle power 32,768-Hz crystal External option Voltage range 1.45W(5V,40MHz) 32,768-Hzcrystal(RTC) 386SX-40 ALI Maximum power Coprocessor Input clocks core CPU Ccmail e e e Limited Yes No No *RD/*WR ’386SX, ISA,’386SXoptional Yes Yes Yes ISA,’386SXoptional No 4–8mA 3(8254) recommended Buffers Yes,CGAresolution, No Yes No Yes recommended Buffers 1 1 8–24mAdepending onpin Testability wait programmable 8, No ISA PC compatible 3(8254) Drive capability No 5-V tolerantI/O interface interface XT Bus 4I/O,1memory No PCMCIA No Yes No 3(8254) No controller LCD 4I/O,1memory selects interface XT (limited) DIO interface, IDE chip Programmable Parallel port 11(2 Serial port (2 7 Yes(limited) RTC ATinterface(8042) Keyboard interface DMA channels 3(8254) Watchdog channels Timer Additionally, the’386EXrequirestoo Also, formanyapplications,theAMD Most embeddedCPUsstillrequiretoo RAM forconfigurationinformation. If yourapplicationneedsareliable

shouldn’t havetorelyontheCMOS EPC it atall.AtrueembeddedBIOS through anetwork,iftheyneed get thecurrenttimeofday L 61CADS30ADS30Intel ’386EX AMDSC310 AMDSC300 ALI M6117C mode or EDO mode mode controller (refresh controller mode mode modeorEDO 80-MHzclock(CPU) None JTAG (only 1 MHz, very JTAG (only 1 MHz, very JTAG (10 MHz) (10 JTAG JTAG(only 1MHz,very JTAG(only1MHz,very None × Many designscan ° × 83)7(2 8237) cs 0–70 C Tcase 85)+*M 11(2 8259)+*SMI –40–85 Hlmr)cm. (alak om (Hallmark) (Hallmark) comm. (Hallmark)comm. (5V)halt;0.5-mW 0.12mWsuspendmode 0.12mWsuspendmode otMs No Most limited testfeatures) No limitedtestfeatures) Most supportsPCMCIA2.0 not365compatible,but No Yes, needsexternalbuffers; needsexternalSRAM × × 1401 1 SPP/EPP 16450 in onechip. held computer complete hand- implement a AMD SC300can Figure 2—The × power-management unitsmissthemark. the transceiverautomatically. a UARTmodethatenablesanddisables provide asimpleenhancementbyadding for thistaskisrathercritical.Youcan (normally controlledbyRTS).Thetiming data, thetransceivermustbeturnedoff a multinodeRS-485bus.Aftertransmitting flash memory. about anythingotherthanfastSRAMand ° × 83)7(2 8237) abetcm. 0–70 C Tambientcomm.; 85)+*M 11(2 8259)+*SMI CIRCUIT CELLAR INK JUNE CIRCUIT CELLAR For embeddedreal-timedesigns,most Embedded applicationsfrequentlyuse ° abetid –40–85 C Tambientind. RS-232 × × SRAM Buffer Video SPEPDIO SPP/EPP LCD 1402 16450 × ° × 83)2(8237superset) 8237) abetcm. –40–108 C Tambientcomm.; 85)+*M 10(2 8259)+*SMI ° C Tcaseind. DSMA DSMD 1998 SC300 32,768-Hz SC300 only only SC310 CPU crystal AMD Élan SC300 / *CAS *RAS 1 or2banks power-downmode 1.6W(5V,33MHz) controllerisintegrated) × DRAM 16450,1 MA0–10 / A3–SA23 × PCMCIA SA0–12 ately orafteraprogrammabletimeout,ifPLL power consumption. struction shouldbeenoughtogetlow program. Ideally,executingthe cessive interruptlatencyandishardto SMI isn’tdesirablebecauseitcausesex- care ofpowermanagementthemselves. most modernharddiskdrivescantake timers areawasteofsilicon.Forexample, recovery timeisinvolved.Mostactivity SC300 control 8259)+*SMI control *WE D0–15 only ° ISA C Tcase As well,awatchdogtimershouldn’t Clocks shouldbestoppedeitherimmedi- × MA sync. U B F U B F not throughindexed separate I/Oport, cessible througha forth. Itshouldbeac- powerdown, andso stop duringupdates, CPUs ataglance. ’386-class embedded Table 1—Compare all could bedrivenoutto the DRAMaddress DRAM databus,and should bevisibleonthe isters andDRAM cycles tointernalreg- debug mode,allbus debug support.In need someimproved most embeddedCPUs disable toprotect (which requireinterrupt configuration registers data registeraccess). tween indexand critical periodbe- And finally,Ithink U B F U B U F B F port printer SPP/EPP Memory PCMCIA PCMCIA Flash slot A slot B HLT option the in- EPC 53 IRS 415 Not Useful 413 Very Useful 414 Moderately Useful Schematics for the M6117 design, as for the M6117 Schematics minimal (untested) Intel well as for a are available via the ’386EX design, Web site. Circuit Cellar SOURCES ALI M6117 Inc. Acer Laboratories, Dr. 1830B Bering San Jose, CA 95112 (408) 467-7456 Fax: (408) 467-7474 www.acerlabs.com Élan SC300/SC310 Inc. Advanced Micro Devices, One AMD Pl. Sunnyvale, CA 94088 (408) 732-2400 www.amd.com ’386EX Intel Corp. 2200 Mission College Blvd Santa Clara, CA 95052 (408) 765-8080 Fax: (408) 765-9904 www.intel.com R300EX and R380EX controllers RadiSys Corp. 5445 N.E. Dawson Creek Dr. Hillsboro, OR 97124 (503) 615-1100 Fax: (503) 615-1150 www.radisys.com SOFTWARE PC MBEDDED EPC E 1998 1998 JUNE If you need a faster CPU, high-perfor- If you need a faster information com- So, watch for all the Once you add a DRAM controller to the add a DRAM controller Once you Pascal Dornier is president of PC Engines, a design house for embedded PC hard- ware and firmware. You may reach him at [email protected]. mance floating point, video display, or mance floating point, CPU is going to be PCI bus, a ’486 class application. a better match for your article, I’ll examine ing up in Part 2. In that Cyrix the AMD Élan SC400/SC410, MediaGX, National NS486SXF/SXL, and SGS STPC Consumer. Thanks for reviewing this data goes to Klaus Flesch of Forth-Systeme (Élan SC300/ SC310) and to Jim Stewart of JK Micro (Intel ’386EX). All mistakes are mine. port the full industrial temperature range temperature full industrial port the Other than applications). (e.g., automotive appli- it mainly in cost-sensitive that, I see and can need very little RAM cations that using SRAM. be implemented cost more it is likely to ’386EX, however, money and board space than its competitors. money and board space such as network Interfacing ISA peripherals additional glue logic. controllers also requires The SC300 shines in hand-held applica- If you need to get your design done If you need to get the right amount A basic design requires On the other hand, if power manage- Of course, your choice really depends on your choice really depends Of course, The Intel ’386EX is strong in deeply fast, I suggest going with the ALI M6117. fast, I suggest going in your way. The full Its simplicity won’t get helps. ISA-bus support also Sure, you’ll of glue logic devices—none. peripherals, but have to add external they’ll be your choice. ment is critical, the AMD Élan SC300/ SC310 is the best choice in this group. Expect to spend some time with its jumble of configuration registers. require a lot of peripherals on the ISA bus. embedded applications that have to sup- Table 1 helps you compare these processors. Table 1 helps you compare tion dictate which CPU is best for you. tion dictate which CPU CPU DECISIONS the ISA address bus for easier logic analy- logic bus for easier address the ISA operation this for normal sis. Disabling dissipation. EMI and power reduces both tions. By contrast, the SC310 is most suitable for deeply embedded applications that don’t necessity. The requirements of your applica- requirements of your necessity. The Real-Time PC RPC

Ingo Cyliax

Multimedia in Real Time

Multimedia is an ongoing rage. But as Ingo reveals, a lot of multimedia doesn’t quite make the “real” part of real time. Read on to determine how to quantify your project needs since excessive throughput adds up to more expensive design costs.

Multimedia applications primarily con- Often, multimedia systems are real-time notice a dropped or duplicated video frame, cern encoding and decoding video, im- because of their deterministic response and but missed audio samples are more dras- ages, and audio. This month, I want to throughput. When you generate video and tic, showing up as nasty clicks. discuss some of the tools that are available audio, the system must send each frame of So, how real time is multimedia? In a to real-time multimedia system designers. video at a certain time. It can’t be early or late. system generating standard NTSC video and In particular, I want to look at the Pentium Even worse, the audio stream must syn- CD-quality stereo audio, the video re- 1 MMX architecture, which has been developed chronize with the video. An observer may not quires a field every ⁄60 of a second (~16 ms) to address multimedia applications. and a whole frame (i.e., two fields, Using reconfigurable hardware for because NTSC is interlaced) in 1 multimedia apps seems like a good ⁄30 of a second (~33 ms). fit, and I discuss a possible solution. Of course, video is typically generated in hardware, but MULTIMEDIA FOCUS there’s usually an interrupt for First question: what do I mean each field or frame so the soft- by multimedia? With all the hype, ware can update the frame buffer. it’s hard to get a clear definition. However, a NTSC video line is For now, let’s define multimedia only about 63 µs long, so a as a combination of audio and video 50-µs interrupt latency can clob- data to process in a system. The ber most of a video line! system may be a set-top box or Photo 1—Traftech’s Zephyr decodes an MPEG stream into NTSC or CD-quality audio is 16 bits at PAL analog video as well as audio. It also sports a PC/104+ video server. It doesn’t matter. interface, which brings PCI speeds to the PC/104 form factor. 44.1k samples per second, so

54 CIRCUIT CELLAR INK JUNE 1998 RPC

COMPRESSION ferencing systems, we Digital Audio If you’re interested in learning about multi- worry about the end-to-end media, there’s no shortage of information. latency of the videos commu- In “HDTV—The New Digital Direction” nication path. We need to compress Filterbank (INK 86), Do-While Jones covers multime- a real-life video feed, transmit it over Psychoacoustic dia standards, offers some TV history, and a long-distance channel (e.g., a wide-area Model Scale Factor overviews MPEG, a common encoding network connection, phone lines, or the Calculation & Coding standard. Mike Podanoffsky (“Compressing Internet), and decompress the video at the Audio and Video Over the Internet,” INK 86) other end without too much latency. Quantization & Coding of Audio Bitstream describes JPEG decoding and gives insight If the video stream has much latency, the

Audio Bitstream into multimedia compression algorithms. audio needs to be delayed as well so they I also recommend Video Demystified, remain synchronized. But, communicating Figure 1—The psychoacoustic model decides which is an excellent reference on all with delayed audio is annoying. So, it might what sub-bands of the audio are important. It may be adaptive depending on the type of aspects of digital video. If you still feel under- be worthwhile to use less aggressive video programming involved. For example, dialog stimulated, check out Digital Audio and compression and sacrifice frame rate and and music scores in a movie may require Digital Video. These books have almost resolution to make it fit through the channel. different sub-band scaling. everything about digital audio and video, Two teleconferencing standards—H.320 you have to generate a sample roughly the conversion from analog to digital and (ISDN) and H.324 (telephone line)—encom- every 20 µs. Of course, audio converters back, the transmission of digital informa- pass components that describe video and usually have buffers. tion, as well as compression techniques, audio codec algorithms. They also address And then, there’s the encoding and error detection, and correcting algorithms. signaling, so teleconferencing equipment decoding, which is extremely CPU intensive. Now that you know where to go for the from different vendors can communicate. Encoding MPEG is about 100 times more details, what things are you likely to find in At the other extreme sits the entertainment CPU intensive than decoding and is often done a multimedia system? Let’s look at digital industry, which uses digital video and audio to offline. The video is encoded and stored video first since it’s fairly complex. offer programming to consumers. In this appli- on disk or tape, before being played back Video requires high data rates to transmit cation, the distribution medium—satellite, as a datastream. digitally. However, its information content is CD-ROM, DVD, or even radio broadcast An MPEG decoder has to perform the low, so you can apply compression algo- from local TV stations—is the bottleneck. decoding in real time, while synchronizing the rithms that greatly reduce the amount of To fit the particular programming source decoded video with the audio. If the video data you need to transfer or store. and the consumer, spend some time ana- decoder gets behind or ahead, it may drop The cost of this compression is, of course, lyzing the video information, choosing a or freeze frames. the compression and decompression itself. In compression strategy, and adapting the As you can see, it’s important to quantify general, the higher the compression ratio, algorithm and the available resolution. the computing resources and I/O needs so the the more computing resources required. A feature-length movie, which may be required throughput is guaranteed and the Some tradeoffs are usually possible, distributed using DVD, needs to be high various components remain synchronized. depending on the application. In telecon- resolution and 16:9 (i.e., letter box) format,

Instruction Data Types Description Instruction Data Types Description

PADD[BWD] B,W,D add with wraparound PUNPCKHWD W->D unpack high word to double PADDS[BW] B,W signed add saturated PUNPCKHDQ D->Q unpack high double to quad PADDUS[BW] B,W unsigned add saturated PUNPCKLBW B->W unpack low byte to word PSUB[BWD] B,W,D subtract with wraparound PUNPCKLWD W->D unpack low word to double PSUBS[BW] B,W signed subtract saturated PUNPCKLDQ D->Q unpack low double to quad PSUBUS[BW] B,W unsigned subtract saturated PAND Q AND PMULH[W] W packed multiply high PANDN Q AND NOT PMULL[W] W packed multiply low POR Q OR PMADDWD W->D packed multiply-add PXOR Q XOR PCMPEQ[BWD] B,W,D compare equal PSLL[WDQ] W,D,Q shift left logical PCMPGT[BWD] B,W,D compare greater than PSRL[WDQ] W,D,Q shift right logical PACKUSWB W->B pack word to byte, unsigned saturated PSRA[WD] W,D shift right arithmetic PACKSSWB W->B pack word to byte, signed saturated MOV[DQ] D,Q move to/from MMX register PACKSSDW W->D pack double to word, signed saturated EMMS — empty MMX state PUNPCKHBW B->W unpack high byte to word Note: B -> packed byte (8 bytes in 64-bit MMX register) D -> packed double (2 double in 64-bit MMX register) W -> packed word (4 words in 64-bit MMX register) Q -> 64-bit MMX register

Table 1—Here we have the MMX instructions. Although Intel claims there are 57 new instructions, many are just variants of the instructions for the different packed data types. Source operand to MMX instructions can be any valid Pentium address mode, but the destination must be an MMX register [1].

JUNE 1998 EMBEDDEDPC 55 yet have a frame rate of strategy of encoding the video data. Some-

only 24 fps. A news program, times, operators have to select parameters mm1 b0 b1 b2 b3 b4 b5 b6 b7 by contrast, might be OK at a so video quality is preserved. + + + + + + + + paddb mm0,mm1 RPC lower resolution and in 4:3 aspect In a nutshell, MPEG is optimized for mm0 a0 a1 a2 a3 a4 a5 a6 a7 ratio. decoding. On average, the encoding pro- The two MPEG standards address these cess is about 100 times more expensive Figure 2—The paddb instruction adds eight bytes packed into a quad-word (64 bit) mm1 to issues. The first, MPEG-1, deals with com- than decoding. another byte-packed quad-word mm0 and pressing video and audio for use on CD- Program insertion is a tricky area that falls stores the result in mm0. The actual computa- ROMs. MPEG-2 concerns multiple formats. under real-time processing. Consider a net- tion is eight byte-wide adds in parallel: a(0) = a(0) + b(0), a(1) = a(1) + b(1), ... a(7) = a(7) + MPEG, however, comes at a cost. Even work transmitting MPEG-2-encoded programs b(7). though it has aggressive and adaptable to stations rebroadcasting the programs to compression possibilities, much of the technol- end users. Because the program is MPEG-2 nity to work on such systems. And, PC-based ogy and effort in MPEG is in the encoder. encoded and the compression algorithm is real-time multimedia processing systems MPEG uses spatial and temporal com- partially based temporal compression, which will likely get a big chunk of the market. pression techniques. It analyzes each frame mostly involves sending incremental frames Of course, there are other opportunities of the video sources and computes the through the system, how does the local digital for cool applications of real-time process- differences between frames as well as TV station overlay local programming on the ing of video and multimedia information compressing much of the information in a network feed? using PCs. Consider the special effects single frame. They can decode the stream into uncom- movie industry. The data is then sent as groups of picture pressed or even analog video, overlay the I recently visited a special-effects com- (GOP) frames. Each frame contains some information, and then encode the informa- pany, and while there is a big presence of reference and some incremental frames that tion before sending it to consumers. While SGI in this field, this industry is fully aware reconstruct each frame in sequence. The this may work, encoding MPEG is expen- of the economy of using PC architecture in GOP, in a sense, defines the compression sive and TV stations can’t afford to add their rendering systems. algorithm itself. Do-While’s article reviews latency to the programming. The stuff they do is pretty serious. Film this in more detail. Some systems can do this now, but the is digitized at 4000 pixels per line and at The encoder’s job is to analyze the details are proprietary. As we move into the 16:9 aspect ratio, so we’re talking about programming and come up with a good digital-TV age, there will be a lot of opportu- 2250 lines or 9 million pixels. To get good color resolution, you might use 12-bit RAMDACs and 30-bit color. Now imagine doing this at 24 fps, and we’re now up to 200+ MHz video rates and about 800+ MBps of data . Later, I’ll provide some code examples of using Pentium MMX for chroma-key processing. This special effect is commonly used to make small models appear against a background—like a spaceship against a picture of a planet, or your local weather reporter standing by the weather map. Compressing digital audio, while not as compute-intensive as video compression, is tricky. Humans can deal with noise in video (remember there’s not much information there), but dislike noise, aberrations, or artifacts of our compression in audio— especially if the audio is in multiple channels. There are two methods for compressing audio. One is to reduce the number of bits in each audio sample by using nonlinear quantization. Here, we use many quanti- zation steps at lower sound levels than at high sound levels. At high sound levels, humans aren’t as sensitive to different sound levels as they are at lower sound levels. If you go to a concert, you don’t know exactly how loud it is—it’s just loud. However, it’s possible

56 CIRCUIT CELLAR INK JUNE 1998 Figure 3—The image con- MMX adds eight 64-bit registers and taining the chroma key (x) is x green 57 new instructions, listed in Table 1, to compared against the key color (green), and a mask is generated. the Pentium architecture. RPC The mask is inverted and ANDed with These instructions target the data manipula- the x to generate only the foreground pcmpeqb tion used in multimedia and signal processing, image and ANDed with the y image to y generate the key background. Finally, the such as finite impulse response (FIR) filters, two images are combined using a logical OR. discrete cosine transforms (DCT), and the

pandn pand logical operations of image processing. More importantly, however, the MMX architecture introduces new data types that increase the data throughput for these applica- por tions. These data types let many of the new to discern whispering, even with some MMX instructions operate on more than amount of ambient sound. one data item at the same time (i.e., SIMD;

Nonlinear quantization is used in tele- Merged (D) single instruction/multiple data). phone systems to squeeze 12-bit audio Contrast this to typical microprocessor into 8-bit samples. The encoding is usually instructions, which operate on one data item exponential, and two different encoding either outputs them digitally for further process- at a time. The new data types in MMX are tables are used today—µ-law and a-law. ing or converts them to an analog format using packed byte, which packs eight bytes into Another method to reduce or compress a frame buffer. The same has to be done with a 64-bit MMX register, packed word (four audio is masking. It can be done when two audio, although the technique differs slightly. per 64 bit), and packed double word (two tones are close together—say, 1000 and One such board is Traftech’s Zephyr per 64 bit). 1010 Hz—we can’t hear the second tone shown in Photo 1. The Zephyr is a PC/104+ The MMX instructions then operate on if one is significantly louder. based MPEG decoder board that decodes the packed words as if they were indi- To take advantage of this, some compres- MPEG-1 into video and audio streams vidual data words. Figure 2 shows what a sion algorithms used in MPEG filter audio without processor intervention, except for paddb (packed add byte) instruction does. into 32 sub-bands and then analyze them managing the datastream into the board. Let’s look at an example. A common spe- to determine which frequency components However, at MPEG-1, the input data rate cial effect for TV and film is chroma keying. to send on. The parameters for analyzing is only 1.5 MBps (196 kBps), which is the Everybody’s seen the weather reporter the bands and scaling the components are raw data rate from a CD-ROM. standing in front of the weather map on your based on a psychoacoustic model, which Intel, by contrast, chose to include DSP- local TV station. Here’s how they do it. is an experimentally derived part of the like instructions on a general-purpose pro- The weather reporter stands in front of encoder, and adapt themselves to the cessor—the Pentium MMX. Both Adastra a screen with uniform color, usually green audio program. Figure 1 shows the block and Teknor have announced or are shipping or blue, and gives the forecast. The back- diagram of an MPEG audio encoder. Pentium MMX-based PC/104 CPU boards. ground—here, the weather map—is a still With MPEG standards, the encoder can use proprietary components to analyze Listing 1—The inner loop of a chroma-key algorithm is implemented via Pentium MMX video and audio sources and find optimum instructions. It performs one cycle, which encodes eight pixels of video-frame data at a time. compression parameters for a particular pro- gram. The decoder, however, can just be a /* The chroma-keying function * x points to the frame with the chroma background dumb piece of hardware that simply de- * y points to the frame with overlay codes the MPEG datastream. The datastream * g points to the key color, this is constant for the whole frame is then much closer to a stream of instruc- * d points to the destination of the result */ tions to perform than digital data values. chroma(x,y,g,d) register unsigned char *x,*y,*g,*d;{ _asm{ VENDOR OFFERINGS mov edx,g Now that we’ve reviewed the kinds of movq mm0,[edx] /* load green constant */ things we are likely to deal with in a multi- mov edx,x media-based system, mostly decoding or movq mm7,[edx] /* load x, the image with chroma */ encoding video or audio, let’s look at some of mov edx,y the components and tools available. movq mm6,[edx] /* load y, the background */ Whenever we’re dealing with fairly stan- pcmpeqb mm0,mm7 /* compare x with green mask -> mm0 */ dard encoders and decoders, we can use pandn mm7,mm0 /* mask off chroma background */ off-the-shelf hardware components. Recall I pand mm6,mm0 /* mask off foreground in background */ mentioned that the MPEG encoder is fairly por mm6,mm7 /* combine image */ complex and sometimes proprietary, but the mov edx,d decoder is simply a machine that reconstructs movq [edx],mm6}} /* save combined image */ video frames from the MPEG stream and

58 CIRCUIT CELLAR INK JUNE 1998 image filmed with a differ- With the MMX architecture, eight 8-bit pixels As well, a new breed of computational ent camera. can be processed at one time, using four element—reconfigurable hardware—is Now comes the magic. A spe- instructions. Compare this to the approxi- changing the way we solve some of these RPC cial box, usually integrated into the mately 24 regular Pentium instructions, problems with “soft” hardware. Watch for video switch, takes the image of the which you have to use without the MMX developments. RPC.EPC weather person and substitutes the back- extension to process the pixels. ground image whenever it finds the color A solution somewhat between software Ingo Cyliax has been writing for INK for in the image. implementation and fixed hardware uses two years on topics such as embedded In an analog video system, you simply configurable hardware. Virtual Computer systems, FPGA design, and robotics. He is filter the video image for the key color. NTSC Company has a PCI-based FPGA card that a research engineer at Derivation Systems shows up as a pure sine wave that’s phase can be configured dynamically to perform Inc., a San Diego-based formal synthesis shifted from the color-burst signal. hardware-based computation. company, where he works on formal- You can also do this special effect digitally, VCC’s card also sports local fast SRAM, so method design tools for high-assurance but it’s a bit different. In digital video or film, it functions like a array processor or imple- systems and develops embedded-system each pixel has a word indicating the color hue ments encoding or decoding functions. Their products. Before joining DSI, Ingo worked and saturation, either by explicitly encod- development environment enables the for over 12 years as a system and research ing the RGB value or by using a color map. design of hardware objects that are imple- engineer for several universities and as an The word size usually varies between 8 bits for mented on the card interface with library independent consultant. You may reach NTSC video and 24 bits for deep-color routines to C and C++ programs. him at [email protected]. spaces. In any case, a single value in the Algorithms like DCT, which form the inner REFERENCES color space now represents the color key. loop of the MPEG and JPEG compression [1] Intel, Intel MMX Technology Overview, 1997. Let’s do this with MMX instructions. The techniques, can be substantially accelerated [2] J. Heron, D. Trainor, and R. Woods, Image Com- pression Algorithms Using Reconfigurable Logic, foreground image (i.e., the weather reporter) over standard processors. For example, a Queen’s University of Belfast, Northern Ireland, and is image x, and the background is image y. VGA-resolution JPEG decoder implemented Integrated Silicon Systems, Belfast, Northern Ire- land, 1997. The algorithm first constructs a mask by on this card FPGA runs at ~50 fps, compared comparing each pixel value in x to the chroma to ~6.5 fps on a 233-MHz Pentium [2]. RESOURCES K. Jack, Video Demystified, Hightext, San Diego, CA, color (green). When it’s green, the mask has However, the RTOS system designer is 1996. a one bit and nongreen is masked as zero. still left wondering how to tie it all together. K.C. Pohlman, Principles of Digital Audio, Sams, India- napolis, IN, 1989. The pcmpeqb instruction does this for a byte- One solution is Microware’s multimedia J. Watkinson, The Art of Digital Audio, Focal Press, packed word on eight pixels at a time. system architecture, Maui, for its OS9 RTOS. Oxford, UK, 1994. J. Watkinson, The Art of Digital Video, Focal Press, The mask is ANDed with the x and y Maui enables the application developer to Oxford, UK, 1994. images. However for x, an inverse mask program against a common API, which gives SOURCES extracts the foreground. MMX has a spe- abstractions for video and audio devices. Zephyr MPEG decoder PC/104+ Card cial instruction of packed AND NOT You then don’t have to worry about what Traftech, Inc. 6981 Millcreek Dr., Ste. 30 (pandn), which implements an AND with kind of hardware is present in the system. Mississauga, ON the logical NOT of one of the operands. It’s even possible to implement some of the Canada L5N 6B8 (905) 814-1293 Image y is simply ANDed with the mask device as software components without Fax: (905) 814-1292 using the packed AND (pand) instruction. recoding the application program. Figure www.traftech.com We now have two images—a foreground 4 diagrams this system architecture. VNS-686M Pentium MMX CPU Card Adastra Systems Corp. and a background with a hole the shape 3988 Trust Way of the foreground image. The final opera- WRAP UP Hayward, CA 94545 (510) 732-6900 tion is a logical OR to combine the images. Multimedia is an exciting area with a Fax: (510) 732-7655 Figure 3 shows what this looks like, and lot of new development. Processor vendors www.adastra.com Listing 1 shows the heart of the algorithm. are developing architectures to accelerate Viper820 Pentium MMX CPU Card Teknor Microsystems, Inc. multimedia applications, and 616 Cure Boivin hardware vendors are offer- Montreal, QC Applications Application Canada J7G 2A7 ing specific board solutions. (561) 883-6191 MAUI System Fax: (561) 883-6690 www.teknor.com CDB Text Drawing Animation Windowing PCI6200, PCI reconfigurable processing unit Bit-BLT Input Virtual Computer Corp. 6925 Canby Ave., Ste. 103 Graphics Drivers Messaging Reseda, CA 91335 Shared Memory (818) 342-8294 Figure 4—Microware’s Maui ar- Fax: (818) 342-0240 Operating www.vcc.com OS9 Kernel System chitecture lets the developer pro- gram against a consistent API, File Multimedia File Manager Serial Character File Manager regardless of how the devices Managers IRS are implemented. For example, Device 416 Very Useful Sound Driver Graphic Devices Keycode/Pointer Devices Drivers the application program doesn’t care if an MPEG decoder is imple- 417 Moderately Useful Hardware mented in hardware or software. 418 Not Useful

60 CIRCUIT CELLAR INK JUNE 1998 APC

Applied PCs Fred Eady

A New View Part 2: Data Acquisition with Virtual Instruments

Virtual instrumentation is only a good deal if it can handle real-world problems. So, Fred looks beyond the software of last month and puts together a data- collection device. Next month, he’ll show you how to measure this month’s data.

Since I talked to you last, lots of “instrumen- ENEMY IDENTIFICATION embedded engine will be used? Is the tal” events have occurred. Fortunately, these For the soldier, proper identification of operating system 16 or 32 bit? Do we need events weren’t virtual like the National Instru- enemy forces is key to battlefield success. standard peripherals like hard disks or ments VIs I introduced to you last time. For the data-collection science officer, iden- CD-ROM drives? There’s National Instruments hardware in tification of the data to be collected is just Rather than go through an embedded Circuit Cellar’s Florida room! That means as important. So, before we throw hard- lifetime wondering, let’s start at the begin- hands-on-plug-it-in-load-drivers-and-run time. ware at a problem, we need to know what ning and work out the answers as we go. Last time, I discussed the software side we’re throwing at. of the National Instruments LabVIEW. We Do we want to collect analog or digital SELECTING EMBEDDED ENGINE saw that, by combining prewritten and data? What types of sensors will we need? The first logical thing to do is to select specialty instrumentation components, just Do the sensors need conditioning? What the embedded platform we’ll base the rest about any data-collection device of the data-collection hardware on. within reason could be realized. We could start with any data collec- Conventional As you’re know, we live in a physi- Programming LabVIEW LabVIEW/CVI tion components, but remember this Environment (PC, Macintosh, or (PC, Macintosh, or cal world. It’s difficult to collect “vir- (PC, Macintosh, or Sun SPARCstation) Sun SPARCstation) is an Embedded PC column. tual” data to correlate with real- Sun SPARCstation) The data-acquisition card I pulled world events. Hence, “real” hardware from the goodie box is AT compat- must compliment the virtual mecha- ible and ISA based. That means that NI-DAQ nisms of the LabVIEW instrumenta- Driver Software the embedded engine we select tion software to collect real usable must be AT compatible and accept data. So, let’s go into the goodie ISA expansion cards. Another plus Personal DAQ or box I got from National Instruments Computer or would be to have the capability of SCXI Hardware and put together the beginnings of Workstation using PC Card technology. a real-world data-collection machine Figure 1—This is a little busy but it shows how all of the A deeper look into the National embedded style. products are interwoven. Instruments goodie box offers some

JUNE 1998 EMBEDDEDPC 61 PCMCIA data-collec- plenty of memory for tion and control possibili- Bill’s memory-hungry ties. I’m getting old and not software. APC seeing as well as I used to, but Problem is, how do I I think I see some PC Cards in the get an ISA data-acquisi- box, too. tion card linked with this The very first and preferred platform puppy? Wait a minute— that came to mind was the new EXPLR2. It the VIPer806 hardware has ISA slots and a PC Card socket resides on an ISA-com- onboard. It can do IDE, PS/2 mice, and patible card. floppy drive, too. Perfect! I dug out my VIPer man- Not. The EXPLR2 is ’386 based. Although uals, and sure enough, LabVIEW can run in a 16-bit environment, “The VIPer806 is a multi- I don’t feel like fooling with Windows 3.11 purpose computer. It can right now. If you want to, that’s OK. I’ll watch. be used as a single-board As you probably ascertained, there’s a computer in conjunction bunch of embedded components in the with a passive back- Circuit Cellar Florida room, so I decided to plane.” Enough said. think about this a little more and come up I pulled the Tempu- Photo 1—This is more like it. Notice that three DMA channels are used by the DAQ card. with a more suitable platform. stech out of its native back- After some thought and file-cabinet plane and inserted the Teknor. A few pulls life better? You’ll recall I have multiple searching, I came across the Tempustech and pushes and a whap to the power switch machines all over the Circuit Cellar Florida VMAX SBC 301. This embedded system is kick-started the Teknor BIOS, and up came room and I hate to run multiple keyboards, based on a 66-MHz ’486 and is capable an intelligent message on the display. mice, and monitors all over the place. of playing with other components via a Yes! No smoke is good. Things are begin- This particular application is another passive ISA backplane. I can add an IDE ning to shape up. I’m sure that Tempustech good example of how useful the Vetra drive and CD-ROM as well as boost the backplane never thought it would see MegaSwitch is. Within a few minutes, I had memory up to Windows 95 levels. This is it! VIPer gold contacts. the VIPer and all its peripherals marching Hmmm . Seems I need to add a video After a few more tugs and grunts, a to 60 Hz. All I had to do was hook the card to make the system complete. No floppy, a 2+ GB IDE drive, and a CD-ROM VIPer up to an unused set of MegaSwitch problem. I look for and find a spare video drive join the virtual-instrument party. Don’t cables and punch a button to select it. card. Well, this ain’t it. The video card is you love this embedded stuff? The VIPer is now embedded platform 6 PCI not ISA. If you’ve read my previous columns, of 8. Hmmm. Sounds like a Borg thing to The Tempustech backplane has no pro- you know that in the middle of articles I me. Anyway, back in the truck. vision for PCI. Being originally from Ten- sometimes park the truck and take a walk. nessee, the Grandpa Jones “Hee Haw” Well, let’s park the truck here and traipse FUELING THE EMBEDDED ENGINE tune came to my lips just a little bit skewed, (that’s Tennessee for “walk”) into the bushes. We’re at the point where we are ready ”I searched the world over and thought I A while back, I mentioned some of the to load one of Bill’s operating systems, found true love, but you were PCI and stuff I use to make embedded development Windows 95. We could go back in time psssst you were gone.” and use Windows 3.11, but I Great idea, wrong interface. don’t think so. When they put This is getting down to where 3.11 on CD-ROM, I’ll load it. I’m gonna have to really do As it turns out, loading any some thinking if I don’t find the version of Windows, CD-ROM right stuff pretty soon. or not, would have been easier A little more digging brought than figuring out why I couldn’t out things I thought I had lost or get the IDE drive to come ready. loaned out and a Teknor VIPer- Seems the drive I selected didn’t 806. I’ve ridden this baby many like 32-bit or block transfer times and put it up wet. There mode with the VIPer. was a hint of moisture in the I really don’t have time to antistatic bag even. play with that now. Lucky for you, As far as the VIPer is con- you’re reading this in “relative” cerned, everything is there with time, but it took a day or so for the exception of the ability to me to reach that conclusion incorporate an ISA daughter card. and get a good load of 95.

There’s onboard video, onboard Photo 2—The “wordy” descriptions are nice. The temperature measure- A load of LabVIEW with the IDE and floppy capability, and ment box is checked for use with the PIC14000. appropriate NI-DAQ equiva-

62 CIRCUIT CELLAR INK JUNE 1998 APC

lent drivers is the next logical step. While bration, messaging, and acquiring data like writing to registers on it’s loading, let’s talk about what NI-DAQ to extended memory. Whew! the DAQ hardware card. and LabVIEW have in common. NI-DAQ also includes high-level DAQ (Do you get the idea that NI-DAQ software ships with every piece I/O functions as well as low-level DAQ I/O DAQ is short for Data AcQuisition, of National Instruments DAQ hardware. functions to aid the user in producing a and maybe NI is short for National NI-DAQ includes an extensive library of workable data-acquisition solution and at Instruments? Hmmm .) callable functions for the VI programmer. the same time maintain high performance Summing it up, NI-DAQ software is the These functions include routines for analog and maximum flexibility. mediator between the embedded com- input (A/D conversion), analog output (D/A High-level functions include acquiring puter and the DAQ hardware. All the conversion), buffered data acquisition, wave- particular numbers of data points or stream- housekeeping, like programming inter- form generation (timed D/A conversion), ing data to disk. Low-level functions are much rupts and DMA controllers, is done by the digital I/O, counter/timer operations, cali- like the ones us bit-bangers are accustomed to, NI-DAQ software.

Photo 3—Is this flexible or what? a—We can choose any Centigrade or Fahrenheit tempera- ture range to match our particular application. b—Not only can we se- lect a temperature range, but we can tailor the measurement pa- rameters to match our sensor output. c—Pretty straightforward. Every channel on every DAQ card in the system is easily identified.

JUNE 1998 EMBEDDEDPC 63 If all that isn’t Bus-related con- enough, NI-DAQ also figuration consists maintains a consistent soft- of setting the base APC ware view among all of its ver- I/O address, DMA sions that lets your data-acquisi- channels, and in- tion applications move between many terrupt channels. platforms with minimal coding effort. Data acquisition- Figure 1 is a picture worth almost as many related configura- words as I have used to describe it. tion has to do with the analog input INSTALLING DAQ AND LABVIEW polarity and range I promise, we’re going to get back to it and other related and install LabVIEW on the VIPer, but entities. before we continue, let’s talk about the Installing the data-acquisition hardware I pulled out of DAQ board was Photo 4—As you can see, repeating the definition process for every the goodie box. just a push into the channel would automatically make another entry into the channel table. We will be installing and configuring Tempustech back- the AT-MIO-16E-1. How do I know that? plane. LabVIEW’s install was more involved. Architecture, a single interface library for It’s silkscreened on the card. How did I Although the software-installation pro- controlling GPIB-based instruments. Yep, Lab- decide which card to use? Well, that’s cess was similar to other installs, I was glad I VIEW not only is the instrument, it can what was in the box! Actually, I did ask for read the doc before jumping in. There are a control the instrument, too. The install went this particular card because I thought it few options that the install program asks you smoothly, but I noticed it took longer with would be of interest to most of you. to choose during the install process. It the 100-MHz VIPer than my 233-MHz yin- The AT E-series boards are software helps to know some of the acronyms like yang desktop. configurable as well as plug-and-play VISA and GPIB. Now that Bill’s OS and LabVIEW coex- capable. To complete our installation, we GPIB is probably obvious to most of ist on the spinning disk, it’s time to do that must perform two types of configuration: you, but VISA isn’t a credit card. VISA in configuration thing. I’ve always hated to bus related and data-acquisition related. this case is Virtual Instrument Software configure things. Especially something that looks as complicated as this DAQ board. But, someone at National Instruments must have taken my “It doesn’t have to be complicated to be embedded” motto to heart. From the LabVIEW perspective, DAQ configuration isn’t complicated, either. (It’s great to know that somebody at National is reading my stuff.) Configuration is accomplished by using NI-DAQ configuration utility, Niconfig. I had a few problems getting the VIPer and Win95 to recognize the DAQ card. So, I went back and read the install instructions again. And again. And again. Finally, out of desperation, I deleted the DAQ card from the Win95 hardware config and performed a refresh. I noticed before that the DAQ card was addressed in the FF80–FF9F area. I thought it odd, but that’s what Bill’s software saw, so I let it go. After I deleted the card and refreshed the Win95 hardware config, the new address was 0120–013F, and the IRQ had changed from 11 to 15 with three DMA channels tagging along. Also, I noticed that the second time around the National Instruments logo appeared in the Win95 device manager window, and the serial number of the DAQ card was picked up as well. Wow!

64 CIRCUIT CELLAR INK JUNE 1998 Photo 5—Here are all the goodies that I found in my box. The large DAC board also comes in a PC Card version.

With all that new stuff showing up, this ment data-acquisition and instrument con- card had better pass the hardware test. It trol the embedded way. APC.EPC did. I chalked the mishaps up to Bill’s Fred Eady has over 20 years’ experience software not National’s. Photo 1 is the fruit as a systems engineer. He has worked of my labor. with computers and communication sys- That about does it for the bus-related tems large and small, simple and com- config. Keeping with the uncomplicated plex. His forte is embedded-systems de- idea, the DAQ Channel Wizard guides us sign and communications. Fred may be through the data-acquisition configuration. reached at [email protected]. We can assign a real name to our inputs. Photos 2 through 4 show how easy it is to SOURCES LabVIEW configure an analog input channel. This National Instruments Corp. process is repeated for the number of chan- 6504 Bridge Point Pkwy. Austin, TX 78730 nels we need for our application. Once the (512) 794-0100 DAQ card is configured, there’s even Fax: (512) 794-8411 www.natinst.com some ready-to-roll apps included. VMAX SBC 301 Tempustech SUMMING JUNCTION 295 Airport Rd. Naples, FL 34104 We now have a combination of hard- (941) 643-2424 ware and software components that make Fax: (941) 643-4981 www.tempustech.com up the basis of a powerful data-acquisition VIPer806 and control tool. Only one last piece. Teknor Microsystems, Inc. There’s a funny looking 68-pin connector 616 Cure Boivin Boisbriand, PQ on the back of the DAQ card. I can’t stuff Canada J7G 2A7 wires into it to make my interface connec- (514) 437-5682 Fax: (514) 437-8053 tions. Back into the goodie box. www.teknor.com Aha! An interface cable. And look—a MegaSwitch screw-down interface block for each wire! Vetra Systems Corp. 275-J Marcus Blvd. Check it out in Photo 5. The hardware is Hauppauge, NY 11787 complete, and just in time. I’m out of paper. (516) 434-3185 Fax: (516) 434-3516 Next month, I’ll put the ready-to-run eemoline@comvetrasyst virtual instruments (National Instruments Virtual O-scope and DMM) to work look- IRS ing at input and output associated with the 419 Very Useful DAQ platform we just built. Remember, it 420 Moderately Useful doesn’t have to be complicated to imple- 421 Not Useful fader in the music industry—must include a logarithmic curve or taper. FEATURE For music, it’s often necessary to make gradual changes in sound ampli- ARTICLE tude. Unless these changes are made in very small jumps, we perceive them as a form of distortion commonly referred to as “zipper noise” because Brian Millier it sounds like a zipper being moved. In the past, these characteristics made it difficult to control volume digitally, and many of the schemes were quite complicated. High-resolution Digital Attenuators multiplying DACs were expensive, and the presence of many digital signals going to the device tended to produce some noise in the audio signal. You could use a DAC to produce a DC voltage which then controlled a voltage-controlled amplifier (VCA). Unfortunately, VCAs are tricky cir- cuits to design, and they have their own dynamic range and linearity problems. This method is complex he mechanical and expensive, but it performs well. t potentiometer has Recently, Dallas Semiconductor Given the CD quality been around for as long devoted some of their engineering as many other electronic prowess to attack this problem. As a we’ve come to components. Until recently, however, result, they now offer a full line of it hasn’t been widely available in a digital attenuators that address these expect, volume digital format. problems. Let’s take a look at how they For set-and-forget apps (e.g., calibra- work and see how they can be used for a control needs to be tion via DC voltages), you could use a common music-studio application— DAC, assuming its voltage range an automated mixing device. handled digitally. matched the application. A four-quad- rant multiplying DAC lets you handle THE DS1800 FAMILY Brian shows us how bipolar signals over a wide range. For Members of the DS1800 family vary a number of years, Xicor produced a greatly in features, but they share a using Dallas digital line of EEPOTS, which were low-resolu- basic design. Figure 1 represents the tion (100 step) DACs coupled with block diagram of one member of the attenuators, TI op- EEPROM memory and a serial interface. family—the two-channel DS1800. Probably one of the most common A resistor ladder connects to a multi- amps and virtual uses of potentiometers is for volume plexer, which acts like the wiper in a control on the numerous consumer mechanical potentiometer. The resistors grounds, and a audio items available today. Human are equal values in the linear models, hearing covers an extremely wide range while the logarithmic models have musical digital of amplitudes. How much of this scaled resistors to provide a pot with a dynamic range is actually needed varies, logarithmic taper. interface. Tune in. but for listening to music, CD quality Figure 2 shows the attenuation-ver- is now the norm. A 16-bit digital sus-position relationship of the DS1800, storage format gives you a dynamic which is a log device. Notably, the wide range of about 94 dB. dynamic range of +20-dB gain goes all Volume controls for such applica- the way down to 80 dB of attenuation, tions must possess high resolution and which suits musical applications well. low inherent noise so that the high- A control logic unit handles the quality signal is not degraded. To interface of the parallel multiplexer match the human ear’s response char- inputs with the various digital control acteristics, a volume control—called a schemes of the DS1800 family. For all

68 Issue 95 June 1998 Circuit Cellar INK® level of a specific From this, you can see the parameter IN1 Potentiometer 0 OUT0 IN1 Potentiometer 1 OUT0 sound source, such as range is limited to 128 discrete values.

POS-0 POS-128 POS-0 POS-128 a vocal or guitar track Dallas probably had MIDI applications

129-to-1 Multiplexer 129-to-1 Multiplexer after it has been in mind when it designed the DS1800 recorded to magnetic device with 128-position potentiometers. W0 Wiper 0 (8-Bit Register) Wiper 1 (8-Bit Register) W1 tape. Since this is The midi-fader listens to the serial B0 B7 B8 B15 often done to several MIDI datastream, responds only to the *RST Control COUT tape tracks simulta- correct commands, and converts this CLK Logic MODE D Unit neously and involves information into a form that can be sent 3-Wire Serial gradual changes or to the DS1800’s three-wire serial inter- Interface “fades,” it’s useful if face. An LCD with a bar-graph read- P0G P1G a computer can con- out of volume level tracks each of the P0A P1A Push-button Control Inputs trol such actions. eight channels implemented. Generally, the tape Figure 1—This block diagram of the two-channel DS1800 shows its push-button recorder is connected THE ANALOG SIGNAL PATH as well as its three-wire serial interfaces. to a computer running Like all members of the family, the a sequencer program DS1800 I chose is a low-power device family members, the number of fast that’s generating some of the music designed to work at the low voltages rise-time digital signals entering the being recorded. The recorder and com- present in battery-operated equipment. device is minimal, and feedthrough of puter are synchronized to each other. It operates from 2.7 to 5.5 V, interfac- the digital signals into the analog Therefore, it’s possible for the com- ing nicely with the 5-V logic supply signal path is virtually nonexistent. puter to send out commands to the used by common microcontrollers. This is critical for audio applications. midi-fader to adjust the volume levels, The downside is that the limit on the The family consists of a full line of in much the same way as it sends out analog signal levels these devices can ± digital attenuators with up to six atten- commands to the various electronic handle is 2.5 Vpeak, or about 1.7 VRMS. uators per package and resolutions of instruments to play musical notes at But, this limit is no problem in nonpro- up to 256 steps. Different devices con- the proper time. This stream of digital fessional music-studio equipment be- tain combinations of push-button, two- commands is sent via MIDI (Musical cause the –10-dBv levels used for normal and three-wire serial, and three-wire Instrument Digital Interface). line-level signals is significantly less. parallel interfaces. MIDI is a serial, optically isolated, As you see in the lower section of The push-button inputs are de- current-loop interface, with a fixed data Figure 3, the only other active compo- bounced and pulled up internally to rate of 32,500 bps and no handshaking nent needed in the analog signal path ease circuit design. Although most of signals. The MIDI protocol calls for of these digital attenuators is a single the units are volatile, a few models eight-bit data transfers, with the most op-amp. Because the digital attenuators are nonvolatile, like the Xicor devices. significant bit equal to 1 for commands operate on a single +5-V supply, the I mentioned the problem of zipper and 0 for data and parameters. op-amp should also operate on 5 V. noise earlier, and you might wonder how a device with a maximum of 256 30 discrete steps doesn’t suffer from this Gain effect in a big way. Here’s where the 20 magic of the device comes into play. . 0.25-dB Resolution Dallas incorporated a novel zero- 10 crossing detection circuit into the 0.50-dB Resolution 0 device. Essentially, it defers any pend- 0 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 ing changes to the pot’s setting until 100 104 108 112 116 120 124 –10 the analog signal entering the pot Gain crosses the zero-voltage threshold. –20 With no signal present, you can alter the pot’s setting without zipper noise. –30

In my tests, I could barely hear any 2.00-dB Resolution artifacts and they only occurred in –40 quick large volume changes. So, I –50 judged the device to be entirely suitable 4.00-dB Resolution for critical musical purposes. –60

PUTTING IT TO WORK –70 A midi-fader is a device used in a Figure 2—The resistor chain in the DS1800 is broken up into five segments, with values chosen to effectively recording studio to adjust the volume produce a logarithmic taper.

Circuit Cellar INK® Issue 95 June 1998 69 controls both channels jointly and I Figure 3—You’ll be happy wanted each channel to be independent, to discover how easy it is to I decided not to use this feature. add more channels to this four-channel midi-fader. While not shown in Figure 3, in my personal unit, the analog signal section is expanded to support eight channels by replicating the circuitry involving the two DS1800s and the TLC2254. The firmware sends out data for all eight channels, and the cascade capa- bility of the DS1800 makes it easy to add more devices.

THE DIGITAL CIRCUITRY The DS1800 has a three-wire serial protocol that interfaces to the SPI port present in the Motorola 68HC705C8, as well as similar ports available on other common microcontrollers. Un- like the *Enable line found on most serial peripherals, the DS1800 needs an active-high signal on its *RST pin to initiate data transfer. Since Dallas Semiconductor antici- pated that multiple DS1800 devices would be needed in multichannel audio applications, it provided a simple way of controlling cascade-connected devices Of the numerous op-amps I tried, going through the midi-fader are phase via the cascade-out pin, COUT. the Texas Instruments TLC2254 quad inverted. This setup has some ramifi- For all cascaded devices, the D op-amp performed the best. Other cations in certain audio applications. input is connected to the COUT pin devices suffered from various short- Two of the DS1800’s features were of the previous device in the chain. comings like crossover distortion, low left unused. The push-button inputs All DS1800 CLK pins are connected in output levels, or low-level oscillations on the DS1800 enable manual volume parallel. To load the cascade-connected (squealing) at certain volume settings. control, which I didn’t need. DS1800s, first raise the *RST line Note in Figure 3 that the plus input to Also, the device incorporates a high, send 16 clock and data bits per the op-amp must connect to a virtual mute feature. Its 128 pot positions are connected device, and then lower *RST. ground equal to half of VCC. I used a encoded into the seven least significant The data effectively ripples its way Texas Instruments TLE2425CLP virtual bits of its command byte, and setting through all of the connected devices. ground generator because it provides a the most significant bit equal to 1 The data format required by the DS1800 stiff ground with no additional circuitry. puts the device into mute mode. is shown in Figure 4. I chose an SPI data All signal inputs and outputs are The advantage of this mode over just transfer rate of 16 µs per bit, so four referenced to this pseudo-ground. Since sending out the lowest-volume setting devices (implementing eight signal the optoisolated MIDI input is the only command is that it lets the user turn channels) can be quickly updated in other connection to external devices, a channel on and off without affecting about 1 ms. floating the signal ground is fine. (or memorizing) the volume level in The only fly in the ointment in this The few additional passive compo- the nonmuted position. otherwise ideal data-transfer arrange- nents needed for the analog signal path Unfortunately, my sequencer soft- ment arises from the fact that the are shown in Figure 3. At each channel ware sends out the same command DS1800 expects its serial data to be input is a voltage divider consisting of whenever the mute button is clicked, sent least significant bit first, whereas RA and RB. You should choose this to even though that button has a toggle- Motorola SPI ports send data out most limit the amplitude of the output signals type action and indicator. This can significant bit first. Both devices are to the ± 2.5-V range mentioned earlier, result in situations where the midi- stubbornly nonprogrammable in this given your signal’s input levels and the fader thinks muting is on and the respect, so I need a software routine +20-dB gain present when the DS1800 sequencer thinks it’s off. that does a bit reversal. is fully cranked up. I was unable to figure out a good In assembly language, this involves Note that the op-amp is configured solution to this problem. Since the mute only eight Logical Shift Right and eight in the inverting mode, so any signals push-button input on the DS1800 Rotate Left instructions, but try it in

70 Issue 95 June 1998 Circuit Cellar INK® a high-level language and see how ing the user-definable characters avail- doesn’t include any provisions for hand- involved it is. It isn’t obvious to me able on most common LCD modules, shaking. Therefore, the microcontroller why Dallas decided to do it this way, a bar-graph readout can be displayed must always be ready to accept MIDI but the rest of the design is so good for each channel. This graph resembles data. that I can live with it. the digital VU meters found on modern The firmware uses an interrupt- The SCI port on the ’C8 is program- audio equipment. driven SCI input routine which accepts med to the 32,500-bps MIDI rate. The Most common LCD modules use the the MIDI data byte, interprets it, and optical isolation required on the MIDI Hitachi HD44780 LCD controller IC or implements it in less than one charac- receive line is provided by a high-speed its equivalent, which allows for either ter time (300 µs). 6N138 optocoupler. This device works four- or eight-bit operation. I wrote a To complicate matters, the MIDI well, as does the PC900 device origi- set of four-bit routines that minimize protocol defines a data-compression nally specified in the MIDI standard. I/O pin usage by using timing loops feature called “running status.” To be However, many other common opto- (rather than polling the LCD’s status of any use for music, the MIDI data- couplers are not fast enough, so be register), which I’ve used with small stream must be processed with little careful if you try using something else. microcontrollers sporting few I/O pins. delay, so elaborate compression algo- The MIDI standard defines 16 unique While the ’C8 has enough unused rithms can’t be used. channels (1–16) that allow for address- I/O port pins to work in a full eight-bit However, music involves a lot of ing up to 16 MIDI devices daisy-chained polled mode, I stuck with these routines repetitive actions, so whenever any together. All MIDI commands have the because they don’t hang the program command is the same as the one preced- MIDI channel number encoded into if the LCD is not installed, making its ing it, the command itself is not sent— their four least significant bits. All use optional. This allows for a lower just its parameters. While quite crude, MIDI devices incorporate some way cost version of the project. this technique provides some data to set the channel to which they will compression and isn’t too difficult to respond. In this design, it’s done by THE FIRMWARE decode by the receiving MIDI device. reading a four-section DIP switch, S1, While the firmware is not particu- The DS1800 digital attenuators are using PB0–PB3, at powerup. larly involved, there are some important not nonvolatile, and they power up in For the front-panel display, I used a considerations that must be addressed. the position of maximum attenuation. 40-character × 2-line LCD. By employ- The MIDI serial data transfer protocol Since I don’t want to burden the se- quencer software with the called Cakewalk, which task of turning up the volume includes a Fader View win- at startup, the midi-fader dow (see Photo 1). After Wiper-1 Wiper-0 firmware looks after setting Position Value Position Value telling the program what all channels to unity gain channel my fader is set to when it comes out of reset. Mute Most Signficant Bit Least Signficant Bit Mute Most Signficant Bit Least Signficant Bit and that it emulates an 15 14 1312 11 10 9 8 76543210 Along with the usual MOTU mixing device, I’m port-initialization tasks, the off to the races. Figure 4—The DS1800 uses this 16-bit command word structure. firmware also reads the MIDI channel DIP switch, assigns the used by the midi-fader is a control- FADE OUT midi-fader to that channel, and puts change command, which has a hex I hope that you’ve gotten a good feel up a message on the LCD indicating value of Bx, where x is the channel for Dallas’s digital attenuator family. this channel assignment. number of the device the command is I didn’t delve into a lot of details that Possibly the most difficult part of being sent to. musicians building a DIY midi-fader the firmware to code was that involved Following this command byte is the might want explained, but I hope this in the eight-channel VU meter display controller number. Since many types of article piques your curiosity. on the LCD. Eight custom characters controllers are used in musical instru- For more information, check Dallas’s were defined and loaded into the LCD ments, many controller numbers are Web site. It offers excellent datasheets controller. These were basically eight preassigned to specific controllers. on all of Dallas digital attenuators, bars of differing heights. To make the midi-fader compatible free for the downloading. I A two-line display gives a resolution with other similar devices out there, I of 16 bar heights. The 128-step volume chose to use controller numbers 16– Brian Millier has worked as an instru- range provided in the MIDI specifica- 23 for the eight channels in the midi- mentation engineer for the last 15 tions is mapped into these 16 heights fader. The last byte sent is the actual years in the chemistry department of using shift commands. volume-level byte. Dalhousie University, Halifax, NS, Then, the proper combination of two Like all data and parameter bytes, the Canada. He also operates Computer custom characters is sent to the LCD last byte has a most significant bit equal Interface Consultants. You may reach to make up the bar. I used several data to 0, so its range is limited to 0–127. him at [email protected]. pointers to place the bars in the proper Three MIDI bytes are sent for each vol- place on the LCD for each of the eight ume change. When several volume SOFTWARE channels. Since volume-change com- change commands appear in a row, the The source and object code for the mands can come in quickly, this routine running-status compression reduces 68HC705C8 microcontroller are had to be tightly coded. this to two bytes per volume change. available from the Circuit Cellar I won’t get into the whole MIDI Controlling the midi-fader from Web site as well as via . tion a couple things. The MIDI command package you’re using. I use a package SOURCES DS1800 Dallas Semiconductor 4401 S. Beltwood Pkwy. Dallas, TX 75244-3292 (972) 371-4448 Fax: (972) 371-3715 www.dalsemi.com TLC2254, TLE2425CLP Texas Instruments, Inc. 34 Forest St., MS 14-01 Attleboro, MA 02703 (508) 699-5269 Fax: (508) 699-5200 www.ti.com I R S 422 Very Useful Photo 1—Popular sequencer software (e.g., Cakewalk) includes a Fader View window designed to operate auto- 423 Moderately Useful mated faders like my midi-fader. 424 Not Useful

72 Issue 95 June 1998 Circuit Cellar INK® DEPARTMENTS FreeDOS and MICRO 74 MicroSeries the Embedded SERIES

Pat Villani 80 Silicon Update Developer

Kernel Design

OS-C started in d 1988 as an experi- ment in writing de- vice drivers using C for MS-DOS. As part of the experiment, I Fed up with wrote block and character device

Part 11 drivers using a C data structure that of forking over matched the MS-DOS request packet. 22 I drew on previous experiences in big bucks applying C to embedded and real-time systems. And, I developed new C pro- for your OS? Pat gramming techniques to map assem- bly-language calls to C and vice versa. offers an alternative I soon recognized I could write an operating system by using the same that’s 99.9% MS-DOS techniques. I decided the design should take advantage of C-language features. compatible. And, it Developing the OS would require fewer resources than a traditional can be used for assembly-language design. In fact, if I developed it myself, I could take ad- embedded develop- vantage of commercially available tools like Borland C and Turbo Assembler. I ment as long as you could also use MS-DOS debugging tools to prototype and debug program mod- follow GNU’s public ules under MS-DOS and later integrate them with special start-up code. license rules. It looked like an excellent project. Using C to build an OS wasn’t new— Unix proved this concept for large multiuser OSs. But, I could find no documented instances for a smaller PC OS. So, I proceeded to build a minimal OS using the device drivers I had written earlier. In 1994, when Microsoft announced its intent to drop MS-DOS in favor of Windows 95 (then known as Chicago),

74 Issue 95 June 1998 Circuit Cellar INK® Jim Hall started the FreeDOS project. tains functions that encompass all DOS-Compatible System Calls His plan was to develop an MS-DOS rules for handling file I/O that deals replacement so that when Microsoft DOS API Entry Points with PSP, handles, or character and stopped producing MS-DOS, FreeDOS dosfns block I/O functionality. could come to the rescue. fs task memmgr You can now find FreeDOS at vari- chario blockio FILE SYSTEM Task and Process Support Code ous FTP and Web sites. There’s also a The DOS-C design allows for a file execrh book describing the kernel in greater manager that is independent from the detail for developers needing to modify Device Drivers design of the rest of the OS. Whenever the kernel [1]. Machine-Level Support Code an application requests an operation FreeDOS may be used as a general- on a file resident on a block device, purpose DOS replacement that executes Figure 1—The FreeDOS/DOS-C kernel architecture is this fs module performs the operation standard MS-DOS applications. Addi- layered, allowing interface behavior to be localized in by working with an internal table tionally, the source for the entire OS the dosfns layer for API and the execrh layer for device called the fnode (file node) table. drivers. is available under the terms of the GNU The fnode table is the foundation public license (see sidebar “The Em- either efficiency or necessity. These for the design of the FAT file-system bedded Systems Developer and GPL”) functions typically perform direct manager. The fnode data structure on many of these same sites. machine control, such as stack manipu- controls all internal file operations What this means for embedded- lation and flipping interrupt bits. You and virtualizes the file. system developers is that there’s a can find this code in a number of When fs performs an operation like free operating system available. All assembly files along with C-to-assem- create or open, it allocates an entry from that’s necessary is that the GPL terms bly interface functions. the fnode table and fills the fnode are followed. fields. The call returns a number that Although these rules seem stringent, DOS-C API is the index into the fnode table. the user needs only to provide a dis- A DOS API entry-point handler From here on out, any function that kette with the source to the kernel on intercepts any system call to DOS-C performs an operation on the file re- request. The license does not cover the and translates it into a C call. I put this ceives this number. The fnode table application, so the embedded developer’s as close to the entry point as possible entry that corresponds to this index code can remain proprietary and yet in order to use C as early as possible. controls all file parameters. take advantage of a royalty-free environ- The C call then does some context If you’re familiar with DOS internals ment, thus maximizing profit. switching and calls the appropriate from the undocumented internals books internal service function. It’s up to [2], you know the need to map internal ARCHITECTURE the service routine to dispatch the fnode to the SFT (System File Table) The DOS-C architecture is layered, system call through the kernel to the structure used by DOS. We handle this similar to what you’ll find in other OSs. appropriate handler. The dispatcher through the dosfns layer function. The only difference between DOS-C and directs a system call into the kernel. The module dosfns maps the fnode other monolithic OSs is that DOS-C A large number of calls are directed number to an SFT handle, which is part has a decoupling between the upper into the dosfns (DOS functions) layer. of its “DOS personality” responsibility. and lower layers as shown in Figure 1. This layer works with the lower layers At the fs level, it does its work in an To guarantee that DOS-C is MS-DOS to add the DOS appearance to the OS-neutral mode to localize unique compatible, there are two interface system calls. features to the personality module. layers where full compliance is neces- It does this by combining calls into sary. The first interface layer—the DOS the various managers in the next lower MEMORY MANAGEMENT API—is the set of entry points you layers with code to add features to the Memory management in DOS-C expect from a DOS-compatible oper- manager calls that are unique to a DOS closely emulates MS-DOS. Because ating system. These include the tradi- interface. For example, this layer con- DOS-C is a real-mode operating system, tional INT 20h, 21h, 22h, 23h, 24h, 27h, 28h and 2Fh. F000:FFFF F000:FFFF F000:FFFF F000:FFFF The other interface layer—the device-driver interface—is also well IPL.SYS 1000:0000 documented and supported by many COMMAND.COM 0000:7E00 hardware and software vendors. This BOOT KERNEL.EXE KERNEL.EXE 0000:7C00 0000:0C00 0000:0C00 layer enables DOS-C to be compatible Scratch Scratch 0000:0400 0000:0400 0000:0400 0000:0400 with MS-DOS to assure proper support BIOS RAM BIOS RAM BIOS RAM BIOS RAM of loadable device drivers. Stage 1 Stage 2 Stage 3 Stage 4 The kernel is written in C wherever Figure 2—There are four stages in booting FreeDOS and DOS-C. The first is execution of the boot program from possible. However, certain functions the boot sector. The second is the disposable intermediate program loader, IPL.SYS. The third is the kernel itself, are written in assembly language for which includes device drivers. The final stage is bringing up the user interface—typically, COMMAND.COM.

Circuit Cellar INK® Issue 95 June 1998 75 the DOS-C memory manager is much Many applications use this informa- Both executable file types start simpler than what you find in other tion, and DOS-C provides this same from a single load entry. It is up to protected-mode ’x86 OSs. information for sake of compatibility. DOS-C to identify the file type. DOS-C manages memory via a Unlike fs, where MS-DOS personality It does this by examining the first memory-block linked list that uses the splits between it and dosfns, memmgr two bytes of the file. If it is an MZ, then same arena header as the one MS-DOS contains all DOS personality. it is an .EXE file and task invokes uses. The arena header in DOS-C is the .EXE loader. Otherwise, task known as the MCB (memory control TASK MANAGEMENT assumes it to be a .COM binary image block). As with MS-DOS, this data Because the DOS-C design emulates and invokes the .COM loader. structure is in front of each allocated MS-DOS, it should be of little surprise Both loaders initially allocate mem- and free memory block. DOS-C uses that the operating system is not multi- ory from memmgr to place the environ- the same M and Z signatures to iden- tasking. As a result, the task manager, ment strings in. The differences begin tify the block type. task, manages a single user task. when the actual file loading occurs. Also, the segment value of the PSP Its primary function is to act as a The .COM loader merely allocates of the program it belongs to, or a 0008h task loader, unlike other operating memory and begins loading the file if it belongs to DOS-C, identifies the systems where task loading is inci- into memory. The .EXE loader, on the owner of the block in the same way. dental to managing the task. Also, other hand, computes the size re- DOS-C uses all other entries in an there are only two relatively simple quired, allocates memory, and then identical manner. executable file types, .COM and .EXE. loads the image.

The Embedded System Programmer and GPL Mention the GNU public license (GPL) to embedded GPL makes certain a developer’s work is protected developers, and reactions range from disapproval to even if it involves modifications to the free code. In hiding under desks. Developers mumble about having to fact, the license goes out of its way to say that changes give away source code. But, that’s not necessarily the case. you make do not necessarily fall under the terms of Written by the Free Software Foundation (www.fsf. the license if they “can be reasonably considered org), GPL lets developers retain ownership of source independent and separate works in themselves.” Clearly, code while placing it and resulting binaries onto publicly this is important to the embedded developer because accessible sites. Ownership comes through traditional it lets you, for example, distribute a compiler under copyright protection, and the license outlines acceptable GPL with your special package. methods of distribution that protect you from someone With FreeDOS, your application doesn’t fall under stealing your code by using it and pretending it’s theirs. GPL unless you make it part of one of the FreeDOS Of course, you should consult your attorney to deter- utilities or kernel. You can distribute your application mine the impact of the license on your project. But, you on a FreeDOS bootable diskette and not release source should do that with any third-party products you use code. GPL emphasizes that “mere aggregation,” such regardless of the source. Any license should be seriously as placing your utility on some form of distribution, reviewed. GPL is just another license. However, some exempts your utility from using GPL. So, if you supply terms within the license scare potential users. an installable device driver with your application, your The license’s preamble states its intent to protect driver code does not necessarily become subject to GPL your rights to receive the product’s source code. It seeks even though it’s part of the OS once it is in memory. to protect your right to give away the source code if you The question: how do you distribute FreeDOS with wish. It also attempts to protect you from the pitfalls of your application and meet the GPL terms? For com- software patents and warranties. In essence, it makes mercial apps, give the customer the source code with certain that software intended to be openly available your application or a written offer valid for three stays that way. It then goes on to outline the terms and years. You are entitled to a “reasonable” charge for conditions of the license and finishes with a warranty. making a copy whether it be for the diskette and ship- In the terms and conditions, the license states that ping or for transferring the source to diskette. The you can make exact, unmodified copies of software latter may be reasonable if your business is not soft- covered by the license, protecting you from any restric- ware distribution and making a copy requires you to tions someone may attempt to place on the software. spend some staff effort creating the disk or tape. It also states that you can modify the code but places At first, this might seem unprofessional and make some minor restrictions on your changes. Simply put, it your product seem amateur, but there are ways around lets you make changes but requires that they be clearly it. When asked by commercial users, I usually advise marked. This request protects you and the original author them to either place an offer in their user manual or from making claims on the changes or the resulting code. supply a separate offer along with their documentation. This is a big boon for free software, and without this Usually, your customers aren’t interested in the OS term, software like FreeDOS and Linux couldn’t exist. source code, but there’s always a curious few.

76 Issue 95 June 1998 Circuit Cellar INK® When task completes loading an the interface is designed for an assem- .EXE image, it seeks the relocation bly-language system, a special assembly- offset and does a segment fixup (nec- language function interfaces all device CRT essary for the ’x86 family). From this drivers. Keyboard point, both loaders proceed with creat- This function, execrh, accepts from ing the PSP, cloning the file table, an I/O handler a packet containing the Console Printer initializing the task’s registers, and function number requested of the Driver Driver Printer Remote executing the task if so requested. device driver. It handles the correct COMMAND.COM Console Serial Port or sequence of calls to the strategy and Driver Host Application MS-DOS Emulator DOS-C AND DEVICE DRIVERS interrupt entry points for the device Software or The device-driver interface layer, driver and returns the packet to the FreeDOS Disk Floppy Kernel Driver Disk which is at the bottom of the DOS-C I/O handler. Special architecture but just above the device The DOS-C device drivers are the Other Hardware, drivers, has two handlers—chario bottom layer of the kernel. Like the Driver LAN, etc. and blockio. remainder of the kernel, C is used in Although each handler uses different these device drivers also. The device Figure 3—When using MS-DOS, the typical develop- methods, both are the primary interface drivers perform the necessary device ment environment is relatively straightforward. Both COMMAND.COM between the device drivers and the interface between the kernel and the and the kernel act as intermediaries between the application and device drivers, virtualizing remainder of the kernel. Both handlers device. DOS-C has the same device the devices while managing the device overhead for the perform all the necessary buffer man- drivers as MS-DOS and they perform application program. agement for both types of I/O, includ- the same functions. ing line-buffer management. CS:IP for the boot block. For MS-DOS, As with Unix, there are two types BOOTING IBM placed the boot location at 0000: of I/O handlers. Their responsibilities DOS-C differs from MS-DOS and 7C00 to provide 30 KB for loading are divided between character stream other DOS clones in its design. Unlike IO.SYS and MSDOS.SYS. I/O (chario) and random access block MS-DOS where there are two files DOS-C doesn’t need boot to load in I/O (blockio). These I/O handlers are loaded into memory to form the oper- this location because the following loosely based on the Unix I/O model. ating system, DOS-C uses just one file, stages are either position independent The character I/O type appears as a KERNEL.EXE. or relocatable. And, we can judiciously stream of bytes to the kernel. The Additionally, the kernel uses the juggle the following stages for any kernel either sequentially reads a byte standard C memory layout of text + data size kernel. from or writes a byte to a device driver. + bss + stack and the ’x86 small model. As a neutral choice, I can load There are also functions to read a This setup gives you an interesting stage two, IPL.SYS, into memory at buffer into memory and handle the degree of flexibility that MS-DOS and 1000:0000h. There is no magic to this familiar DOS line-editing functions. other DOS clones don’t—you can address, and it can be almost anywhere. The block I/O interface provides locate the DOS-C kernel anywhere in I can dynamically locate IPL.SYS functions to read and write a block of memory, including ROM. anywhere in memory because it is built data to a block device—usually a disk. from the kernel source code using the Each block corresponds to a sector and BOOTING FROM DISK ’x86 small model. This limits the total is represented in memory as a data Figure 2 depicts the four distinct size of IPL.SYS to only 64 KB. But by structure in a block cache. When the stages involved in the boot. This ap- limiting the scope of the IPL, we can kernel reads data, blockio reads the proach simplifies the design through easily fit its functionality into this sector into a buffer and places it into a modularization and minimizes the effort amount of memory. least recently used (LRU) chain. expended in software maintenance. IPL.SYS loads KERNEL.EXE and is When blockio needs a new buffer, For example, a bug that may exist aware of the MS-DOS file systems. it writes the tail of the list to disk, if in KERNEL.EXE doesn’t require changes However, its lifetime is short and its needed, and returns that buffer. When in IPL.SYS. As well, no change in size purpose is simple: load the kernel. To blockio completes the data transfer, of either IPL.SYS or KERNEL.EXE reduce development time, I derive the the buffer goes to the head of the LRU affects the other. IPL from the kernel source by reduc- chain, indicating that it’s the newest The booting of DOS-C begins from ing the kernel functionality to only buffer. within the computer’s ROM BIOS. what is needed to load the kernel. Management functions handle these After power-up self-test, the BIOS This task is completed via #ifdef operations for dirty buffer write back, initiates the boot procedure and is at switches throughout the kernel. These as well as buffer fill. It also performs the first stage. switches cut out unneeded functions buffer-management functions like This stage is identical to the way such as the API, write, or delete. LRU management and flush. almost any PC-compatible OS starts We only need functions like open, As with the API, the device-driver out. The BIOS sets aside a specific read, and close. We further reduce interface is well documented. Because location in memory and the initial IPL.SYS by including only one loader

Circuit Cellar INK® Issue 95 June 1998 77 the processes of loading the boot block console. The same holds true of other LCD and IPL.SYS naturally disappear, but device drivers. It’s possible to create the the memory layout of the kernel may application on a typical DOS platform Keypad change. and move it into the target device by Typically, ROM space is allocated changing only the device driver. in different areas than RAM and may Only certain key functionalities Console Printer Thermal Driver Driver Printer be noncontiguous. To accommodate need to be implemented, such as line

Serial Port this, a commercial locator fixes the feed to move characters to the LCD. Driver Modem memory locations so the ROM image The same is true of other devices. Application FreeDOS Software Floppy is correct and does not need fixing up. or DOS-C Disk Kernel Drive or Driver EPROM It also means that when DOS-C runs, TAKING OFF or EEPROM its strings and tables may be located In Part 2, I’ll take a closer look at an Other Special in ROM. The ROM start-up code intelligent printer similar to the ones Drivers Hardware, LAN, etc. handles this situation by initializing used in airports for printing tickets RAM and moving fixed data to RAM. and boarding passes. Figure 4—Similar to the development environment, the The ROM startup effectively by- These ATB printers are generally FreeDOS/DOS-C kernel performs the device and overhead management. Using device virtualization, the passes stages one and two. When it quite complex and need many commu- kernel allows the devices to be those typically found in completes, it invokes main and DOS-C nication modules and interface emula- embedded controllers and yet still use a standard API. continues with stages three and four. tion modules with different types of COMMAND. In the embedded application, the use of Then, DOS-C is ready and running interface drivers. Also, they sometimes COM is optional. from ROM. need different print-mechanism driv- and the device drivers for disk and ers for different types of stock that console. TYPICAL APPLICATION may be used by the printer. Stage three starts once the kernel is When you examine a typical DOS Typically, applications such as these, loaded into memory. The kernel starts application, such as the one illustrated where the core software remains un- at main, like any C program, and begins in Figure 3, you’ll notice that the touched but many I/O options exist, by initializing itself. This task includes application runs more or less along- make good candidates for embedded locating all of memory and building side MS-DOS. This action is because OSs. Next month, I’ll show you how arenas and loading the proper addresses MS-DOS actually runs in the same DOS-C simplifies such a design. I into the interrupt vectors. After initial- memory space as the application. Pat Villani has 22 years of industry ization, the system begins to process Although you might initially con- experience in both hardware and CONFIG.SYS . sider this situation a hindrance, for the software, most recently developing Finally, the kernel searches for and embedded developer, it’s a blessing in firmware and real-time kernels. He COMMAND.COM loads into memory and disguise. For example, the application currently works for a major computer makes this the granddaddy program. If can handle real-time events external company writing portions of OS ker- COMMAND.COM returns, the kernel shuts to the operating system. nel and system management tools. down and you need to reboot. This However, you need to be careful in You may reach Pat at [email protected]. situation is no different from the case system design to properly partition COMMAND. where MS-DOS cannot find functionality. For example, you don’t SOFTWARE COM and issues the error message “Bad want to replace any device-driver func- or missing command interpreter,” only tionality with code unique to your FreeDOS is available at ftp.simtel. this approach is cleaner. application. Your design is much more net and www..org. The When COMMAND.COM successfully robust if you can replace only the latest kernel is available at www. loads, stage four commences. COMMAND. device driver when changing platforms. iop.com/~patv. COM does its own initialization, includ- As an example, let’s look at an ing creating the initial environment intelligent printer. In design, it’s simi- REFERENCES and executing AUTOEXEC.BAT. When lar to the typical DOS application. In [1] P. Villani, FreeDOS Kernel, R&D this completes, COMMAND.COM issues Figure 4, you immediately see the Books, Miller-Freeman, New a prompt and goes into a loop await- similarity between them where the York, NY, 1995. ing user input. DOS-C is now loaded application coresides with the kernel. [2] A. Schulmann et al., Undocu- and ready to run. You also see a significant number mented DOS, Second Edition, of differences in the peripheral devices. Addison-Wesley, Reading, MA, BOOTING FROM ROM One difference is the console. The 1994. When built with a different start- normal keyboard and display is replaced up module, DOS-C can also run from with an LCD and keypad. I R S ROM. The booting method varies In this example, the application and 425 Very Useful slightly because of the nature of the kernel remain constant, but the device 426 Moderately Useful medium. When booting from ROM, driver changes to handle the different 427 Not Useful

78 Issue 95 June 1998 Circuit Cellar INK® growth derives from the law of small numbers, not the death of 8-bitters. SILICON Indeed, today’s billions of units per year are just the tip of the iceberg. It’s UPDATE not hard to imagine a cyberfuture where little chips permeate our existence.

MCU CLASSIC Tom Cantrell I’ve worked with various companies hoping to enter the micro business. It’s critical, but sometimes difficult, to convey to a commodity IC outfit that micros are a different beast altogether. Fabulous ’51s For example, a manager recently asked me how designers decide which micro to use. To him, if a micro offered a few key features for a good price and delivery, that was all there was to it. Of course, that’s not at all what happens. The decision is driven by human factors. Designers sometimes choose a new chip for the fun of learn- Even o doubt, you’ve ing it. Usually, though, they rely on n heard dire predic- their own stable of chips, tools, and though tions like “The 8-bit accumulated know-how. Only truly micro is dead.” Of course, compelling technical issues justify the it’s been the source is usually some expert who nontrivial challenge and risk of switch- happens to make a living marketing ing to a completely new architecture. around 16- and 32-bit chips. Or, it might be That’s why 20-year-old designs like an analyst who sells rosy studies to the ’51, 68xx, PIC, and Z8 still play a for a long those marketeers so they have some lead role. The issue isn’t whether a new ammo for the next staff meeting. architecture is technically superior (not time, the 8-bit micro Well, it’s nonsense! Statisticians may hard with 20 years of hindsight) but quibble over the exact number, but whether the old chips are good enough. keeps on going and there’s no doubt the lowly 8-bit MCU plays a huge—and growing—role in our MULTISOURCE CODE going and going. In lives. Yes, 16- and 32-bit chips are doing Old-timers will remember the hey- fact, new variations wonderful things, but their strong day of second sourcing, when chip Compatible with MCS-51 products keep popping up. 8 KB of in-system reprogrammable downloadable flash memory SPI serial interface for program downloading PDIP

Endurance: 1000 write/erase cycles (T2) P1.0 1 40 VCC Tom lets us in on the 2-KB EEPROM (T2 EX) P1.1 2 39 P0.0 (AD0) Endurance: 100,000 write/erase cycles P1.2 3 38 P0.1 (AD1) 4.0–6-V operating range P1.3 4 37 P0.2 (AD2) smarts some of these *(SS) P1.4 5 36 P0.3 (AD3) Fully static operation: DC to 24 MHz (MOSI) P1.5 6 35 P0.4 (AD4) Three-level program memory lock (MISO) P1.6 7 34 P0.5 (AD5) new ones possess. 256 × 8-bit internal RAM (SCK) P1.7 8 33 P0.6 (AD6) RST 9 32 P0.7 (AD7) 32 programmable I/O lines (RXD) P3.0 10 31 *EA/VPP Three 16-bit timer/counters (TXD) P3.1 11 30 ALE/*PROG 9 interrupt sources *(INT0) P3.2 12 29 *PSEN Programmable UART serial channel *(INT1) P3.3 13 28 P2.7 (A15) (T0) P3.4 14 27 P2.6 (A14) SPI serial interface (T1) P3.5 15 26 P2.5 (A13) Low-power idle and power-down modes *(WR) P3.6 16 25 P2.4 (A12) Interrupt recovery from powerdown *(RD) P3.7 17 24 P2.3 (A11) Programmable watchdog timer XTAL2 18 23 P2.2 (A10) XTAL1 19 22 P2.1 (A9) Dual data pointer GND 20 21 P2.0 (A8) Power-off flag

Figure 1—Atmel, a flash ’51 pioneer, offers a new ’8252 which incorporates 8-KB flash memory for code and 2-KB EEPROM for data. The chip can be programmed in parallel or serial mode, the latter via a four-pin (select, clock, in, out) SPI interface.

80 Issue 95 June 1998 Circuit Cellar INK® people’s micro, if you Let’s take a look at the latest devel- R/*W XTAL 1 Watchdog OSC will. opments on the ’51 front, and you’ll Timer *CE1–4 4 XTAL2 This doesn’t mean see what I mean. Address the laws of economics BA15–0 are repealed. Yes, you FLASH IN YOUR FUTURE? 16 RST Interface Data can shop around for a Flash micros are starting to take off, ALE Byte-Wide Bus BD7–0 cheap, plug-compatible and there’s a lot of reason to believe *PSEN 8 EA Control *PE1–4 8051. But don’t expect they’ll become even more popular. Timing and Bus 4 suppliers to cut their Atmel, the undisputed leader in flash-

P0.7 own throats. They’re based ’51s, is well-positioned for such about as excited about an eventuality. However, Philips (the Special- Function VCCO a lowball ’51 deal as largest ’51 supplier overall) has recently Registers the folks at Rockwell announced plans to join the fray.

P0.0 VCC or Hitachi are about a Before checking out the parts, real- Lithium *PF 68k inquiry. In other ize that all flash micros aren’t created Control P1.7 *VRST Data words, don’t call me, equal. For example, first-generation Registers I’ll call you. flash micros are little more than an (128

Port 1 0 Bytes) What it means is EPROM/OTP replacement because they that, across the raft of use the same parallel programming V P1.0 LI suppliers, ’51 designers scheme, 12.5 V , and so on. CPU PP P2.7 have access to a broad This is OK, but it really doesn’t spectrum of products— support the popular idea of streamlined Bootstrap Loader a lineup more exten- assembly line programming. Sure, it’s ROM sive than possible from possible to kludge together some kind P2.0 any single supplier. of hack for a pseudo-EPROM flash chip TXD P3.7 Furthermore, it means (e.g., muxes for all the pins, switch- RXD the ’51 is continually able 12 VPP, etc.), but it isn’t clean. Timer 0 freshened and up- By contrast, Atmel’s latest flash ’51s, Timer 1 Port 3 2 graded, ensuring that such as the 89S8252 shown in Figure 1, INT0 P3.0 INT1 the technology gap offer the best of both worlds. They

with newer architec- still support parallel, high VPP program- tures doesn’t get too ming for those happy to stick with Figure 2—The Dallas ’5001FP supplements a standard ’51 core with a dedicated byte-wide code and data bus, freeing port pins to handle peripheral I/O functions. wide. gang programming. Finally, although At the same time, they include a suppliers battled for designers’ share of true plug compatibility is limited to serial programmer that only needs a few mind by encouraging, at least on the the old baseline chips, plug similarity pins (SPI inter- surface, wide sourcing. I remember a goes a long way towards ensuring face) and a Motorola press conference where they healthy competition. It’s a lot easier to single power touted the 68k’s big tent with a bunch switch from one ’51 to another supply (5 V). of licensees that included the likes of with a few different features Holding Hitachi, Philips, Rockwell, and others. than to a completely From a purchasing agent’s point of new architec- view, it was the golden age—much as it ture. remains for commodity ICs today. You could call multiple distributors and get them bidding against each other by telling each that the other guy was lower until only one was left standing. That might work for DRAMs, but the micro business needs more fixed investment (for R&D, tools, etc.), and thus profits, than such destructive competition allows. Inexorably, the multisourced micro disappeared and Photo 1—The EZ- is now practically extinct. USB Xcelerator kit Except for the ’51, that is. Of the old includes a development board, software tools (C, ASM, debugger) from 8-bit war-horses, it’s unique by virtue Keil Software, and plenty of software drivers of profligate sourcing. It’s a veritable and examples.

Circuit Cellar INK® Issue 95 June 1998 81 the part in RESET invokes the serial needs 5 V, whereas the DS5001FP 128K × 8 SRAM programming mode, which lets the flash Philips uses 12 V. For (and extra 2 KB of on-chip data EEPROM) compatibility with exist- +5 13 VCC VCCO 12 32 VCC 54 change a single byte at a time (i.e., no ing programmers, both VLI R/*W 10 29 need to erase the entire chip). require high voltage for *WE +3-V 74 22 30 The new Philips 89C51RX+ dishes parallel programming. Lithium *CE1 *CS1 CS2 Battery up another flavor of flash memory. Like Otherwise, Atmel and 24 2 2 A16 *OE Atmel, Philips supports traditional Philips parts have a lot of *CE2 PORT0 parallel and in-system programming other neat features and BA14–BA0 A14–A0

(ISP) modes. upgrades. They have dual PORT1 63 31 However, the Philips ISP philosophy data pointers, fancier *CE3 A15 is subtly, but profoundly, different from peripherals, watchdog PORT2 Atmel’s. Both parts are ISP in the sense timers, faster clocks, and BD7–BD0 D7–D0 of easy post-PCB assembly (re)program- more. Designers are sure PORT3 16 GND ming. Philips goes a step further with to benefit from the battle 14 52 self-programming that enables the chip for their flash ’51 favor. MSEL GND to dynamically change its own code. Here’s how it works. A Boot ROM ’51 RAM CRAM Figure 3—With built-in voltage supervisor, battery switching, and bootstrap overlays the top 1 KB of code space, Dallas Semi is known ROM, the ’5001FP is especially well-suited for SRAM connection. The chip which contains routines to erase a for its fast (4 clock/instruc- completely manages the SRAM power and control signal generation, maintaining data integrity without needing any glue logic. block, program byte, verify byte, and tion at 33 MHz) 80C320, so on. There’s also a Boot Vector that but it has other tricks up its sleeve, too. Besides the ’5001 chip, Dallas also defines what happens after RESET The DS5001FP depicted in Figure 2 offers the DS2251T module, which depending on the state of a flash-status is an interesting alternative that com- combines the MCU with a 32–128 KB byte. Execution at the Boot Vector can bines a vanilla ’51 with a dedicated byte- of SRAM, real-time clock, and battery. also be forced by external pin setting. wide memory bus, so adding external The Boot Vector in turn points to a memory doesn’t consume I/O port “OH SAY CAN USB?” user-written Loader in one block of the pins. Four chip enables (*CE1–4) sup- That was the title of my article about flash memory that’s responsible for port various combinations of 32-KB USB in INK 74. There, I pointed out that erasing and programming the other blocks for a total of up to 128-KB the USB concept was grand, especially blocks. The Loader, taking advantage memory. Likewise, four peripheral compared to the ludicrous rat’s nest of calls to the Boot ROM, can self- enables (*PE1–4) handle data accesses. of parallel, serial, mouse, game pad, program the chip using any technique. While any type of memory can be and so forth lurking behind PCs. For example, using the 89C51RX+, you used, the DS5001FP is especially well- However, the downside of vaunted can remotely (re)program it via modem suited for SRAMs (see Figure 3). An PC compatibility is inertia. I correctly a built-in feature of your design. on-chip voltage supervisor not only reckoned USB wouldn’t take off until Note the default shipping configura- generates power-fail detect (*PF) and the arrival of a critical mass of built- tion includes a prewritten Loader to reset (*VRST) but also controls the in driver software with Win98. accept commands and data via the on- previously mentioned byte-wide bus Despite the fact there’s a zillion USB- chip UART. That means a factory-fresh enables to prevent spurious writes. capable PCs out there, the vast major- part can be inserted in a board and Like Philips’ flash parts, the ’5001 ity of USB ports are gathering dust. programmed serially at a later time. includes a bootstrap loading feature The issue is complicated by the fact One key difference: in serial pro- that downloads the SRAM via serial that Win98 seems to be slipping (no real gramming mode, the Atmel part only port after first-time powerup. Once surprise), with the rather interesting initialized and verified, kicker that an awful lot of lawyers are the bootstrap loader involved. As well, the quality and quan-

12-MHz PLL leaves the stage, and tity of USB support in Win98 remains XTAL Enhanced 8051 Core I/O Ports (24) power-management logic to be seen. I overheard one Microsoft ensures that the SRAM engineer saying they’ve “got more D+ remains valid (up to 10 important networks to deal with.” USB 8-KB Address Bus (16) XCVR D– Anchor or years, depending on the The transition to Win98 and/or USB 32-KB Data Bus (8)

USB Data Bus (8) RAM battery). The SRAM need may not be as quick and clean as antici- Engine Address Bus (16) Core never again be touched pated. At this point, USB is scratching 2-KB (at least until the battery for each peripheral design and inch of FIFO I2C runs dry), but it can be shelf space one torturous step at a time. rebootstrapped as often Ultimately, however, I believe the Figure 4—When USB finally starts rolling, look for ’51-based derivatives like as desired by driving the combination of automatic-installed base the Anchor Chips AN21xx to get onboard. *PROG input. (i.e., USB on every motherboard) and

Circuit Cellar INK® Issue 95 June 1998 83 keeps the ’51 young at heart. It approach, supports full 1024-byte HOST DEVICE combines the best aspects of isochronous (i.e., time-sensitive stuff E Host identifies device other derivatives in a unique like audio, video, and high-speed data N is attached U combination (see Figure 4). acquisition) packet transfers in less M E Anchor Chips starts with a than half of a single 1-ms USB frame. R Host assigns unique Device provides initial A address to device device descriptors hot-rodded four-clock/instruc- The chip comes in low-cost 44- and T I tion core. A PLL fed by an 80-pin PQFP packages (Photo 1). Larger O Host issues configuration N to be used by device external 12-MHz crystal versions support external expansion by generates the 24-MHz CPU bringing the address and data bus (non- R clock and 12-/1.5-Mbps (high/ muxed, don’t need a latch) off chip. E Host loads new firmware Device simulates disconnect N into device from S/W file and reconnect low data rate) USB clock. Another variant brings out only the U M The USB engine is powerful, data bus for connection to an external E Host begins Device provides updated R enumeration again config info to host with a default device descriptor FIFO, providing dedicated read and write A that lets it boot as a generic pins (*FRD, *FWR) to drive it. Other- T I Host verifies new device. Logic handles the low- wise, every version of the chip includes O resources available N level transfer details, accom- an I2C port and 24 I/O lines configurable plishing an entire multipacket to function as PIO or the usual alternates Host issues configuration to be used transaction in hardware. Thus, (e.g., UARTs, timers, interrupts, etc.). according to Anchor, manag- Of course, a RAM-based design raises Figure 5—Booting up the AN21xx is a two-step process. First, ing the network consumes the obvious question of how to install there’s a normal USB enumeration cycle, and application-specific ’51 code is downloaded into the on-chip RAM. Next, renumeration only 10% of CPU bandwidth, code after powerup? One approach, like reintroduces the PC to the now-personalized chip. leaving the rest for application- an FPGA, relies on accessing an external specific processing. boot memory (either I2C or parallel) to simple sanity will prevail. And when Although a ROM version is available, load the on-chip RAM after powerup. it does, the market for USB chips—no Anchor’s claim to fame is exploiting on- Anchor calls its more novel approach shortage of them ’51 based—will explode. chip RAM—and there’s a lot of it (up “renumeration.” The USB spec requires The AN21xx from Anchor Chips is to 32 KB). There’s also an extra 2 KB of bus enumeration when a peripheral a good example of the way new blood USB FIFO which, using a ping-pong disconnects or connects (i.e., hot plug).

84 Issue 95 June 1998 Circuit Cellar INK® At powerup, the Anchor chip auto- startup. The company did very well 89C51RX+ matically enumerates as a default USB over the years, making him quite Philips Semiconductors device. Then, as shown in Figure 5, a wealthy along the way. 811 E. Arques Ave. host PC downloads the ’51 code via the If you haven’t already guessed, that Sunnyvale, CA 94088-3409 USB connection into the on-chip RAM. company’s success was based in no (408) 991-5207 Once loaded, the chip simulates a small part on a popular line of 8-bit Fax: (408) 991-3773 disconnect/reconnect, causing the host chips! You can bet I always ask him if www-us2.semiconductors.philips. PC to renumerate. This time, Anchor’s the 8-bit market is dead yet every com/microcontrol chip responds to interrogation with the time I see him. DS5001FP, DS2251T just downloaded device description. MCUs may come and go, but ’51s Dallas Semiconductor I This feature provides a neat chame- are here forever. 4401 S. Beltwood Pkwy. leon-like capability. For instance, take Tom Cantrell has been working on Dallas, TX 75244-3292 a piece of USB-based data-acquisition (972) 371-4448 gear with a variety of functions and chip, board, and systems design and marketing in Silicon Valley for more Fax: (972) 371-3715 modes. Depending on the task, an An- www.dalsemi.com chor-based solution can switch hats than ten years. You may reach him by by redefining the number of endpoints E-mail at tom.cantrell@circuitcellar. AN21xx (up to 16), type of connection (e.g., com, by telephone at (510) 657-0264, Anchor Chips, Inc. isochronous, bulk, interrupt, control), or by fax at (510) 657-5441. 12396 World Trade Dr., MS 212 and FIFO allocation appropriately. San Diego, CA 92128 SOURCES (619) 613-7900 AND THE CHIP PLAYED ON 89S8252 Fax: (619) 676-6896 The 8-bit micro was initially pro- Atmel Corp. www.anchorchips.com nounced dead 20 years ago during the 2125 O’Nel Dr. height of the original showdown be- San Jose, CA 95131 I R S tween the 8086 and 68k. (408) 441-0311 428 Very Useful The marketing guy giving the pre- Fax: (408) 436-4300 429 Moderately Useful mature eulogy moved on to a small www.atmel.com 430 Not Useful

Circuit Cellar INK® Issue 95 June 1998 85 PRIORITY INTERRUPT

Darwin Couldn’t Have Done Better

volution is a good thing. I hate to think how boring everything would become if there were no improvements in e ideas or products. Just imagine—if nobody wanted to go faster and climb higher, a mouse might still be just a rodent. Today, we are in the information age. I say that rather than calling it the computer age because the wealth and speed of information gathering is the greatest evolution. A computer, like the automobile, may be the physical component that triggers cultural growth and evolutionary change, but it takes an application with universal acceptance to create a true revolution. One of the critical areas being affected by the rapid evolution of the Internet is print publishing. If you listen to marketing people from MIS and electronic-media organizations, they’ll tell you that there’s no reason to buy a printed book or magazine ever again. Of course, a similar claim was made shortly after the invention of the television. And, we all remember how the VCR was supposed to spell the demise of movie theaters. In short, be careful of predictions. This information revolution is a phenomenal bandwagon that can’t be ignored. Because the degree of commitment is so critical, however, it’s even more important to carefully examine all the facts. The first reality is that, much to the chagrin of electronic publishers and electronic communication companies, print media isn’t going away. While it’s theoretically possible to publish everything in an electronic-only format, the people who actually buy subscriptions seem to have a different opinion about its necessity—basically, “don’t rush me!” In my experience, the pressure isn’t to simply replace print magazines with their electronic online equivalent. Instead, there seems to be a marriage of accommodation. This marriage of technologies doesn’t necessarily dictate an equal distribution of either resources or subject content, however. Of course, certain tasks should be logically allocated to the more efficient partner. Until bandwidth isn’t the limiting issue, printed media is still the better place for high-resolution photographs and complicated schematics. Long program listings, articles too short to print, archived articles, and product datasheets are more suited to the Web. A realization of this new division of resources should be apparent this month. Magazines traditionally offer Reader Service. That’s the official name for the bingo card next to the advertiser index page that you fill out and mail in for more product information. The bad news is that I’ve eliminated bingo cards in INK! The good news: we now have the advertisers and their URLs set up on our Web site. Traditionally, the number of bingo-card responses was a measure advertisers used to gauge the value of their ad placements. But, using such an inadequate and inefficient medium to judge the quality of a highly motivated audience like INK’s certainly begs the question. Like most of our readers, when I see something interesting in an ad these days, I don’t go check off the bingo card and sit around three weeks waiting for something to arrive in my mailbox. I immediately go to the Web site and download the datasheet—instant action and instant gratification. I don’t have a crystal ball and I can’t predict the eventual shakeout between print and electronic media. What I can predict is purely personal. Circuit Cellar INK is in the process of greatly expanding its Web site to better serve both readers and advertisers. Like all good things, the process will take some time, but our Web site is going to contain more of the projects and relevant application materials that have always distinguished Circuit Cellar from the crowd. It may no longer be enough to simply say that we publish a reputable technical reference magazine. People with hands-on responsibility, like INK readers, always have a thirst for more application materials. The Internet offers a convenient medium to expand technical product support. Establishing and maintaining a company Web site shouldn’t be viewed merely as a competitive accommoda- tion to rolling evolution. Properly utilized, a Web site can be the vehicle that is that evolution.

[email protected]

96 Issue 95 June 1998 Circuit Cellar INK®