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 # 1 0 0 N O V E M B E R 1 9 9 8 INDUSTRIAL CONTROL Control via the Internet

Making Buildings Smarter

Embedded Linux

Toughen up that PC BIOS

$3.95 U.S. $4.95 Canada TASK MANAGER

Netting 100

®

th INK n your hands you hold the 100 issue of i Circuit Cellar INK. Have you been here from the beginning, over 10 years ago? Or, maybe you just 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 picked up this issue from the newsstand today for the EDITORIAL DIRECTOR/PUBLISHER ASSOCIATE PUBLISHER very first time. No matter. It’s definitely a time for celebration! Steve Ciarcia Sue Skolnick I find it fitting that a milestone issue like this one has the theme MANAGING EDITOR CIRCULATION MANAGER Industrial Control. After all, home automation and building control has been Elizabeth Laurençot Rose Mansella a Circuit Cellar hallmark from the start. It’s nice to see that although the TECHNICAL EDITORS CHIEF FINANCIAL OFFICER Michael Palumbo Jeannette Ciarcia implements have of course changed over the years, the interests haven’t. Rob Walker ART DIRECTOR INK still focuses on what the readers want. WEST COAST EDITOR KC Zienka But , the implements have changed indeed. No longer are the control Tom Cantrell ENGINEERING STAFF options limited to switches and sensors. There’s a new game in town—well, CONTRIBUTING EDITORS Jeff Bachiochi in the world, to be more accurate: the Internet. Ken Davidson Fred Eady PRODUCTION STAFF The capabilities we get through the web are far beyond what we’ve Phil Champagne NEW PRODUCTS EDITOR John Gorsky been able to do without it. OK, I admit, sometimes I get a bit bored hearing Harv Weiner James Soussounis the same old hype about how everything is going to be done through your PROJECT EDITOR computer—you’ll turn on the heat at home before you leave the office, you’ll Janice Hughes order take-out, you’ll do some catalog shopping, you’ll be able to check EDITORIAL ADVISORY BOARD whether you left the iron on after you left the house, and on and on. But, I’m Ingo Cyliax Norman Jackson David Prutchi starting to get impressed: this scenario is coming true! Cover photograph Ron Meadows—Meadows Marketing In this issue, Chris Sontag shows us a web-implemented irrigation PRINTED IN THE UNITED STATES controller system that revises the sprinkler schedule based on weather ADVERTISING forecasts retrieved over the Internet. And if the forecasts prove wrong—oh, ADVERTISING SALES MANAGER Bobbi Yush Fax: (860) 871-0411 that never happens, right?—you can simply access the controls via a web (860) 872-3064 E-mail: [email protected] browser. (I guess this means no more laughing as you pass the building on ADVERTISING COORDINATOR the corner that has its sprinklers set for 4 P.M., come rain, come shine.) Valerie Luster Fax: (860) 871-0411 (860) 875-2199 E-mail: [email protected] Sounds pretty good, right? Of course, there’s a new challenge: how are you going to use the Internet in your applications? CONTACTING CIRCUIT CELLAR INK Well, if you need some ideas or want to kick around some thoughts SUBSCRIPTIONS: INFORMATION: www.circuitcellar.com or [email protected] with other engineers, here’s some good news. Circuit Cellar INK is a co- TO SUBSCRIBE: (800) 269-6301 or via our editorial offices: (860) 875-2199 GENERAL INFORMATION: sponsor of the First Annual Embedded Internet Workshop being held on TELEPHONE: (860) 875-2199 FAX: (860) 871-0411 Friday, November 6, at the Wyndham Hotel in San Jose. INTERNET: [email protected], [email protected], or www.circuitcellar.com EDITORIAL OFFICES: Editor, Circuit Cellar INK, 4 Park St., Vernon, CT 06066 This workshop, organized by Dr. Lance Leventhal, offers sessions on AUTHOR CONTACT: embedded web servers, the future of embedded Internet, application E-MAIL: Author addresses (when available) included at the end of each article. ARTICLE FILES: ftp.circuitcellar.com development, embedded web hardware, embedded Java, and web security. For information on authorized reprints of articles, The day promises to be chock full of information from some of the leaders contact Jeannette Ciarcia (860) 875-2199 or e-mail [email protected]. in embedded web technology—Annasoft Systems, Lucent Technologies, CIRCUIT CELLAR INK®, THE COMPUTER APPLICATIONS JOURNAL (ISSN 0896-8985) is published monthly by Phar Lap Software, and Phoenix Technologies, to name just a very few. Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, And of course, we’ll be there. Tom Cantrell will introduce keynote Canada/Mexico $31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and speaker Mark Tolliver, who will talk about Java and the embedded market. possessions $39, Canada/Mexico $55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money order, or check drawn on U.S. bank. Steve and Jeff will be attending as well, and I’ll be there, actively recruiting Direct subscription orders and subscription-related questions to Circuit Cellar INK Subscriptions, P.O. Box 698, Holmes, PA 19043-9613 or call (800) 269-6301. editorial. We hope to see you at the workshop, but if you can’t make it, we’ll Postmaster: Send address changes to Circuit Cellar INK, Circulation Dept., P.O. Box 698, Holmes, PA 19043-9613. make sure you still get to read about the all latest useful control technologies Circuit Cellar INK® makes no warranties and assumes no responsibility or liability of any kind for errors in these and applications in Circuit Cellar INK. programs or schematics or for the consequences of any such errors. Furthermore, because of possible variation in 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 and Circuit Cellar INK are registered trademarks of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written [email protected] consent from Circuit Cellar Inc. is prohibited.

2 Issue 100 November 1998 Circuit Cellar INK® Mobile Environmental Control 12 Dan Leland Motor Commutation Techniques 20 Chuck Lewin

Web-Implemented Irrigation System 26 Chris Sontag

Smart Building-Control Applications 34 Beau Wadsworth

I MicroSeries 64 Digital Processing in an Analog World Part 2: Technology Choices David Tweed Task Manager 2 I From the Bench Elizabeth Laurençot 72 MIDI Netting 100 Part 2: The Show Must Go On Jeff Bachiochi Reader I/O 6 INK On-line I Silicon Update 78 Socket Rocket Tom Cantrell New Product News 8 edited by Harv Weiner

Advertiser’s Index/ 95 INSIDE December Preview Priority Interrupt 96 Steve Ciarcia ISSUE What’s PC?

PC 40 Nouveau PC edited by Harv Weiner 100100 44 All BIOSs are Not Created Equal Scott Lehrbaum

49 RPC Real-Time PC Embedded RT-Linux Part 1: General Introduction Ingo Cyliax 57 APC Applied PCs emWare Top to Bottom Part 1: Monitoring via the Internet MBEDDED Fred Eady E

Circuit Cellar INK® Issue 100 November 1998 3 READER I/O

CONSIDERING THE ALTERNATIVE Thanks for your comments. I’ll have to plead guilty I enjoyed Jeff’s article “Transformerless Power Con- to a conscious omission. I cringe when I see capacitors version” (INK 97), but he left out a method that performs being used this way. At any but the smallest currents, more efficiently and costs less than what he described. the heat build-up in these high-voltage capacitors As sources of reactance, inductors generally perform accelerates component deterioration. poorly compared to capacitors. I appreciate the desire Yes, this method is cheaper, and I would encourage to eliminate bulky inductors from a power supply, but adding a MOV across the input to protect the capaci- before abandoning reactance altogether, consider using tor from unforeseen over-voltages. However, from a capacitance. safety perspective, I wouldn’t base my product on it. A circuit with a series resistor (to resist fast line spikes) In fact, I’ve heard rumors that this form of power- and a series film capacitor, followed by a bridge, a par- stealing circuitry will not be cutting the muter in allel Al-electrolytic capacitor, and a zener (five compo- future consumer devices. nents) will perform well for a wide range of circuits. It offers higher efficiency (greater than 90%) and lower Jeff Bachiochi cost (less than $0.50 in quantities over 1000). A $0.20 250-V 0.47-µF series film cap provides more than 8 mA. The current depends on the derivative of the line voltage and is hardly affected by the output voltage (1.5–36 V). Editors note: The URL listed for Paradigm Systems in the sources section of Fred Eady’s “Debugging & Joe Betts-LaCroix the Net186,” (INK 97, p. 59) is incorrect. The correct [email protected] URL is www.devtools.com.

November Design Forum password: Control INK ON-LINE

Your magazine enjoyment doesn’t have to stop on PIC Abstractions the printed page. Visit Circuit Cellar INK’s Design Design Abstracts from our Design98 Contest Forum each month for more great online technical Digital Chromatic Tuner for Musical Instruments— columns and applications. Here are some of the great Darko Lazovic new on-line articles you’ll see in November: The Video Capture Pro—Winston Gadsby Columns Dot/Bar-Graph Controller—Eduardo Sigal Silicon Update Online: Standard Chips Can’t Be Counted Out—Tom Cantrell Lessons from the Trenches: Bridging C and Missing the Circuit Cellar BBS? Assembly—George Martin Then don’t forget to join the Circuit Cellar INK newsgroups! The cci newsserver is the engineer’s Forum Feature Articles place to be on-line for questions and advice on Build an 8051 Development System on a Budget— embedded control, announcements about the Bruce Reynolds magazine, or to let us know your thoughts about Creating a Flexible Custom Evaluation Tool INK. Just visit our home page for directions to Platform for ASICS—Eric Jacobsen become part of the newsgroup experience. www.circuitcellar.com

6 Issue 100 November 1998 Circuit Cellar INK® NEW PRODUCT NEWS Edited by Harv Weiner

variety of power-management and industrial-con- trol applications. The IC contains a wide-band transimpedance amplifier for converting the current into a propor- tional voltage through an internal, noninductive, 1.3-MΩ shunt resistor. The sense element operates in both high-side (VDD referenced) or low-side (ground referenced) applications. A current polarity indicator (sign bit) that gives a positive or negative indication of the current flow direction is included. A low-offset high-speed (90 ns) comparator pro- vides over-current indication with user-programmable threshold for precise setting of the over-current alarm. Excellent linearity is made possible by temperature- compensated internal circuitry (±200 PPM/°C), eliminating temperature-related offsets including self-heating effects. CURRENT-SENSOR IC The surface-mount UCC3926DS is packaged in a The UCC3926 current-sensor IC contains an internal 16-pin narrow plastic body SOIC and is priced at current-sense element and precision amplification circuitry $3.60 in 1000-piece quantities. to offer a complete, single IC solution for current sensing. It uses an integrated noninductive current-sense element Unitrode Corp. that eliminates the need for an external sense resistor, (603) 424-2410 minimizes power loss, and offers higher efficiency. It Fax: (603) 424-3460 handles input currents up to ±20 A, and it addresses a wide www.unitrode.com

LOW-POWER CONTROL DEVICE HulaPoint Remote combines an advanced motion only the standard mouse buttons are used, HulaPoint algorithm with an innovative Hall effect–type sensor to is compatible with both the Logitech three-button and provide accurate and effortless cursor control. The low- the Microsoft/IBM two-button mouse protocols. power device is designed for remote controls, such as The ergonomic sensor provides 10° of movement in those used for multimedia and game products, as well every direction. Because it uses magnet technology, as telecom devices and H/PCs. there are no moving parts to break or wear out. This HulaPoint Remote provides either CMOS-level serial quality makes the device highly durable. output or ASK modulated output, which is suitable for HulaPoint Remote is available as either a chip-and- driving the external-power sensor kit for integration transistor and IRED (infrared on an existing PCB or as emitting diode). Equipped a drop-in module. Drop- with a wait mode, it con- in modules are designed sumes less than 50 µA and to fit customer require- operates in a 3–5-V range. It ments. can be powered by three or An evaluation kit four AA batteries and will containing the remote operate for one year on and all the components three batteries. necessary to test the As well, HulaPoint Re- device is priced at $150. mote can encode up to 12 keys. These keys may be USAR Systems, Inc. used for left, right, and (212) 226-2042 middle mouse-button selec- Fax: (212) 226-3215 tion and as function keys. If www.usar.com

8 Issue 100 November 1998 Circuit Cellar INK® NEW PRODUCT NEWS RUGGEDIZED VIDEO CAMERAS The GBC TKO-450 and TKO-935C (both known as The Brute) are discreet industrial- strength cameras that can be used indoors or outdoors. The heavy-duty die-cast camera case features a polycarbonate window, tamper-proof screws, and conduit fittings for cable entry, making the unit weather- proof and vandal resistant. Both the TKO-450 (B/W model) and the 1 TKO-935C (color model) feature a ⁄3″ CCD camera that is internally adjustable on a three-way gimbal. An included corner mount features a ball joint for external adjustability. The camera comes standard with a clear polycarbonate window, and an optional gray window is available if conceal- ment of the camera is desired. 8-BIT RISC The TKO-450 has over 425 lines of reso- The PIC12CE673 and PIC12CE674 lution and a sensitivity of 0.03 lux. The are one-time programmable (OTP) 8-bit RISC microcontrollers TKO-935C has 330 lines of resolution and a featuring EEPROM data memory, four-channel 8-bit ADC, and sensitivity of 0.4 lux. The color model also an on-chip oscillator. The ’673 features 1024 × 14 words of OTP has automatic through-the-lens white bal- program memory, and the ’674 offers 2048 × 14 words of OTP ance and backlight compensation for true- program memory. Both devices have 128 bytes of SRAM and 16 color rendition. Both models come standard bytes of EEPROM data memory, enabling critical system-param- with a 4-mm lens, electronic shutter, and eter storage to be distributed throughout the application. Typi- power supply. Optional 2.5-, 6-, 8-, and 12-mm cal applications include remote controls, security systems, lenses are also available. battery chargers, PC peripherals, and smart sensors. The TKO-450 lists for $349.30 and the The devices have six I/O pins, 35 single-cycle instructions TKO-935C lists for $559.30. (400-ns execution time), 8-bit timer/counter with 8-bit program- mable prescaler, and an on-chip 4-MHz clock oscillator for CCTV Corp. additional system cost and size savings. An in-circuit serial (201) 489-9595 programming capability enables the microcontrollers to be Fax: (201) 489-0111 programmed after being placed in a circuit board. Maximum www.gbc-cctv.com power-consumption is 2.0 µA for maximum battery life. The PICMaster Universal development system supports the microcontrollers. This Windows-based system features the MPLAB integrated development environment, which gives users the flexibility to edit, compile, emulate, and program parts all from a single user interface. The comprehensive PICMaster is available for $2490 without the Pro Mate II device programmer ($3345 with Pro Mate II). A CE-compliant version of PICMaster is available for European applications. The PIC12CE673 and PIC12CE674 are available in 8-pin PDIP and windowed CERDIP packages. Pricing in 1000-unit quantities (4-MHz, commercial temperature version) is $2.04 each for the PIC12CE673 and $2.39 each for the PIC12CE674.

Microchip Technology, Inc. (602) 786-7200 Fax: (602) 899-9210 www.microchip.com

Circuit Cellar INK® Issue 100 November 1998 9 NEW PRODUCT NEWS DIGITAL PANEL METER The DMS-30PC-4/20S series of 4–20-mA current-loop Datel, Inc. input, 3.5-digit, LED display-panel meters consists of a loop- (508) 339-3000 current conditioning board mounted to an epoxy-encapsulated Fax: (508) 339-6356 voltmeter. These devices operate from a single +5-V power www.datel.com supply or an optional supply ranging from 7.5 to 32 V (24 V nominal). The 2.17″ × 0.92″ × 1.0″ package features a large (0.56″) red or green LED display and 100% soldered connections. The advanced circuit design achieves a maximum loop drop of only 2 V. Two band-gap voltage references and precision metal film resistors ensure stable performance over the wide operating temperature range of 0° to +60°C. Gain (span) and offset (zero) adjustments are performed with high-precision, 20-turn potentiometers. All decimal-point and range-change settings are made on a gold-plated vibration-resistant DIP switch. There are no solder gaps or jumpers. Connections to the current loop and the power source are made on a rugged four-position screw-type terminal block. A bezel assembly, featuring secure screw fasteners and an EPDM rubber gasket, is available for applications requiring moisture and dust resistance. Low-power or high-intensity red LED models are also available. Prices for the meters start at $78 in single quantities.

10 Issue 100 November 1998 Circuit Cellar INK® NEW PRODUCT NEWS DATA TERMINAL The QTERM-B30 pedestal-mount operator-interface/ data terminal is a rugged low-cost device suitable for industrial applications. The terminal has a four-line × 40-character supertwist lighted LCD, 55-key tactile membrane keypad with QWERTY-style layout, and four programmable indicator LEDs for operator feed- back. The keypad legend and logo label can be fully customized. An optional manufacturer ID code means only terminals you buy operate with your equipment. The QTERM-B30 comes with an EIA-232 serial inter- face. An optional EIA-422 serial interface is available. Data rates from 1200 to 19,200 bps are accommodated with a wide range of data formats. Approximately 50 software commands are available to the host for con- trolling the terminal, including cursor control, query commands, and hardware (lighting, buzzer, etc.) control. The standard terminal uses an external 5-VDC supply, and an optional regulator enables operation with an external 7.5- to 24-VDC supply. The 8″ × 7.38″ × 1.5″ unit is made of a rugged cast-aluminum housing with QSI Corp. studs for pedestal mounting. (801) 466-8770 • Fax: (801) 466-8792 The QTERM-B30 sells for $585. www.qsicorp.com

Circuit Cellar INK® Issue 100 November 1998 11 FEATURES FEATURE 12 Mobile Environmental ARTICLE Control

Dan Leland 20 Motor Commutation Techniques

26 Web-Implemented Irrigation System Mobile 34 Smart Building-Control Applications Environmental Control

friend of mine a called me up a short Access is power. time ago and asked if I could help him out. Ap- Using a One-For-All parently, he wasn’t having much luck finding a device that would let him universal remote, X-10 remotely control a few lights, his TV, stereo system, and possibly an electrical modules, and a PIC, appliance or two. You might think it’s nothing that a universal IR remote Dan empowers the control and a little X-10 technology couldn’t handle. wheelchair-bound Well, that’s not the whole story. There were a few other issues to think community, giving a about. My friend is paralyzed from the neck down and is on a limited budget. quadriplegic friend His search of available assistive tech- nologies turned up a fairly good selection remote access to the of environmental control products, but only a few of the more expensive de- lights, thermostat, vices came close to meeting his needs. In all fairness to the companies security system, and that develop special-needs technology, it’s important to remember that people more. with severe physical disabilities repre- sent a small market. A company that produces assistive devices by the doz- ens, or even hundreds, is not able to benefit from the kind of economies that typical consumer-electronics manufacturers enjoy. So, prices tend

12 Issue 100 November 1998 Circuit Cellar INK® to remain high for even the most basic that enables you to operate an OFA came up with is a simple scanning type technical aids. without having to press the buttons, of controller. Considering all the various commer- and presto, you have the makings of The scanning user interface (SUI) cialization hurdles facing manufacturers an accessible environmental-control has 40 labeled LEDs (arranged in a 4 × of assistive devices, I was somewhat solution. 10 array) corresponding to the buttons surprised to find so few independently Of course, I’m referring to the three- on the OFA infrared remote. As the engineered adaptations of existing pin serial port built into the upgradable name implies, a person scans the dis- consumer products. Why couldn’t a models, which was originally intended play and selects various control options universal remote and a few X-10 mod- for in-house use as a means to update using one or two input switches. The ules be made a little more accessible? preprogrammed manufacturer codes. SUI translates the selection and sends Needless to say, it didn’t take home- the appropriate control command to the NOT JUST ANY REMOTE automation enthusiasts long to discover OFA through a serial connecting cable. In many cases, the fact that most that all the OFA button functions can The SUI is built into a small black consumer electronics products are so be accessed via the port. Connect a enclosure, occupying very little space highly integrated and miniaturized is suitable host controller, and you have (see Photo 1). It mounts next to the probably the biggest barrier to creating a fairly versatile gateway for home- wheelchair armrest, where it’s fairly accessible options. I have to admit, the control applications. inconspicuous yet visible to the user. idea of adapting an existing infrared The OFA mounts to the wheelchair remote wouldn’t have seemed all that SUI AS IN GUI? frame, behind and above the user’s right practical had I not been familiar with I wanted to avoid building a custom shoulder, for optimal IR beam spread. the One-For-All (OFA) series of univer- input device, so I tried to design an sal remotes available from Universal interface that could be used by people TWO WAYS TO SCAN Electronics. with physical disabilities other than A person navigates through the SUI Many of their devices are affordable, quadriplegia. As a result, I decided to display and makes selections using X-10 capable, and able to control a stick with some of the more tried and one of two operating modes. Auto-scan variety of audio-visual components. trusted methods that are used to con- mode generates an automatic scanning Add to the list a unique little feature trol assistive devices. The answer I sequence with three selectable speeds.

Figure 1—With so few components, the SUI circuitry can be built into a relatively small enclosure. A four- position DIP switch provides several selectable control options.

Circuit Cellar INK® Issue 100 November 1998 13 Both scan and select functions are The SUI accepts most ability to assembly programming. I knew controlled by a single switch. The switches or any SPST momentary there were some great software tools first switch closure powers the SUI contact switch. There’s a wide range available for the PIC line of micros. on, and the second starts the scan of ability switches available through The ’16C84 had just enough I/O for down the leftmost column of LEDs. manufacturers and distributors of the job, and I didn’t let a single pin go A third switch action redirects the assistive devices, and they’re designed to waste. Almost half of the I/O-port scan across a desired row. Once the to respond to gross and fine physical pins are used to control the LED display scan reaches the appropriate point, the movements (e.g., blink, finger-flex, array. final switch activation executes the head-tilt, sip-and-puff, and oversize Although a display made up of OFA control function that corresponds button and paddle switches). discrete LEDs may seem a little low to the labeled LED. tech compared with an LCD panel, Auto-scan mode is designed to har- SUI INSIDE it’s much easier to follow the scanning ness a single physical action, but it I tried to keep the circuitry as sequence when all the labeled selections requires a certain amount of coordina- simple as possible. The only frills in are visible at once. Scrolling across a tion to manage the auto-scan timing. the bare-bones circuit of Figure 1 are a two- or four-line LCD to read multiple In step-scan mode, one switch con- couple of setup DIP switches. selections can get quite tiring after a trols the scan and a second performs Aside from the PIC , while. An LED array, of course, becomes the select function. The scan is incre- I used some easily available common less practical as the number of selections mented one step at a time with each parts. The PIC16C84 was an interesting increases. activation of the scan switch. choice, considering I had absolutely Four Port B lines (RB0–RB3) and two The user reaches a desired selection, no experience with Microchip’s product Port A lines (RA0, RA1) are multiplexed at his or her own speed, by alternating line. None of the microcontrollers I by a 74HC42 decoder and a 74HC4051 between scan and select switches. This was familiar with seemed particularly analog switch to sink 10 LED rows and provides greater control for those who suitable for this application, so I decided source four LED columns. Switches have difficulty anticipating the timing to try something new. S1 and S2 of the four-position DIP of the auto-scan sequence. Step-scan is Aside from all the good things I’d switch (SW1) are read through pins ideally suited for a sip-and-puff (pres- heard about the 8-bit devices, I’m RA2 and RA3 at powerup. The con- sure/vacuum) dual-action input switch. somewhat of a coward when it comes figuration of these switches puts the

A Power on Colstart: LEDs off Initialize vars. 2 tone beep for read DIP switch start of colscan timer = autoscan or stepscan

Ready: Colset: Ye s Colscan: 2 tone beep reset for return last col to rowscan in scan? Rowset: No reset row/col Colscan: for new scan light LED beep increment col No B Ye s Start: No Timeout start scan count = 6 s? Shutdown input? Ye sSmode2? N o timer = stepmode Ye s Ye s Smode2 No Ye s Rowscan: input for col last row scan? Ye s Auto2: No in scan? No No input to Timer = count select? to autoscan? No Smode2 No Timeout: Ye s Rowscan: input to count = 6 s? shutdown Ye s light LED, beep select increment row Ye s

Ye s Smode1? No timer = stepmode Select: Ye s beep, lookup OFA Smode1 control byte input for row scan? No No No Auto1 No Ye s input to start Timer = count Serial: to autoscan? No Ye s col scan? serial output Smode1 Timeout to one-for-all input to start count = 6 s? Shutdown col scan? Ye s

Ye s Ye s Wakeup: Serial byte = W? add K to wakeup sequence No A B

Figure 2—The SUI software begins with an initialization sequence and then waits for an input to start the scan down the rows. If the first step-scan or auto-scan mode input routines detect a select input, the program execution is passed to the column-scan segment. The column-scan input routines are similar, but a select input in either auto2 or smode2 results in serial-control commands being sent out to the OFA.

14 Issue 100 November 1998 Circuit Cellar INK® SUI into auto-scan or It turned out that the step-scan mode and sets wheelchair sip-and-puff one of three auto-scan controller could be cycled speeds. between drive functions, During scanning, RB7 seat adjustments, and outputs a PWM audio several auxiliary relay out- signal to a tiny piezo puts. A short connecting transducer through a cable between the SUI and simple on/off/attenuator two of the relay outputs circuit consisting of a eliminated the need for an resistor and switches S3 additional switch. and S4 of SW1. The audi- Optional control outputs tory feedback beep is aren’t necessarily common enabled or disabled by S3, to all powered chairs, so an and two volume levels additional input device is are provided by S4. still required in some cases. The OFA serial control The schematic for a proto- data, output on pin RB6, Photo 1—The scanning user interface, prototype sip-and-puff switch, and One-For-All 8 type sip-and-puff switch and the DC supply volt- infrared remote (not shown) are the basic components for an accessible mini environmental- using two Micro Pneumatic age are routed out to the control system. Logic (MPL) dual-port OFA through a 3.5-mm pressure switches appears stereo phone jack. The tip lead on the auto-scan input at the bottom right of Figure 1. The PIC detects scan-and-select user jack is connected to the LDO regulator- Pressure and vacuum sensing was input through RB4 and RB5, respec- enable line. When the tip-to-ground obtained by simply teeing the air- tively. Each I/O line is connected to connection is initially made, the PIC supply tube to the input port of the the tip contact on separate 3.5-mm software latches the regulator-enable puff switch and to the output port of stereo jacks. line low, through pin RA4 and the the sip switch. The MPL 501s have This setup enables the connection PNP/NPN transistor combination. diaphragm-operated contacts that of individual off-the-shelf ability Once powered, further tip-to-ground respond to pressures ranging from 0.1″ switches, which typically come with contact doesn’t affect the regulator to 0.75″ of water. 3.5-mm mono plugs attached. Addi- but is seen as valid auto/scan input by A very small amount of the sensi- tional in-line diodes and grounded RB4. If no user activity is detected on tivity can be adjusted with a setscrew Schottky diodes provide a measure of RB4 within approximately 6 s, the that changes the contact spacing. I ESD and negative-voltage protection on software sets RA4 high and shuts down found these switches to be a little too all I/O lines connected to external jacks. the regulator to help minimize power sensitive, so I’d probably try a higher The three conductor-input jacks and consumption. rating for any future applications. The jumper JP1 provide several control- The 6-V supply is slightly reduced pressure-switch terminals are wired switch options for other potential by a polarity-protection diode installed with a common ground to a single applications. By jumpering the RB5 on the ground terminal of the DC power three-conductor cable with a 3.5-mm select line over to the ring contact on jack. The LDO regulator handles the stereo plug attached. the auto-scan input jack, a dual-action lowered input voltage quite nicely and As luck would have it, I was able sip-and-puff switch can be connected supplies 5 V to the circuit. to get power for the SUI from an aux- to the SUI via a single three-wire cable. The supply voltage is passed straight iliary outlet on the wheelchair that JP1 can also route the supply voltage through to the OFA, so the input should was clearly intended for some other out through the ring contacts on each never exceed 7 V. The SUI and OFA type of accessory. I contacted the local jack. This aspect comes in handy when combination draws a maximum of dealer’s service department and obtained you need to use more specialized input- ~55 mA when the OFA transmits an all the necessary technical details switch devices that require power for infrared command. before attempting the SUI connection. optical or magnetic sensor arrange- The output was well isolated from ments. SUI ONBOARD the rest of the controller circuitry and Although I didn’t use this particular Although my friend has good head provided a clean 6 VDC at 750 mA. Like feature in my prototype, I recommend movement and slight control of his the auxiliary control relays, some wheel- using a resistor or a resettable fuse on fingers, he prefers to use a sip-and-puff chairs may have a similar power option the voltage supply line to the header. interface to operate his electric wheel- and some may not. An alternative solu- Some kind of protective device is a good chair and access his home computer. I tion is to tap the wheelchair batteries idea in case a mono plug is accidentally made the mistake of building a sip-and- directly with a small DC-to-DC con- inserted into the stereo jack, connecting puff switch for his SUI before I looked verter that isolates the SUI and OFA the power supply to ground. at the electronics on his wheelchair. from any motor-generated transients.

16 Issue 100 November 1998 Circuit Cellar INK® BACK TO BASICS As this was my first PIC project, I wasn’t keen on spending too much GND time or money on software develop- Rx ment. I needed something to get me up and running as quickly as possible, so I ended up purchasing the PicBasic Compiler and Epic Programmer from + – microEngineering Labs. – + PicBasic commands are quite power- ful, and it doesn’t take long to string a + – few together to get things going. But- ton, Sound, Pins, and Serial are just – + a few examples of I/O commands that +V handle input, audio feedback, display IN control, and serial communications for the SUI program. Typically, a pin assignment and a Figure 3—Removal of the OFA8 battery cover reveals the contact points for the installation of the SUI con- couple parameters for each command necting cable. are all you need. Although Port B pins are the only ones supported by these is tested and the program branches to PicBasic commands, Port A pins can the step-mode input routine or contin- be accessed with Peek and Poke calls. ues in auto-scan mode. The program code, like the hardware, The auto-scan 1 input routine polls is fairly straightforward. As you see in RB4 again, but this time the loop-pass Figure 2, there are four basic program counter limit is set by the Timer vari- segments—initialization, row scan, able. If no input is detected before the column scan, and serial output. The count reaches Timer, the program program starts by setting all the vari- jumps back, increments the scan, and ables and I/O ports, which effectively returns to the input loop. turns off the LED display and enables Without input, this cycle continues, the regulator through pin RA4. resulting in an automatic scanning Port A is read to obtain one of four sequence down the left column, with values for the DIP-switch settings on the Timer value setting the speed. Any RA2 and RA3. This value is adjusted input during the scanning process is and assigned to the Timer variable. seen as a Row selection, and program Three values determine the auto-scan execution is passed over to the column- speed. The fourth sets a branch condi- scan routines. When the last row is tion further on in the program, which reached, the program goes back, resets runs the step-mode rather than the the display variables, and waits for auto-scan input routine. another start-row-scan signal. After the initialization, a dual-tone The step-mode 1 input routine beep signals the SUI is ready for input. polls RB4 to increment the scan and The Row and Column display control then RB5 to select a row. If input is variables are reset for a new scan detected on RB4, the program jumps sequence. An input loop polls RB4 for back, advances the scan, and returns a start-row-scan signal while increment- to the input loop. If no input occurs ing a loop-pass counter. If no input is on RB4, then RB5 is polled for a Row detected before the counter reaches a select condition. If no input is detected timeout limit (~6 s), pin RA4 is set on either pin, the loop repeats until high and the regulator is shut down. the 6-s timeout counter eventually If input is detected, the Row and shuts down the regulator. Column values are output on Ports A If a Row selection is detected in and B, lighting the LED in the first row auto-scan 1 or step-scan 1, the scan- of the first column. A corresponding ning sequence is temporarily halted, beep is generated, and the Row variable the program jumps to the column- is incremented in advance for the next scan handling routines, and a dual- pass. At this point, the Timer variable tone beep signals the change.

Circuit Cellar INK® Issue 100 November 1998 17 The code structure is essentially OFA WAKE-UP CALL rity system, a door actuator, and his the same for column scanning as it is Before the SUI can send over com- home entertainment system. Even for rows. This time, however, it’s the mands, the OFA8 must be initialized with the added cost of various X-10 Column variable that gets incremented, for serial communications. First, one accessories, he still had enough left resulting in a left-to-right scan sequence of the OFA8 keypad buttons must be over to take me out for coffee. across a selected row. manually pressed to bring the OFA8 Unfortunately, that’s when he gave When the last column in a row is micro out of sleep mode for about 5 s. me his list of suggestions for Version 2. reached, the program resets the vari- The SUI is then activated and the Hmm…let’s see: telephone control, ables and returns to the row-scanning Wake function is selected before the EEG interface, robotic assistant…? I sequence down the left column. The micro goes back to sleep. This serial auto2 and step-scan2 input rou- wake-up command suspends the OFA Dan Leland has spent the past 11 years tines poll RB4 and RB5, but instead of sleep-mode routine and keeps the OFA working in research and development redirecting the scan, the input in- in serial mode. The OFA8 returns to for the Neil Squire Foundation, a vokes the OFA serial control routines. manual mode if the power is removed, Canadian nonprofit organization A beep indicates an OFA control so this procedure must be done the whose goal is to provide innovative selection has occurred. The program first time the unit is powered up or services and technology to individuals derives a value of 0–39 from the current after any power interruptions. with significant physical disabilities. Row and Column variables and assigns The SUI auto-power-down feature For more information on some of the it to the variable Key. A look-up com- helps offset the fact that the OFA is Foundation’s activities, please visit mand uses Key as an index variable to always on in serial mode. The manual www.neilsquire.ca. You may reach retrieve a value from a table of 40 keypad press in this set-up sequence Dan at [email protected]. numeric constants. Each constant in is a bit of a drag, but it’s specific to the list corresponds to an OFA serial only four OFA models that I know of, SOURCES button command. including the OFA8. PIC16C84 The serial-out subroutine sends the The older OFA12 and OFA6 can be Microchip Technology, Inc. ASCII-character equivalent of the byte switched to serial-control mode with (602) 786-7200 constant out to the OFA. If the byte just a serial wake-up command, and Fax: (602) 899-9210 equals an ASCII “W”, the OFA wake- they don’t require the physical button www.microchip.com up routine kicks in and sends a “K” to press. Unfortunately, the OFA12 is complete the wake-up sequence that discontinued and the OFA6 lacked the MPL501 pressure switches puts the OFA in serial-command mode. program capacity for my friend’s appli- Micro Pneumatic Logic, Inc. The program returns to the last cation. The OFA6 is still readily avail- (954) 973-6166 input routines and checks for further able and probably meets the needs of Fax: (954) 973-6339 selections, which enables consecutive most people. www.pressureswitch.com button presses for repeating functions With the OFA in serial mode, the One-For-All 8 like volume up. If no further input is SUI can send over serial-control com- Universal Electronics, Inc. detected, the program eventually returns mands corresponding to any of the (330) 487-1110 to a point where a timeout routine OFA button functions. By following Fax: (330) 487-1131 powers the SUI off. the instructions outlined in the One- www.ueic.com For-All 8 user guide and code book, THE OFA CONNECTION you can access all the features of the PicBasic compiler software, EPIC The One-For-All 8 remote I used in OFA through the SUI. programmer this application is connected to the If the user needs help with the OFA microEngineering Labs, Inc. SUI with a 36″ audio patch cable with setup procedure, manufacturer codes (719) 520-5323 molded 3.5-mm stereo phone plugs on or macro sequences can be entered Fax: (719) 520-1867 each end. One of the plugs is removed manually anytime after the OFA is www.melabs.com and the leads are soldered to the three powered on and before the SUI sends X-10 control accessories points located beneath the OFA battery the wake-up signal. The OFA retains X-10 USA compartment (see Figure 3). programmed information even if the (800) 675-3044 With reference to the stereo-plug power supply is temporarily removed. (201) 784-9700 contacts, the tip lead is soldered to the Fax: (201) 784-9464 +V battery spring contact, the ring SUM OF THE PARTS in www.X-10.com lead is soldered to the Rx pin, and the So, how much accessibility does ground lead is soldered to the GND $75 worth of parts buy? In my friend’s Home Automation Systems, Inc. pin. Finally, the side of the battery case, a fair amount. (800) 762-7846 cover is notched to accommodate the From his wheelchair, he now has (949) 221-9200 cable, and it is then snapped back into control over ten lights, two sets of Fax: (949) 221-9240 place. drapes, a ceiling fan, thermostat, secu- www.smarthome.com

Circuit Cellar INK® Issue 100 November 1998 19 cremental encoder) to generate a sinu- soidal commutation waveform. FEATURE Software-based commutation also performs advanced functions like auto- ARTICLE matic phase finding and waveform shaping. These two techniques let you eliminate Hall-effect sensors and also permit the motor performance to be Chuck Lewin improved by linearizing the commuta- tion output tuned to a specific motor. In this article, I explore the capabili- ties and benefits of software-based sinusoidal commutation and show how it can be used in applications involving Motor Commutation brushless motors. I also examine some other commutation schemes and offer practical guidelines on which scheme Techniques works best in a given application. SINUSOIDAL COMMUTATION The term “sinusoidal commutation” refers to the waveform of the motor currents used to drive the brushless motor windings. Figure 1 illustrates these waveforms for two commutation phasings—a 120° phasing scheme used with three-phase brushless motors and achine designers a 90° phasing scheme used with two- m have long sought to phase brushless motors. It’s a never-ending get the maximum Sinusoidal commutation has performance from their gained popularity lately because it has race to get the most systems. But as they push throughput the potential to operate a given motor to the limit, they often fight a battle more smoothly. It also offers more performance from with motion-stability problems like predictable behavior than the same torque ripple, oscillation, or overshoot. motor commutated using traditional your system. But, Motor commutation is an important six-step techniques. weapon in this battle. Recently, there Although sinusoidal commutation according to Chuck, has been an increase in the number of has been used in a wide variety of applications using software-based applications, it’s especially popular in motor commutation commutation performed by high-speed systems that are sensitive to torque DSP chips. By doing commutation in disturbances. Linear motors and other is a good springboard software, it’s possible to improve the direct-drive brushless applications fall motion’s smoothness and accuracy. It into this category, as do applications for flying over the may also reduce the audible noise like medical automation, semiconduc- level of the motor during operation. hurdles of oscillations, Historically, commutation was a) Phase A Phase B Phase C performed using hardware-based Hall- overshoot, and all effect sensors. This scheme requires 120˚ commutation sensors in the motor, as

those other motor- well as electronics in the motor ampli- b) Phase A Phase B fier, to perform the phasing.

stability problems. By taking advantage of the power 90˚ and flexibility of software-based sys-

tems, it becomes possible to perform 90˚ 180˚ 270˚ 360˚ commutation functions in the con- Figure 1a—Commutation waveforms for three-phase troller’s CPU. This software-based permanent magnet brushless motors are separated by method uses the position feedback 120°. b—Waveforms for two-phase brushless motors device of the motor (typically an in- are separated by 90°.

20 Issue 100 November 1998 Circuit Cellar INK® tor automation, scientific Motor output These amplifiers may be (PWM or Analog ±10 V) instruments, and analytical Motor command register located on the board or in a Phase A equipment, among others. command separate amplifier. This tech- MTR_OFF Phase B To amplifier nique is used without a current- command MOTOR-OUTPUT Target postion MTR_ON loop circuit, so that the motor and velocity Phase C SIGNAL GENERATION (from profile command is controlled in voltage mode. generator) Servo filter In a digital sinusoidal (PID or PIVff) commutation scheme, the Actual position PHASE INITIALIZATION motor-output signal is An important question Actual position calculated from the posi- (from encoder) concerning the adoption of tion encoder as well as software-based sinusoidal from information about Figure 2—Here’s the control flow for a typical commutating digital controller. The commutation is how the mo- the initial phasing of the torque command is provided manually (motor command register) or by position servo tor phases are initialized after (PID). Then, the torque command is vectorized into A, B, and C commands and set motor windings. The out- to the amplifier using encoder feedback to determine the phase angle. powerup. Position feedback is put signal to each winding usually provided by an incre- is determined digitally by synthesizing encoder counts per electrical cycle, and mental encoder. On powerup, a sinusoidal waveform and combining init_phase is the initial phase angle no absolute information is available it with the overall desired torque out- offset in encoder counts. concerning the correct motor phasing. put of the servo filter. This situation presents a serious Figure 2 shows the control flow for MAKING CONNECTIONS challenge to the universal adoption of a typical digital controller that synthe- Figure 3a shows typical connections encoder-based sinusoidal commutation. sizes the sinusoidal waveforms using for an all-digital sinusoidal commuta- To address this challenge, most digital an internal ROM look-up technique. tion controller, like those available from controllers support two distinct phase Typical digital commutation motion-card vendors. The digital con- initialization schemes—the first using schemes read the encoder position on troller provides two analog output no hardware sensors at all other than a discrete time-sampled basis and signals (using a DAC): phase A and B. the encoder itself, and the second using determine a new motor output value An amplifier circuit (on the same the Hall-effect sensors—in conjunction for each of the three brushless motor PC board or on a separate board) gen- with the encoder. phases. State-of-the-art systems per- erates the phase C signal using the form commutation waveform lookup equation C = –(A + B). This amplifica- ALGORITHMIC INITIALIZATION at least at 10 kHz, and many perform tion technique is used with a current- The first method, often called algo- at 15+ kHz. For high-speed applications, loop scheme that converts the analog rithmic initialization, performs a short such as spindle motors running at voltages output by the motion processor phase excitation procedure that applies 30,000+ rpm, accurate high-frequency into torque commands to the motor. power to the motor windings and waveform synthesis is a must. Figure 3b shows a digital controller observes the motor response. Based on Given the current shaft angle (en- using a direct PWM output technique the settling position of the motor, the coder position) and initial phasing of so three output signals (phase A, B, and correct commutation can be determined. the motor (which locates the shaft to C) are provided. These signals are sent This technique provides accurate results the proper electromagnetic position), directly to H-bridge-type amplifiers to and doesn’t require separate commu- you can calculate the desired current drive the motors. tation sensors like Hall-effect sensors. in each motor coil for a phase angle for three-phase brushless motor via:

a) Analog-input amplifier

phase_A_angle = (Encoder – init_phase Phase A 1 Phase A Axis 1 Axis 1 × 360 Phase B Axis 1 Motor 1 % n_counts) n_counts Phase B 1 C = A – B Motion Phase C Axis 1 phase_B_angle = phase_A_angle – 120 Figure 3a—A controller with controller Phase A 2 Phase A Axis 1 phase_C_angle = phase_A_angle – 240 onboard commutation in analog Axis 2 Motor 2 output mode sends two phase Phase B 2 C = A – B Phase B Axis 1 signals (A and B) to the amplifier. Phase C Axis 1 and the value output on each phase The amplifier constructs the third signal is: phase (C) using the current loop to ensure that the sum of the phases is b) PWM-input amplifier × 0. b—A controller with onboard phase_A_output = sin(phase_A_angle) torque Phase A Axis 1 commutation in PWM output mode phase_B_output = sin(phase_B_angle) × torque Phase B Axis 1 sends three phase signals (A, B, and Motor 1 phase_C_output = sin(phase_C_angle) × torque Phase C Axis 1 C) to the amplifier. Each signal drives Motion controller Phase A Axis 1 where Encoder is the current encoder the amplifier’s half bridges directly. With PWM input, the amplifier Phase B Axis 1 Motor 2 location in counts, % is the modulo usually runs in voltage mode and Phase C Axis 1 operator, n_counts is the number of doesn’t perform a current loop.

Circuit Cellar INK® Issue 100 November 1998 21 Hall-based commutation not only the type of motor, as by each physical Phase A because of the elimination of torque manufactured motor. So, it’s important discontinuities but also because the to understand the torque variations

mtr_cmd motor torque resulting from sinusoidal over a sample of specific motors to Power level Power commutation is more linear than the develop an optimum average waveform. Time torque resulting from six-step. Also, the torque ripple magnitude Phase B The sinusoidal waveform more and characteristics may not be propor- closely matches the optimum wave- tional to the commanded motor torque

Power level Power form required by the motor to create level. As an effect, a compensating perfectly linear torque output. waveform, which is optimal for one Time But, motors specifically purchased motor torque level, may not be optimal Figure 4—This typical excitation sequence of motor to be commutated using sinusoidal at a lower or higher level. windings to determine initial phasing uses algorithmic commutation do not create perfectly Detent torque is an example of such techniques. The phase-A current increases, holds, and linear torque output. Figure 5 shows nonlinearity. Detent torque is a torque falls off. Current B goes through the same sequence. typical torque output for a motor that disturbance found in some types of The rotor angle just before the phase-B current angle determines phasing. is commutated using sinusoidal com- brushless PM motors. It results from mutation at a fixed torque level. the magnetic attraction of the magnets The disadvantage is that, while As the graph indicates, the actual in the rotor to the stator at specific power is being applied, the motor torque output deviates from linear by rotation points. bumps uncontrollably. And if the load 5–10%. This deviation represents the Detent torque is typically not pro- friction is high or even against a hard torque ripple that can be expected from portional to the commanded motor stop, the procedure does not operate sinusoidal commutation. Six-step torque operating level, so it can’t be correctly at all. But, most software- commutation torque ripple tends to completely removed this way. How- based controllers recognize this condi- be in the 10–15% range. ever, it may be possible to lower detent tion because the motor does not move. Waveform shaping is occasionally torque by modifying the waveform in Figure 4 shows a phase excitation used when the motor characteristics other ways—for example, a fixed output sequence used with algorithmic phase are consistent and well understood offset for each motor position. initialization. More complicated se- and when this torque ripple is not quences that try to minimize the acceptable. The basic technique is to OTHER COMMUTATION CHOICES motor movement may be adopted, but transform the sinusoidal waveform by Sinusoidal commutation as a these techniques require the motor to multiplying by a compensating torque method for driving brushless DC move at least a small distance. magnitude, thereby linearizing the motors has been gaining popularity in Algorithmic initialization techniques resultant torque output. Figure 6 recent years because it offers smoother that don’t require the motor to move shows this, dramatically exaggerating motion with no discontinuities in the at all have been explored but are not the magnitude of the correction. power applied to the motor. yet in common use. These techniques Although this technique is appealing Several other commutation tech- typically attempt to measure the main and easy to implement, it has several niques are commonly used, each with vector angle axis of the inducted limitations. First, the torque response a particular domain of applicability. winding voltage when excited via a of a given motor may vary as much by Understanding the strengths and fixed frequency of all three windings.

HALL-BASED INITIALIZATION Method Advantages Disadvantages In the second phase-initialization Hall-effect six step Widely used Not as smooth because of method, three Hall-effect sensor signals discontinuous application of for each axis are connected directly to power through each motor coil the digital controller and are used just Digitally synthesized sinusoidal Smooth motion; Hall sensors required with Hall-based initialization high performance during phase initialization. Digitally synthesized sinusoidal No sensors beyond Motor movement during phase The advantage is that the motor with algorithmic initialization encoder required initialization phasing can be determined from the Resolver-based sinusoidal Commutation circuitry In typical applications, resolvers moment the motor is powered on. is fairly simple and associated R/D circuit is more expensive than the incre- Once the Hall-sensor information has mental encoder been collected during initialization, Linear Hall-based sinusoidal Commutation circuitry Output of Hall sensors is not only the encoder is used and the motor is fairly simple truly sinusoidal; not commonly is commutated sinusoidally. available Sensorless (back-EMF) Very low cost; no Will not work at DC; not appro- sensors required priate for positioning applications WAVEFORM SHAPING Sinusoidal commutation is generally Table 1—A third method (internal to the motor) also uses Hall sensors but simply packages them on a small circuit an improvement on square-wave or board mounted inside the motor.

22 Issue 100 November 1998 Circuit Cellar INK® weaknesses of each scheme enables designers to optimize their choice of commutation techniques.

HALL-BASED COMMUTATION output Torque Hall-based (a.k.a. trapezoidal or six-step) commutation is the most 0˚ 90˚ 180˚ 270˚ 360˚ Phase angle common method of commutating brushless motors in positioning appli- Figure 5—Even if perfect sine-wave current commands cations. Figure 7 shows the relationship are sent to each motor phase, the motor’s torque output may not be linear. The output may be distorted by the of typical Hall-sensor signals to the geometry, mechanics, and materials of the motor. resulting current flow through each motor coil. The advantages of this technique Each Hall sensor outputs a binary are that it is cost effective and accurate. high or low value, switched every 180 Additionally, the resolver requires no electrical degrees. The three Hall phase-initialization procedure. sensors may be phased relative to each Its disadvantages are that it is not other in various ways, but in all cases, fully digital and it depends on analog the sensors encode six unique states circuitry, which may drift over. As well, per electrical cycle with a resulting off-the-shelf resolvers and their asso- drive waveform as shown in Figure 7. ciated R/D converter chips are expen- The advantage of this scheme is its sive compared with an incremental popularity, as well as its low cost and encoder of comparable resolution. ability to operate from DC (motor stand- still). A disadvantage is the discontinu- LINEAR HALL SENSORS ous current applied through each coil. Another technique uses special Hall At the Hall switching points, position- sensors that provide three sinusoidal ing systems may experience servo output signals that can be used to phase instability or torque discontinuities the motor command using analog because of the abrupt changes in the multiplier circuits. The technique power applied to each motor coil. that generates the final motor com- mands through each coil is identical RESOLVER-BASED COMMUTATION to resolver-based feedback. Resolvers provide sinusoidal infor- This technique has the advantage mation about a motor’s shaft position that it does not require an initializa- which is electronically extrapolated tion procedure. On the other hand, using an IC known as an R/D (resolver the analog waveforms output by the to digital) converter to generate a digital Hall sensors are seldom truly sinusoi- representation of the motor shaft angle. dal. This situation may distort the One benefit of the sinusoidal signal torque applied to each coil, resulting output by a resolver is that it can be in increased motor ripple. Also, these used to commutate the motor. An sensors are not commonly available analog-multiplier IC generates three for most motors. phased signals by electronically multi- plying the unphased torque signal from SENSORLESS COMMUTATION the controller with the three phased Sensorless commutation techniques resolver feedback signals. This technique use information generated by the motor is nearly identical to the all-digital during operation to determine motor one except that it’s performed in analog. phasing. The most common signal is

90˚ a)90˚ M0 b) Figure 6a—A pure sinusoidal waveform has M constant magnitude over the entire commuta- tion electrical cycle, so that M equals M0 at all 180˚ 0˚ 180˚ 0˚ times. b—The shaped waveform has variable magnitude so M does not equal M0 at all phase angles. The oval modification is shown

270˚ 270˚ here. More complicated modifications may be required based on motor behavior.

24 Issue 100 November 1998 Circuit Cellar INK® spindle control and fan control. For That depends on many factors that Phase A Phase B Phase C these applications, try a low-cost IC only you can judge. I that implements sensorless control. Chuck Lewin is chief technology officer IT’S YOUR CHOICE of Performance Motion Devices. He has been working in motion control Hall A I examined the characteristics of a Hall B for eight years and designing DSP- Hall C software-based implementation of based motion systems for five years. sinusoidal commutation. Because of He has written articles for various the broad applicability of sinusoidal 90˚ 180˚ 270˚ 360˚ engineering magazines, providing commutation to brushless PM motors, practical, application-oriented advice Figure 7—The typical phase excitation sequence for it has substantial merit for high-per- on the implementation of motion- Hall effect–based commutation is shown here in six formance motion systems. steps. Three Hall sensors determine the phase output control systems. You may reach Given lowering electronics prices, at any given phase angle. Chuck at [email protected]. the cost of sinusoidal commutation back-EMF voltage, which is created in for systems that already use a position the coil as the permanent magnet of the encoder has become about the same SOURCES brushless DC motors rotates past it. as for less advanced six-step schemes. MC1231A Presently, sensorless commutation Despite the strengths of software- Performance Motion Devices, Inc. techniques can only be used when the based sinusoidal commutation, there (781) 674-9860 brushless motor is rotating, and are several alternative schemes that Fax: (781) 674-9861 therein lies its greatest limitation. are worth considering. For a given www.pmdcorp.com This technique cannot be used for application, system cost, desired per- positioning applications because the formance, and sensitivity to distur- 5651 motion-control card commutation information disappears bances, among other factors, play an Technology 80, Inc. at DC when the motor stops moving. important role. Table 1 summarizes (800) 545-2980 However, it requires no sensors of the techniques I discussed. (612) 542-9545 any kind and is commonly used in high- Which commutation technique Fax: (612) 542-9785 volume applications like disk-drive will work best in your application? www.tech80.com

Circuit Cellar INK® Issue 100 November 1998 25 But, adding a 32- or 64-bit micro would drive the price out of range for the FEATURE consumer market. So “intelligent” devices continue to be unintelligent, ARTICLE and we run to the sprinkler controller whenever it rains. But what if you could connect a simple device to dynamic information Chris Sontag without adding resources to the device? A sprinkler controller that monitors environmental conditions or forecast information and changes its actions Web-Implemented based on that information would save money and be politically correct. The device would be educated with updated Irrigation System information, making it truly intelligent. INTELLIGENT ARCHITECTURE To make a sprinkler system intelli- gent, you need three things. You need an interface to enable easy access and control of the device from anywhere. You also require a way to gather ou’re driving in and analyze current environmental y a rainstorm that’s conditions as well as a decision-mak- Tired of relying on been going all day and ing process to adjust the device based pass a house or business on current information. Also, a solu- the weatherman in with its automatic sprinklers watering tion based on Internet standards makes the lawn. So much for water conser- the interface user friendly and easy for this El Niño year? vation (a perennial topic of discussion the device manufacturer to implement. during non-El Niño years in the arid Using emWare’s EMIT (Embedded Chris is, too. After desert climes of the Western U.S.). Micro Internetworking Technology) No doubt, the building’s owner set software, I can put an intelligent system seeing all those the automatic sprinkler timer to start into place. EMIT includes five modular watering the lawn on a preset schedule, software components: automatic sprinklers and the microcontroller in the sprinkler control unit obediently turned the • emMicro, a compact, special-purpose working in the rain, sprinklers on—rain or shine. The owner micro web server that requires less is either too far away to change the than 1 KB of device memory he decided to hook device or the process of changing the • emNet, a message-based protocol program at the device is too complex. that combines packet and stream up a controller to the Somewhere along the line, we interchange started calling even the simplest elec- • Microtags, preprogrammed packets ’Net for live updates, tronic devices “intelligent.” But if that define device controls (e.g., electronic devices are really intelligent, switches, buttons, LEDs) making this device why do they water the lawn when it’s • emGateway, which expands Micro- raining? These devices are only as smart tags into their full parameters truly intelligent. as the information they’re given. • emObjects, a library of JavaBean A truly intelligent device should components consisting of visual and accept dynamic information and make utility objects adjustments based on that information. It may even take forecast information These components work together to and weigh decisions based on what is create a dynamic user interface without likely to happen in the future. requiring extensive resources from the You might argue that this ability device itself. Figure 1 shows how takes far too much capacity to build these components work together. into simple devices like a sprinkler EMIT software is placed in three timer with an 8-bit microcontroller. areas—on the device, in a gateway

26 Issue 100 November 1998 Circuit Cellar INK® browser, and at a user the device. But for this interface. The device is emGateway Web Browser example, you can mini- HTTP Requests embedded with emMicro, HTTP Server HTTP Client mize device requirements

Microtags, and emNet, as emObjects Internet to reduce expenses. emWare-Enabled (served if not well as variables, functions, emObjects Device installed on the *Dynamic events, and documents. Device browser Expansion Control ADDING SMARTS Application Process & The user interface is a Device Access Display The EMIT components Service standard web browser, Functions JavaScript enable control of the Events Java Run-time enabling access via a Java- Variables Device Link system through a GUI Interface enabled GUI. The browser Documents Module from anywhere at any RS-232 communicates with the Microtags *Future Implementation time. Now we need to gateway, which sends emNet add information to educate emNet Device Access Libary RS-232 Optional access to the Device information to and pulls Device 1 the device regularly, allow- RS485 Access Service from C, command- information from the device. Device 2 line, or custom network applications ing the sprinkler system Device 3 Ethernet Between them lies the Device n Etc. to water proportionally— key to networking small less in the spring and more Figure 1—The EMIT distributed architecture moves the majority of resources away from the devices to the Internet. in the heat of summer. device, providing full Internet networking for devices with microcontrollers as small as 8 and Using emGateway mini- 16 bits. The flexible architecture, with emGateway as the key, meets a variety of solutions Because the device has mizes resource require- and implementation needs. Internet connectivity ments at the device by built in, it can check the moving the workload to the client from off to on. The browser then in- National Weather Service’s web site side of the equation. vokes emGateway, which sends the for precipitation information and When a user requests the device request to emMicro at the device. forecasts. For more accurate informa- interface from a web browser, the When emMicro receives the request, tion, you can connect the system to browser sends the request to emGate- it causes the device’s microcontroller temperature sensors, moisture probes, way, which translates the high-level to flip the valve switch. Because device and wind monitors at the property. request and sends it to emMicro at information has changed, the state of Using the forecasts, you can program the device. emGateway receives infor- the embedded device changes, so a state- the device to water in the early morning mation through the Microtags built into change message is sent to any interface hours of hot, dry days, providing the the device, and substitutes each Micro- emObject (component) monitoring necessary moisture to the lawn and tag with a corresponding emObject. affected variables. The interface now avoiding heavy evaporation that comes emObjects are JPEG or GIF images shows the valve state as on. from watering in the heat of the day. or Java applets that represent device In addition to the 1-KB emMicro On days with rain in the forecast, the controls to the browser. The page with web server, this application is about sprinklers could automatically shut off. the substituted emObjects is then sent 900 bytes. If you have to build physical When your computer is off or the to the browser. interface logic onto the device (LCD, sprinkler system is unable to access EMIT components process user buttons, switches, etc.), you need the Internet or weather-station infor- requests to view and set device infor- another 2–4 KB of program space. mation, the system simply defaults to mation, dynamically representing the For applications on devices with its regular schedule or to user input. results on the desktop. For example, larger processor capacity, the emGate- You can even program the device users may ask to turn a sprinkler valve way requirements can be moved to to weigh current data (temperature, humidity, rainfall, etc.) against fore- Listing 1—This code is part of the applet’s definition of notifyChange, which is called whenever a casts. For example, if the day is hot variable is changed at the interface, showing the interactivity between the device and the interface. and dry, but the forecast calls for a heavy storm at night, the device can public void notifyChange(String variable, Object value){ postpone watering and let the coming if(variable.equals("Sec")){ storm take care of the lawn. On days seconds = ((Integer)value).intValue(); timeDisplay.setSeconds(seconds); when the predictions are wrong, you } simply call up the sprinkler interface else if(variable.equals("Hrs")){ and reset the sprinklers. hours = ((Integer)value).intValue(); The sprinkler interface allows for set_hours(); } customized usage in other ways. For else if(variable.equals("Min")){ example, you can turn off the system minutes = ((Integer)value).intValue(); for a few hours to accommodate an timeDisplay.setMinutes(minutes); unexpected thunderstorm or turn the } } system on if an expected storm fizzles out. On the other hand, if you’re away from home (or forgetful), the sprinkler

Circuit Cellar INK® Issue 100 November 1998 27 device is intelligent enough to turn back interface on the device itself. Some The clock has two main software on to a preset schedule after an allotted sprinkler controls seem to require a components—an interrupt-service time without receiving any data input. college course just to get your lawn routine (ISR) and the clock routine. watered at the right time. The 8051’s hardware timer 0 executes PUTTING THE PIECES TOGETHER A serial EEPROM device stores the ISR once every 10 ms. The ISR Everything sounds good in theory. interface documents and program must reset the hardware timer for the But what about putting this smart times in a nonvolatile array to ensure next interrupt and account for inter- device in place? that the device retains essential infor- rupt latency, which would cause the In addition to about $20 worth of mation if it loses power. A 9-V battery clock to drift off. garden-variety sprinkler components, serves as a power backup to keep the Unfortunately, the 8051 architecture I used an AT89C2051 microcontroller. clock running during a power failure. doesn’t support a 16-bit auto-reload This 20-pin 8051 derivative from Atmel All you need onboard is the micro- mode, which would make it unneces- includes 2 KB of program space. controller and the hardware it needs sary to correct for interrupt latency. I installed an RS-232 transceiver to to turn on 24-V AC devices. I used a This situation isn’t hard to correct. provide external communications. The 74HC138 decoder so eight valves could Because T0LOW (an 8051 special software handles a real-time clock/ be controlled using three lines from the function) is small (zero), there’s no calendar and an alarm clock that se- microcontroller. The schematic provides real possibility of a rollover when the quences throughout the program and for an additional decoder that gives addition is done and, therefore, no manages the watering start times. control for up to 16 valves (see Figure 2). reason to account for a carry into the The emMicro module provides a Figure 3 shows the programming upper portion of the counter. The most remote interface for manually pro- logic. As I mentioned, the real-time important thing the ISR does is set the gramming the system and customizing clock/calendar was implemented bit variable called temMSbit, which watering schedules. One of the beauties completely in software, and it uses tells the real-time clock routine that a of the remote interface is that it can the microcontroller’s 18,432-MHz time tick occurred. be easier to use than the physical crystal as its time base. The clock routine is responsible for counting the ticks created by the ISR. Basically, it just counts hours, minutes, seconds, and days, and it sets a few bits here and there to tell other routines when to operate. For instance, once every minute, the bit variable CheckWater is set. This way, the alarm-clock routine knows to check all the scheduled watering times to see if any are supposed to begin. There are two day counters. One is used for watering schedules based on the day of the week (Mon- day through Friday) and the other handles periodic watering (every other day, every third day, etc.). The counting routine is called by the main calling loop in a round- robin multitasking methodology. It is called much more frequently than the 10-ms rate of the timer ISR, so it is sure not to miss a tick. Whenever the ISR sets temMSbit, the clock routine increments its clock registers as necessary. It then clears temMSbit so it won’t respond more than once to each tick.

PROGRAMMING BRAINS Three main steps were involved Figure 2—The connections made in the emWare sprinkler controller enable external information to control the function of in integrating EMIT software into sprinkler valves. the sprinkler-system application:

28 Issue 100 November 1998 Circuit Cellar INK® • include the emMicro code module include statements or by directly Manual in the application Main Control including the tables. • Calling create the resource tables Loop Valves Placing calls to the emMicro entry • Real-Time insert calls into the entry points of Clock points is straightforward because there emMicro are only two. However, there are some Schedule rules that applications must obey. The first task is usually handled via One entry point is the serial port Valve an include statement placed after Control interrupt vector entry. emMicro has the application code. its own serial ISR, but the vector has Information about the application emMicro to be installed into the microcontrol- is specified for the browser interface ler’s main vector table. The other entry from the resource tables. Creating the Figure 3—The programming logic centers around the is the main emMicro entry (called resource tables is just a matter of edit- main calling loop, which receives information from and emMicroEntry). transmits information to other controlling elements of ing the example tables included with the device. For an application to coexist with EMIT to match the application’s needs. emMicro, the application must be For example, my sprinkler controller Next, EMIT components process written using a cooperative multi- primarily uses the variable table to user requests to view and set device tasking methodology. Each process, make a large number of variables (e.g., information. There are two bytes to including emMicro, is called by a Hrs, Min, and Sec) visible to the web- describe the type of each variable (byte main calling loop, and it must respect browser interface. These tables tie the or word) and whether the variable is all the others by releasing the process browser interface to the microcontroller read-only or read/write. control back to the calling loop in a application. Listing 1 presents a section Finally, variable names are placed timely fashion. of the variable table. into the table in the form of NULL- “Timely,” of course, depends on how The structure of each table is similar. terminated strings. Other tables specify often each process really needs to have The first byte is the number of elements events, functions, static documents, the processor’s attention. emMicro in the table. This sprinkler controller and capabilities. Once these tables are must be called at least often enough uses 37 variables, so the first byte in created, they are included at the end of to receive each character from the the variable table is 37. the application source code either via serial port.

Circuit Cellar INK® Issue 100 November 1998 29 No process should ever stall the the watering on/off image switch. have omitted the NotifyChange processor in a tight loop waiting for This object displays one of two im- callback for Sec by setting a direct some event to happen. That’s what ages depending on its state (active or link between Sec and the emObject interrupts are for. inactive). timeDisplay (see Listing 2). The only other rule is that no process You can establish the connection Since emitjri handled the commu- should get exclusive use of the CPU between the image switch waterOnOff nications requirements, the majority registers. Each process can use them and the embedded variable Water. So, of the coding effort was spent defining without regard to their previous state. whenever an ActionEvent occurs event-handler functions. Whenever a This design has several advantages. (when the switch is pressed and re- button is pressed, text entered, list First, the clock is set from the browser. leased on the interface), the event items selected, checkboxes checked, Not a single line of code in the micro- value (True or False) sets Water. and so on, events are generated. The controller application is occupied with The embedded-controller clock is a event-handling functions for 24-/12-h how the clock is set. Also, all the con- good example of communicating vari- clock, A.M./P.M., and day select are figuration parameters are adjusted able state change to the display applet. characteristic of many event handling without any code in the microcontroller. The embedded variables Hrs, Min, functions that had to be created. Forcing the browser to display new and Sec change regularly, and these Many features were built into the information (or fancy graphics) is as changes need to be relayed to the applet. user interface (see Photo 1) that could easy as changing the value of a variable You may set up the callbacks for not easily be accomplished via hardware in a resource table. If the microcontrol- the embedded variables. Whenever the or by defining the interface completely ler application calls for a special func- variable values change, notifyChange within the embedded controller. The tion to be executed when a button is is called with the variable name and size of the applet increased to approxi- pushed on the browser interface, you the new value. Similarly, we could mately 75 KB, but the controller and only need to write the code for the function. emMicro executes it for you. Listing 2—Events are generated every time an action is taken at the interface (e.g., text entered, boxes checked, items selected). This code describes the event-handling functions for the 24-/12-h clock, A.M./P.M. BUILDING AN INTERFACE selection, and day selection. Little code was needed to interface to the controller, since EMIT provides // select 24-h clock mode prebuilt emObject interface components void hr24RadioButton_Action(Event event) and handles the communication details. { // get value of embedded variable "State" To simplify the task further, I used Object object = emJri.getJSJriVariable("State"); Symantex’s Visual Café and integrated int state; the emObject components with the // disable am/pm buttons existing component toolkit. This way, amRadioButton.enable(false); pmRadioButton.enable(false); I could select the objects from the isClock12 = false; component palette, add them directly state = ((Integer)object).intValue(); to the applet, and easily manipulate /* instead of using a separate variable (wasted resource) to layout and component properties. hold clock mode, set bit 0 of the State variable to indicate 24-h clock mode. */ The heart of the applet is an invisible emJri.setJSJriVariable("State", new Integer(state | 0x0001)); object called emitjri (EMIT Java Run- set_hours(); // update clock time Interface). A new emitjri object } is configured to communicate with // change clock to am this controller, which has a manufac- void amRadioButton_Action(Event event) turer ID of four and a device ID of 11. { All emObjects are passed a reference /* reset embedded variable "Hrs." Device runs in 24-h mode so to the emitjri object. This way, em- subtract 12 from current hour. Since there is a JriLink to this variable, notifyChange will be called and complete the Object events can directly set variables clock update */ on the embedded controller. Changes emJri.setJSJriVariable("Hrs", new Integer(hours-12)); in embedded variables can also change } emObject properties directly. // set current day emitjri also contains function calls void dayChoice_Action(Event event) that enable the applet to directly set { and get embedded variable values, as int day = dayChoice.getSelectedIndex(); well as registering a callback to be /* set current day from 0 to 6 depending on the selected item */ emJri.setJSJriVariable("Days", new Integer(day)); notified when an embedded variable dayLabel.setText(dayNames[day]); value changes. } An example of an emObject directly controlling an embedded variable is

30 Issue 100 November 1998 Circuit Cellar INK® Or, emGateway could serve networking platform, which includes the client the prestaged class access to the Internet. file along with the standard Intelligent devices are a reality, so set of preinstalled emObjects. long as we are intelligent enough to connect those devices for continuing EDUCATION IS POSSIBLE education. I When the PC came out, its intelligence was amazing. But Chris Sontag is chief technology of- the PC only truly became ficer and a cofounder of emWare. His intelligent when it was net- areas of expertise include networking, worked with other devices security, X.500-based directory ser- and connected to the Internet. vices, embedded systems, and inter- Embedded devices are fol- nationalization. You may reach Chris lowing suit. Their limited at [email protected]. intelligence expands as they connect to the Internet and SOURCES other networks. EMIT V.2.5 Software Developer Kit This isn’t just a vision for emWare Inc. devices with 32- and 64-bit (877) 4-emWare Photo 1—The GUI can match the device interface or add to the micros with their extended (801) 256-3883 functionality available on the device. This weather-station interface memory and costs. And, you Fax: (801) 256-9267 provides an easy, intuitive view of weather conditions, enabling the don’t have to settle for a user to see the impact of changing data on the device functions. www.emware.com stripped-down web server. support interface hardware costs were Tremendous potential still exists AT89C2051 reduced. in the 8- and 16-bit microcontroller Atmel Corp. The end result is a Java class file market. That growth will continue as (408) 441-0311 that we can compress onto a 32-KB devices using these smaller MCUs are Fax: (408) 436-4200 EEPROM and serve from the device. connected through a complete device www.atmel.com

32 Issue 100 November 1998 Circuit Cellar INK® designed to squeeze every ounce of energy savings while providing ad- FEATURE equate comfort. In my application, the software is ARTICLE divided into two major components. The Occupancy Detection Unit (ODU) must recognize not only when the area is actively occupied and when it is not Beau Wadsworth occupied, but also when the area is occupied by inactive occupants, who may be resting or sleeping. The Pattern Learning Unit (PLU) records the occupancy history for the Smart Building-Control area and predicts the next arrival. OCCUPANCY DETECTION UNIT Applications The ODU provides the information that the PLU uses to predict future activity. It may seem like a no-brainer to detect occupancy in software (assum- ing hardware input like a motion detec- tor), but the task is tougher than it looks. In fact, it’s difficult to know for sure that no one is in the area. f you’re like me, The problem is this: when motion i you’ve been wait- activity ceases for a period of time, Dreaming of those ing a long time for how do you know what happened? the arrival of the smart Are the occupants gone? Is someone smart buildings of building. In theory, our homes and there who is simply inactive? The offices will be outfitted with intelligent solution is to detect two different the future? Well, it’s lighting and energy-management sys- types of activity—interior activity and tems that learn our habits and adapt entry/exit activity. time to wake up. to our needs. As shown in Figure 1, you can Many people have done research on accomplish this task by monitoring the Beau’s powerful advanced building-control software door(s) of an area (via door switches using the PC, or some other “large” used in the security industry) and also machine-learning platform, intent on building a truly monitoring the interior of the area via intelligent system. However, there motion detection. Any time an entry/ software figures out haven’t been that many applications exit door is opened, this signals a deployed in the marketplace. potential change of occupancy. building occupancy In this article, I want to show you As Figure 2 illustrates, it’s not hard a software technique that exhibits to figure out whether people are coming patterns, yet it’s machine learning but in a small, simple or going. If there is no motion detection implementation that runs on any following activity at the door, then simple and small microcontroller. The algorithm tries someone must have left. to understand the comings and enough to run on any goings of people and to anticipate when they might arrive next so Motion Detector microcontroller. it can provide advance heating, Entry/Exit cooling, lighting, and so forth. Door

NOT-SO-NEW TECHNOLOGY

This type of intelligent build- Path ing software was first used, I To Other believe, in certain HVAC con- Areas trollers as far back as 1987. Used mostly in the lodging in- Figure 1—A combination of entry/exit-door and interior-motion dustry, these controllers are information gives the needed results.

34 Issue 100 November 1998 Circuit Cellar INK® Conversely, if motion detection this in Figure 2a as the overshoot a) simply ceases without any door activ- relative to the door timing. Time ity, then the area is not really unoccu- This problem forced me to add a Motion pied. Instead, the occupants must have blanking window to the algorithm so Overlap

retired to an inactive state even though that the real search for motion is Door they are still in the building or area. delayed by a few seconds. A value of 6 s The accuracy of this method is tied works well. Any more than that and b) directly to the quality of motion-detec- the algorithm often fails to detect when Time tor coverage—the more the better. In someone arrives and passes through Motion a house or small office, simply covering the motion-sensing area too quickly.

the main traffic area gives good results. In that case, the system sees the Door Using motion detection in every room arrival but turns around and looks for gives near-perfect performance. evidence of someone leaving (remem- Figure 2—From the timing relationships, it’s easy to In the algorithm, the search process ber, door operation starts the test pro- see when occupants leave or arrive. a—In the leaving starts when the entry/exit door is cess). When the system sees no motion situation, an overlap can occur which must be accounted used. After the door closes, we look activity, except what took place during for in software. b—This graph shows an arrival. for motion for a period of time. If the blanking period, it assumes the indicates clearly what the occupancy there is activity, then clearly someone person left again. So, the blanking pattern was for that day. is still on the premises. If not, then window has to be set carefully. you may declare the area unoccupied. As well, a false unoccupied state THE MOMENT OF TRUTH The time period used can vary, but can be declared when someone leaves The core technique at work in the a good figure is in the 10-min. range. the area while another person, who PLU is to take the record for the same The delay period is a trade-off. Too has been inactive all along, is hidden day of the previous week and use it to from motion detection. Clearly, be- predict the occupancy for the current cause of this weakness, the technique day. It’s well worth keeping a week’s Unoccupied should be used with great care. worth of records since human habits Occupied Many types of automatic responses center around a weekly pattern.

0 h 24 h (e.g., arming a security system) should The process of putting the data to not be implemented. While the sys- work is straightforward. Once every Figure 3—Here’s a typical occupancy history record for tem’s performance can be increased hour, at the same moment when the a 24-h period. This system doesn’t even know what the by adding more motion detection, current occupancy state is recorded in actual time is. It simply starts recording at powerup and rolls over 24 h later. Each day-long record is matched there’s always the possibility (espe- today’s record, the record for that same against previous records. cially where occupants may be sleep- day in the previous week is evaluated. ing) of a misfire. At this moment of truth, the algo- little time and you find that the area rithm looks ahead in the record to see is frequently declared unoccupied, PATTERN LEARNING UNIT if there is any expected occupancy. It only to have this decision reversed a Once the ODU has a good idea of only needs to see a couple of bits in short time later when an occupant the occupancy state, you can put this the data from the previous week—the emerges from some back room. Too information to use. The PLU makes a ones that indicated the occupancy much delay time, and energy savings continuous record of the occupancy state in the next two hour slots. are reduced while the algorithm waits state using a simple encoding means. These bits tell us if the area was for occupants who may never appear. Three bytes contain a total of occupied a week earlier during the One issue affecting the ODU is the 24 bits, each of which can represent upcoming couple hours. Whenever the phenomenon of slow motion-detector the occupied or unoccupied status for release. The occupancy-detection any one hour in a day. Under this algorithm looks for motion detection method, any one-day record can be Temporary Long-Term Memory Records (Permanent Records) as soon as the door closes. However, encoded in three bytes. An entire week’s Temp 1 Day 1 some motion detectors stay tripped worth of data takes only 21 bytes. Temp 2 Day 2 for a relatively long time after motion Later, I’ll show you how this encoding Temp 3 Day 3 ceases (up to 6 or 8 s), which causes a method makes it easy to compare Temp 4 Day 4 problem when the slow motion detec- occupancy patterns. Temp 5 Day 5 Current Memory Day 6 tor is located near the entry/exit door. As I mentioned, in this implemen- (Short Term) While leaving, the occupant trips tation, the system doesn’t even know Previous 24 h Day 7 the detector, opens the door, steps what the actual time is. It simply out, and closes the door. Unfortunately, starts recording time from powerup Figure 4—The system keeps track of previous patterns. the motion detector is still triggered and notes the passing of hour, day, Short Term Memory is the most recent 24-h record. Long Term Memory is a week-long record that remains even though the occupant has stepped and week increments. As shown in semipermanent. Five temporary slots hold unusual out and closed the door! You can see Figure 3, a record for any given “day” records.

Circuit Cellar INK® Issue 100 November 1998 35 as an engineering ap- scores for patterns that really are Enter proach. Here, “fuzzy” similar, while producing nothing for means that the software patterns that aren’t all that much No Ye s Match today’s record Store as Exit is able to recognize pat- alike. Shifting both to the left and to in LTM? new LTM terns even when patterns the right and then looking for a score Compare against don’t match exactly. of at least 23 out of 24 gives a good all temp records The algorithm also assurance of a similar pattern.

No High-scoring temp record Ye s recognizes when the If the record is not deemed similar scores at least 18? building is unoccupied enough to the LTM record for that

Store in oldest Store as Ye s Second time for No for an extended period weekday, it is compared to the five temp location new LTM same record? (vacation detection) and temporary records. The comparison Exit Exit suspends all pattern with the temporary records is similar recording and anticipa- to that for LTM records, except that Figure 5—This block diagram shows the overall strategy. The current day’s tion until the building is the shifting process is not employed record is compared to various patterns in an attempt to find the best match. normally occupied again. and the current record is compared to It looks first for a close match with the most likely element—that day’s record The original patterns are all five temporary records with the in LTM. Failing that, it looks next for a sufficiently high score with any of the retained until they are score of each comparison being noted. temporary records. needed again. The highest-scoring comparison building is unoccupied, it’s simply a The fuzzy recognizer makes a series that scores at least 18 is taken as a matter of testing the next two hour of comparisons that each day’s record match. A current record that fails to bits, and voilà—we have anticipation. is put through in an attempt to gauge match any record is deemed a new Using this method, with 1-h reso- its validity. Figure 4 shows how previ- temporary record, overwriting the lution, accuracy is ±1 h. That’s why ous records are stored in memory. oldest one in memory. the anticipator looks at the next 2 h of Long-term memory (LTM) is a semi- If a given record does match a tem- last week’s record. If it only looks 1 h permanent record, one week long. If a porary record, a quick check is done ahead, it could err on the minus side current record passes muster, it re- to see if the same thing happened last all the way down to (almost) zero places the existing record for that week. If the record matches the same anticipation. Using 2 h gives it a perfor- particular weekday in LTM. miscellaneous record for two weeks mance range of 1–3 h of anticipation. There are five additional slots for running), that record wins a place as The range can easily be decreased temporary records that did not match the LTM for that weekday. by using a higher resolution system- anything at the time they appeared. I should note that the algorithm wide. For example, records can indi- The temporary records are key in also checks for a completely unoccu- cate half-hour increments instead of the process of learning new patterns. pied state during the current record’s an hour. This technique uses double Anytime a current pattern matches 24-h period. Whenever there is a match the amount of RAM but has an antici- the same temporary pattern for two with the unoccupied profile, a counter pation range from 30 to 90 min. The weeks running, the system assumes is incremented. If this happens for three beauty of this method is that any that it’s seeing a new schedule for consecutive days, all system learning resolution can be used and the imple- that weekday. is suspended (i.e., vacation detection). mentation stays pretty much the same. Figure 5 shows a block diagram of the matching process. Each day’s a) Shifting the patterns while taking the score A FUZZY RECOGNIZER record is compared to the same day’s yields extra information It may seem like the PLU was rela- record in LTM using a pattern-match- tively easy to construct. Unfortunately, ing process. As shown in Figure 6, the the algorithm is still not very smart. two patterns are compared bit by bit Even though it predicts the arrival with the total number of like bits 0 24 h of occupants with some success, it being noted. Unshifted Score = 21 Shifted Left = 23 records and acts on any and all patterns Clearly, if all 24 bits are the same, Shifted Right = 19 that arise, regardless of how atypical the patterns are exactly alike. The b) they may be. To build a sturdy machine tricky part is recognizing patterns that that only recognizes typical patterns, are very similar but not exactly alike. a more complex mechanism is required. The approach used here was to shift 0 24 h The software approach that tran- the patterns one bit position relative Unshifted Score = 21 Shifted Left = 19 scends the basic PLU is a sophisticated to each other and then measure the Shifted Right = 19 fuzzy recognizer that verifies the ordi- score again. This technique tells us if nariness of a pattern before commit- the patterns are similar except for Figure 6—When patterns are compared, each bit position is checked and the number of matching bits are ting it to memory. Note that I’m being offset somewhat. counted to yield a score. Shifting the patterns one bit to using the term “fuzzy” loosely. It As you see in Figures 6a and 6b, the left and to the right tells us if the patterns are similar does not refer to the use of fuzzy logic the shifting process can yield higher but simply offset by an hour or so.

36 Issue 100 November 1998 Circuit Cellar INK® they are adopted as the new permanent look similar (like two combs) but that record. are almost opposite in timing. Needless to say, this mode of op- BUT DOES IT WORK? eration is unlikely because of the 0 24 h Unshifted Score = 0 The system performed very well rarity of a comb-like pattern arising in Shifted Score = 24 during informal testing. As expected, normal circumstances. And even if the algorithm learns occupancy patterns the comb problem appeared, it may be Figure 7—The comb problem can yield “matches” between records that appear similar but actually are within a maximum of three weeks. irrelevant because the anticipator almost opposite. When schedule changes are slight, looks ahead for some time. the system doesn’t change for the In other words, if the area saw very Through this pattern-matching following week. When given a markedly frequent occupancy changes, the antici- process, a delicate balance is created. different pattern, the software waits a pator ends up expecting arrival pretty If a pattern is similar to patterns for couple weeks before adopting the new much all the time. Fortunately, this is that weekday in the past, the new pattern into its permanent record. the behavior you want anyway, so the pattern is immediately adopted as Because the algorithm is verifying comb problem is fairly benign. permanent. This technique enables the pattern’s validity in the second quick adjustment to changes like week, it’s too late to act on it even if SYSTEM RESOURCES Daylight Saving Time. it passes the test. In the third week, the In case you want to set up a similar If the pattern isn’t similar enough anticipator responds to a new pattern. system, you can download the source to adopt immediately, it is compared This algorithm has one weak spot. code for the PLU. However, I didn’t to previous unusual patterns. If there When the patterns contain a large include code for the ODU. It is inter- is a match with one of these for at least number of alternately occupied and twined with the application software two weeks running, then that pattern unoccupied periods, as Figure 7 shows, and would have been difficult to use is taken as the permanent record. the algorithm is threatened by what I in that form. As a result, slight pattern changes call the “comb problem.” The PLU takes only a few hundred are adopted immediately, while anoma- The problem is that the shifting lines of assembler code, which trans- lous patterns are ignored unless they process used in the matching algorithm lates to about 750 bytes of storage on persist for several weeks. In that case, can yield a high score for patterns that an 8-bit micro. In terms of execution time, the worst-case condition takes about 1800 instructions. On an 8031 running at 12 MHz, that equates to about 5 ms to run the PLU thread. This light load is further eased by the fact that the bulk of the PLU thread only runs once per day for an execution overhead of roughly 0.0000057%. So, the PLU can be easily integrated into an application without burdening system resources. I hope you’ve seen how straightfor- ward it is to set up intelligent building- control applications. Now you’re ready to take us into those smart buildings we’ve heard about for so long. I

Beau Wadsworth has been designing embedded systems since 1983. His company designs and manufactures products on an OEM basis for the security and home-automation indus- try. You may reach Beau at (423) 689- 8851 or at [email protected].

SOFTWARE The source code for the PLU is available on the Circuit Cellar web site.

38 Issue 100 November 1998 Circuit Cellar INK® Photo courtesy of emWare

40 Nouveau PC edited by Harv Weiner 44 All BIOSs are Not Created Equal Scott Lehrbaum 49 Real-Time PC Embedded RT-Linux Part 1: General Introduction Ingo Cyliax 57 Applied PCs emWare Top to Bottom Part 1: Monitoring via the Internet Fred Eady SUPER-FAST CPU BOARD The VME64 (V2P2) and CompactPCl (C2P2) are believed to be the industry’s fastest NPC SBCs. Both feature a pair of Pentium II Deschutes processors operating at speeds up to 450 MHz (550 MHz in the future). Each processor is equipped with up to 512 KB of level-2 cache to maximize memory-access performance. The two processors share up to 1 GB of 100-MHz synchronous DRAM main memory. The processors, cache, and memory are linked via a 100-MHz FSB Local bus, which supports the 450-MHz Deschutes processors as well as next-generation 550-MHz Katmai processors. The boards incorporate Intel’s 82443BX and the 640 Advanced Graphics Processor. The DEC 21554 Draw Bridge Chip is included on the CompactPCI version to enable multiprocessing. The boards also include dual Ethernet interfaces (twisted pair) operating at 10 or 100 Mbps, a 40-MBps ultra-wide SCSI interface with auto-termination, and a 64-bit AGP graphics engine with 8 MB of video RAM optimized for 3D rendering. Also available are two MOTION-CONTROL DEVELOPMENT SYSTEM ultra-DMA 33 IDE interfaces, a pair of USB ports, and a parallel port. MotionObjects is an object-oriented application that turns a For applications that must be deployed without a rotating hard Windows 95 or Windows NT computer into a digital oscilloscope disk, the boards provide 72 MB of M-Systems’ DiskOnChip flash and motion-control development system. It complements Westamp’s memory and up to a 750-MB SanDisk 1.5″ flash IDE. The Disk- SP2k-series multiaxis digital-positioning brushless servo driver. OnChip flash memory comes with M-Systems’ TrueFFS file-system Three main development tools help program and fine-tune the software, which enables the flash memory to emulate a hard disk. SP2k servo drivers—MotionEditor, MotionLink, and MotionScope. The V2P2 and C2P2 run a variety of OSs, including Win NT, MotionEditor is a program editor that enables the user to drop Solaris x86, QNX, Vx-Works, and Real I/X. The boards come in text and edit it into a usable program. Working in conjunction equipped with AMI’s BIOS and onboard diagnostics software with MotionEditor, MotionObjects offers a compiler that enables and status LEDs. the user to code in a highly intuitive, procedural, and object- Pricing for the V2P2 and C2P2 starts at $7200 with 0.5-GB oriented language. memory and two 400-MHz Pentium II processors. MotionLink lets the user speak directly to the hardware from any Windows 95– or NT–based PC. Using an RS-232 cable, the General Micro Systems, Inc. user can download or upload a program into the SP2k or similar (800) 307-4863 • (909) 980-4863 servo drivers. Fax: (909) 987-4863 MotionScope is a feature-rich graphics-plotting tool used to www.gms4vme.com evaluate and optimize system performance. The data files may be saved for later retrieval, plotting, printing, and analysis. MotionScope plots command speed (programmed speed), actual speed, and following error. Tuning variables include integral gain, derivative gain, velocity feed-forward gain, and accelera- tion feed-forward gain enabling the programmer to fine-tune the SP2k servo driver for optimal performance. MotionObjects sells for $395 with the purchase of the SP2k- series digital-positioning brushless servo driver.

Westamp, Inc. (818) 709-5000 Fax: (818) 709-8395 www.westamp.com

NouveauPC edited by Harv Weiner 40 CIRCUIT CELLAR INK NOVEMBER 1998 NPC

CompactPCI SBC The SC-1501 is a CompactPCI single-board computer that supports slot–size unit features a built-in 64-bit GUI Intel Pentium CPUs ranging from 133- to 200-MHz MMX. The single 6U- accelerator with 2 MB of DRAM, up to 128 MB of synchronous DRAM, 10BaseT and 100BaseTx Ethernet, and USB port. It also includes 512 KB of cache and a 128-KB flash BIOS. Other features include a floppy-drive controller, one ECP/EPP parallel port, two 16C550-compatible serial ports, real-time clock, flash-disk option, and support for the 32-bit CompactPCI bus and DEC PCI/PCI bridge. An extension file module card—the SC7001—adds support for a 2.5″ hard disk drive, 3.5″ floppy disk drive, and optional SCSI and PMC slot interfaces.

Computer Modules, Inc. (408) 496-1881 Fax: (408) 496-1886 www.compumodules.com

INDUSTRIAL SBC The VSBC-6 is an EBX-compliant single-board computer that The 8″ × 5.75″ × 2″ board includes a full complement of includes PCI-based video, flat-panel BIOS support, 10BaseT industrial features such as eight 12-bit analog channels, 16 opto-22 Ethernet, PC/104-Plus expansion (the PCI-enhanced version of digital lines, two RS-422/-485 COM ports (plus two standard RS- PC/104), and USB interface. The new embedded computer is 232 COM ports), and three extra timer/counters. For high- compatible with QNX, Windows 95/98/CE/NT, VxWorks, and reliability applications, the board includes ECC circuitry that other popular operating systems. detects and corrects one-bit memory errors on the fly, as well as a watchdog timer with true hardware-reset capability. The VSBC-6 accepts all socket-7 processors up to 300-MHz ’K6 and 233-MHz Pentium. Memory op- tions include 8–128-MB EDO or true error-correcting SDRAM, 2–72-MB DiskOnChip flash memory, 512 KB of battery-backed SRAM, and 256-KB level-2 cache. The VSBC-6 board includes a highly reliable de- sign and construction, with latching I/O connectors and latching high-reliability memory sockets. Each board is subjected to a 48-h burn-in and 100% function testing, and is backed by a two-year warranty. The VSBC-6 is priced at $793 with a 200-MHz ’K6 CPU in 100-unit quantities.

VersaLogic Corp. (800) 824-3163 (541) 485-8575 Fax: (541) 485-5712 www.versalogic.com NouveauPC NOVEMBER 1998 EMBEDDEDPC 41 PCI MEZZANINE CARD The TCOM4-SC is a PCI mezzanine card that controller, which can format and deformat up to 128 HDLC provides four E1, T1, or primary-rate ISDN interfaces. channels. NPC Both long- and short-haul communications at speeds of To support low-latency communications with other boards 1.544 Mbps (T1) or 2.048 Mbps (E1 or primary-rate ISDN) residing on a common backplane, the TCOM4-SC provides are supported. an optional SC-Bus (Signal Computing Bus) expansion port The TCOM4-SC can be used with any baseboard (e.g., a VME based on VLSI Technology’s SC4000 controller. Opti- bus or CompactPCI CPU board) that provides PMC sites. The module mized for carrying multimedia communicates with the baseboard via a 32-bit, 33-MHz master/slave traffic such as voice, fax, and PCI interface that complies fully with V.2.1 of the PCI electrical video, the SC-Bus enables up to specification. The module also complies fully with the PMC 128 channels of incoming or mechanical specification. outgoing T1, E1, or PRI traffic to be The TCOM4-SC’s four E1/T1 physical-line interfaces routed to other boards without occu- are implemented using Brooktree Bt8370 T1/E1 trans- pying system-bus bandwidth. T1, E1, ceivers. The transceivers perform T1 framing compli- and PRI channels can be mapped dy- ant with the SF, ESF SLCR99, and T1DM standards, namically to any of the SC-Bus time slots. and E1 framing compliant with the PCM30, The TCOM4-SC starts at $465 (quantity G.704, G.706, G.732, and ISDN primary- 1000) for a two-channel E1/T1 solution. A four- rate ISDN E1 standards. The transceiver also channel version of the TCOM4-SC costs $635 in supports alarm and error monitoring, sig- 1000-piece quantities. naling supervision, trunk conditioning, and facility-data-link (FDL) mainte- SciTech, Inc. nance. The TCOM4-SC’s data- (608) 833-7877 link interface is based on Fax: (608) 833-8738 Brooktree’s Bt8474 HDLC www.stinc.com

CompactPCI DEVELOPMENT SYSTEM The Ziatech ZT 5081 6U 14-slot development system features transition cards for simplified cabling. The backplane also supports an SBC with a 200-MHz Pentium/MMX processor, 64-MB ECC peripheral and I/O cards adhering to the PICMG hot-swap. DRAM, 512 KB of L2 cache, a 3.2-GB IDE hard drive, a floppy The new rack-mount system comes with MS-DOS, Ziatech’s drive, a wide SCSI interface, and two 150-W hot-swap power industrial BIOS, and flash disk. The internal hard-disk drive is supplies. The feature set is ready for the installation of PC- housed in a 19″ rack-mount compatible operating systems IEEE 1101.10-compliant such as Windows NT, QNX, or Compact-PCI chassis with VxWorks. Ziatech offers op- a 14-slot backplane, suit- tional development toolkits com- able for general-purpose plete with additional files to and telecommunications help simplify the implementa- applications. tion of these operating systems. In addition to accom- The ZT 5081 6U 14-slot de- modating 32- or 64-bit velopment system is priced at Compact-PCI cards, the $5595. backplane supports the H.110 computer telephony Ziatech Corp. bus for voice and other (805) 541-0488 telephony applications and Fax: (805) 541-5088 IEEE 1101.11-style rear www.ziatech.com NouveauPC 42 CIRCUIT CELLAR INK NOVEMBER 1998 44 N to meettheexactingdemandsofmedical,military,andfactoryenvironments. tough BIOS.Scotthelpsusmakesureourembedded-PCproductsarefit enough No PC-basedCPUissuitableforembeddedapplicationswithoutan equally vigorously. Some mightholdupwell, form-factor proponent canarguetheircase bacterial contamination? factory productionlineortest bloodfor the resultingproductbetrusted toruna new embedded-PCformfactor. But,can iron andacookiecuttercan whip upa nology. Almostanyonewithasoldering pervasive, it’svirtuallyacommoditytech- form factors. backplane PCs, ded territoryarePC/104,passive- PC. AmongthePC’sforaysintoembed- absolute necessityinembeddedsystems. accident prone,too,andreliabilityisan climate oftheembeddedworld.Itwas solitaire, notventureoutintothehostile designed tositinawarmofficeplaying of SiliconValley.Afterall,thePCwas ded systemwouldhavebeenlaughedout putting thePCarchitectureintoanembed- No doubt,everyboardvendor and The PCarchitecturehasbecomeso But itslimitationshaven’tstoppedthe ot longago,anyonewhosuggested EPC All BIOSs are NotAll BIOSsare and lotsofproprietarySBC Created Equal Created CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR PC SELF-DESTRUCT tions nevercrossed theirminds. had toconsider forsuchexoticapplica- submersibles. Theissuestheywould have up insupersonicaircraftand deep-sea that theirsleeknewcomputer would end IBM designteamprobablynever dreamed how wellthePCwasdesigned. these problemshavenothingtodowith architecture. Thereasonsbehindsomeof Who hasn’tseentheirsystemcrash? have tolookbeyondyourowndesktop. cut itforembeddedsystems,youdon’t out anequallyfine-tunedBIOS. suitable forembeddedapplicationswith- PC motherboard,noPC-basedCPUis board vendorsmightimprovetheaverage talk aboutBIOSinstead.Asmuchas were designedforembeddedsystems. especially architectureslikePC/104that But, it’simportanttoremember thatthe It’snotmyintentiontoindictthePC To understandwhy“normal”PCsdon’t But, let’ssetasidethehardwareand S cott Lehrbaum 1998 LIKE KRYPTONITE can bemoresubtle, especiallytheones weak pointspose suchathreat.Theeffects down isnevergood.Butnotall ofthePC’s ously combust,theycausealot of damage. many criticalfunctions.Ifthey spontane- for controllinganuclearpowerplant? an operation?Whatifitwasresponsible monitoring apatient’svitalstatisticsduring data. Ifyouloseit,canbeinbigtrouble. the smallmatterofsystemconfiguration pop inanewbattery.ButonPC,there’s dead? Withanyothergadget,youjust much longeroperatinglifetimes. with embeddedPCs,whichtendtohave lete afteracoupleyearsanyway).Notso (especially sinceaPCisconsideredobso- battery lifeisprobablymorethansufficient For theaveragePC,afive-orten-year Obviously, acompletecomputer melt- Embedded applicationstakecareof What ifthissamebasictechnologywas And whatiftheCMOSbatterygoes Take theCMOSbattery,forexample. EPC 45 Military the embedded system. become An embedded-PC BIOS should provide The BIOS keeps a copy of the current I talked about problems that can arise A good starting point starting A good the BIOS may For a super-fast startup, can fully But if the board manufacturer Industrial Control Transportation an alternative way of storing configuration data. For example, in its enhanced em- bedded-PC BIOS, Ampro uses a small EEPROM to back up CMOS RAM data. set-up configuration in EEPROM and re- stores the CMOS if battery backup isn’t available. The only information lost at power- down is the real-time clock time and date. if the CMOS battery dies. But protecting configuration data isn’t the only issue. Some embedded applications can’t use batteries, especially if they’re near explo- sive environmental gases. Hey, if a battery sparks while you’re near a pocket of meth- ane, you is to cut features that the is to cut need, like repeti- systems don’t tests and plug-and- tive memory rou- Some initialization play support. streamlined if the hardware tines can be stripped response time or even has a fast is low. Obviously, out if its chance of failure carries some risk. that kind of change time. In this case, need to cut execution tests and initializa- many of the hardware have to be skipped. tion routines simply being done, system document what isn’t want the feature. developers might still use the parts of the They may not need to system that aren’t being initialized, or they might be able to initialize the hardware from inside their own application code. BATTERY-FREE OPERATION PC MBEDDED Medical Aviation Telecom E that noncritical errors

1998 1998 Ever timed your desktop PC to find out Embedded-PC BIOSs should provide Despite advanced PC technology, you PC technology, Despite advanced the problem, an embedded- Whatever retrying all avail- The BIOS has to keep don’t have a Many embedded systems These are just two examples, but a well- High reliabilityAlternative storage mediaPower management XWatchdog timerBattery-free operationNo-fail startup XInstant on XUnattended operation XRemote access X X features XStart-up customization X XRTOS support X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X vertical market segments. NOVEMBER NOVEMBER how long it takes to start up? Embedded systems can't get away with such outra- geous startup delays. options for dramatically accelerating the start-up process. Aside from using a fast- booting OS, expert embedded BIOS de- velopers can usually find lots of fat to trim in the POST procedure. can still run across ill-behaved hardware. across ill-behaved can still run particular systems quit for no Sometimes, (POST). the power-on self-test reason during has to deal just give up. It PC BIOS can’t and coax it with recalcitrant hardware back into operation. boot fails the first time able boot devices if the it can do is restart through. The best thing the hardware wasn’t POST in case any of powerup. This also initialized properly on time to get ready. gives the hard drive more input device, so if keyboard or any other it the BIOS doesn’t detect a keyboard, can’t report “Keyboard error or no key- It board present—press F1 to continue.” should continue POST no matter how the keyboard test comes out. designed embedded-PC BIOS needs an entire toolkit of problem-recovery options. That includes ensuring the hardware comes up running OK and INSTANT ON NO-FAIL STARTUP NO-FAIL don’t stop the boot-up process. Table 1—These critical embedded-PC BIOS enhancements are commonly required in certain mainte- some alternative method of access- Before talking about ways of toughening Before talking as an jump out Medical instruments categorically in- Medical systems are Production-line systems can be mission- Another common trait of automation If there’s a display, it’s more likely to be There are all sorts of military applica- Many military applications are portable, It’s important to keep the system’s total My program for getting an embedded- PCs usually work reliably, as long as up the PC BIOS, let’s look at some of the BIOS, let’s look at some up the PC systems in facing embedded special issues 1). markets (see Table a few vertical systems that better obvious example of Not all medical work when they’re needed. but they may still devices are life-critical, a patient is diag- have an impact on how are prescribed. nosed or what drugs crashes. No matter tolerant of software software is written, how well the application a built-in automatic critical systems need The machines also recovery mechanism. have to come up running very quickly. critical as well. Production lines churn out millions of dollars worth of product an hour, and down time quickly turns a profit- able operation into a money loser. So, the embedded PCs have to be reliable, oper- ating continuously for long periods of time. systems is that the embedded PC tends to be deeply embedded. There’s no floppy disk drive, keyboard, or mouse. a few black and white characters or color LEDs than a VGA monitor. For tions for embedded PCs, from missile guid- ance to aircraft systems to ruggedized field PCs. Exacting specifications and op- erational reliability are an absolute must. which raises the issue of power manage- ment. To maximize battery life, a thorough and well-designed power-management interface is essential. power appetite to a minimum, perhaps by using alternative, low-power options for program-storage and video-display features. originating with the BIOS. But, they can But, they the BIOS. with originating systems. with embedded still play havoc nance, ing the system is needed. PC BIOS ready for mission-critical embed- ded applications is summarized in Table 2. you keep them in the shallow end of the pool. But there are some pretty effective ways of strengthening the PC, both at a hardware and BIOS level. BIOS FITNESS Table 2—This list gives you a look at some of the benefits of embedded-PC BIOS enhancements BIOS embedded-PC 46 of benefits the of some at look a you gives list 2—This Table ALTERNATE ACCESS display orkeyboard.Howdoyouaccessit? task beforereturningcontroltothesystem. to hooktheBIOSandperformaspecial code manyopportunitiesthroughoutPOST a greaterdegreeofstart-upflexibility. a goodstartingpointforgivingtheBIOS near theendofPOST.The55AAhookis disks theopportunitytoinstallthemselves like networkbootROMsandsolid-state 55AA ROMscan,whichgivescode weight, andpowerbudget. space, that’sanicewaytocutthecost, application codecanbestuffedintoROM software doesn’tneedanOSandallthe system earlyonandneverletgo.Ifthe requires specialinitializationearlyinPOST. system usesanexoticvideointerfacethat off thePOSTmessagedisplaycompletely. cation software.Orperhapsyoucanturn to embedded applications. embedded to there untilthesystembootsintoappli- ihrlaiiyFine-tunessystem operation (signaltiming,deviceinitializa- Optimizessystem performance forcompatibilitywithall High reliability Restartsthesystem incaseofasoftwarecrash,power Unattended operation support RTOS Year-2000 compliance Power management Watchdog timer Providesoptionsfor programanddatastorageusing Providesalternativetostandard keyboardandvideoscreen Allowsremotesoftwareupdates andremotedebugging Alternative storage media support Providesnear-instantpower-on tosystem-readystartup Allowscustomizationofthe startupprocessforsystem- Remote maintenance capability Preventshardware initializationerrorsanddevicefailures Alternate consoleaccess Start-up customization Battery-free operation Instant on No-fail startup So, yourembeddedsystemhasno A goodembedded-PCBIOSgivesROM All PCBIOSssupporttheIBM-standard Some applicationsgrabcontrolofthe Another typicalscenarioisthatthe onscreen earlyinPOSTandleaveit EPC One answeristothrowalogo in yourboxisaplainoldPC. users toknow You maynotwantend ON STARTUP that themagic Allows systemtobeoperatedforextended amountsoftime Avoids softwarefailuresduetotheY2Kcomputerbug Reduces totalsystempowerbudgetforportableandbattery- Allows thesystemtooperatewithoutbatteries,preventsa all operatingconditions tion, etc.)foroptimalsurvivabilityand performanceunder with zerouserintervention major RTOSs powered applications brownout, orotherfailurecondition nonmechanical (solidstate)media capabilities viaserialterminalorotherinterconnect unique hardwareinitialization,displayofcustomlogos,etc. system CMOS RAMbackupbatteryfailurefromharmingthe from haltingthestartup CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR REMOTE MAINTENANCE tasks remotely. should letservicepersonnelperformthese system maintenance.TheembeddedPC into serialconsolemodeautomatically. figuration, theBIOSneedsawaytoswitch easy waytochangethesystemset-upcon- serial consoleaccessport.But,withno good toletoneoftheportsdoubleasa be scarce;theygetusedupquickly.It’s console accessatvirtuallynocost. most PCs,theseremotefeaturesprovide two ormoreserialportsarepresenton using aphonelineorradiomodem.Since modem cableorfromaremotelocation portable computerconnectedviaanull information tobereceivedonahostsystem. commands tobeenteredanddisplay interconnect. Itshouldenablekeyboard console accessoveraserialportorother needed onlyforoccasionalmaintenance. and keyboard,increasingcostsforfeatures OEM toaddavideocontroller,display, later analysis.Itdoesn’tmakesenseforan system statusduringflightandsavesitfor Consider asystemthatrecordsaircraft need auserinterfaceforsystemoperation. You’re also going to You’re alsogoingto need occasional Then again,available Ideally, thisaccessisachievedviaa The BIOSshouldofferoptionsforremote Lots ofembeddedapplicationsdon’t

serial portsmay 1998 STORAGE SUPPORT WATCHDOG TIMER the applicationsoftwarelaunchesfaster. expense ofOSlicensingbutcanmeanthat ROM. Thistechniquenotonlysavesthe may bebetteroffstoringprogramcodein include removableSSDoptions. down. Ideally,theBIOSsupportshould rugged andlesssusceptibletobreak- Without movingparts,SSDsaremore drives. (SSD) mediainplaceofmechanical riety ofoptionsforusingsolid-state disk version ofanaphylacticshock. and floppydrivestogointotheelectronic strong magneticfieldscausemosthard and vibration,temperatureextremes, environmental conditions.Intensiveshock optimized tothe application’srequirements. WDT andprovide recoveryprocedures ware enoughflexibilitytomanage the The routinesmustgiveapplication soft- port itthroughsoftwareinterrupt services. ture, theembedded-PCBIOS should sup- restart andrestoreittooperation quickly. to crash,theWDTcaninitiateasystem something happensthatcausesthesystem so it’snotaffectedbysystemglitches.If tem independentlyoftherestcircuit, cal activities.TheWDTmonitorsthesys- necessity forallsystemsthatmanagecriti- can thatsystembedown? pilot applicationforalargejet.Howlong brownouts, andmore.Consideranauto- That includessoftwarecrashes,power must continuetoworkunderallconditions. for mission-criticalembeddedsystems:they code tobeROM-residentonthetarget. serial debugger,ratherthanforcingthat matic downloadofthetargetportion embedded-PC BIOShastosupportauto- is on-the-flyserialdebuggingsupport.The on-system softwaredevelopmentfeasible transfer filesbackandforthfromahost. need remoteconsoleaccessandawayto from aremotelocation.Thosesystems fications canbemadeonthesystembut on theembeddedsystemsosoftwaremodi- program sourcecodeandcompilersresident Beyond SSDs,manyembeddedsystems Embedded-system BIOSssupportava- Embedded systemshavetoendureharsh Although aWDTishardware fea- A reliablewatchdogtimer(WDT)isa It’s asimplebutessentialrequirement Another requirementtomakingremote Some usersmaywanttokeeptheir 48 Y2K COMPLIANCE death recently,butit’simportanttoseethat user-selectable dutycycle. you caninterleaveCPUoperationusinga setpoint. Forpower-sensitiveapplications, matically engagetheCPUfanatathermal temperature. Oneapproachistoauto- BIOS shouldmonitorandcontroltheCPU the componentsandoptionalinterfacesused. of optimizingpowersavingsdependingon areas ofenhancement.It’smostlyamatter ment codearemoresubtlethanother Power Interface)haveseentothat. and ACPI(AdvancedConfiguration as APM(AdvancedPowerManagement) and power-managementstandardssuch management. InitiativeslikeGreenPC automatic andsoftware-managedpower Sure, this topichasbeenbeatento Sure, If excessivetemperatureisanissue,the The changestothepower-manage- tend tohavealotofbuilt-insupportfor

portable applications.PCBIOSs EPC is animportantrequirementof MANAGEMENT Low powerconsumption POWER CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR RTOS SUPPORT late andreturnthepropercenturyvalue. century rolloverandshouldalwayscalcu- matically updatethereal-timeclockaftera the averagedesktopmachine. they’re doingtendstobemorecriticalthan ways thandesktopPCs.Again,what bedded systemsinmuchmoredramatic year-2000-related problemscanaffectem- vices maynotbeaccessibletoanapplica- supported throughenhancedBIOSser- interrupt routines.Specialfeaturesthatare is incompatiblewithvirtuallyallBIOS RTOSs operateinprotectedmode,which BIOS servicesfrominsideanapplication. compatible withallRTOSs. embedded PCtomakesuretheproductis There’s anartinrefiningtheBIOSforany RTOSs mayornotlikewhattheysee. ized thesystemcomponents,different cess hardwaredirectly. discard BIOSinterruptservicesandac- can betricky.Foronething,theytendto A Y2K-compliantBIOSshouldauto- Another issueishowtoaccessenhanced Depending onhowtheBIOShasinitial- Support forreal-timeoperatingsystems 1998 AND THEREST Scott Lehrbaum has been at Ampro Com- Ampro at been has Lehrbaum Scott A FEWLASTWORDS specifications withroomtospare. bus timingparameterssatisfyapplicable bustness byensuringthatcomponentand should trytomaximizethemodule’sro- rations andtimingrequirements.TheBIOS kinds ofsystemswithdifferentbusconfigu- bad orcorruptset-upconfiguration. BIOS shouldenableeasyrecoveryfroma known togetlostfromtimetime,the eliminates anyneedforhumaninteraction. So, awell-designedembedded-PCBIOS tended forweeks,months,orevenyears. media onthetargetmodule. any diskdrivesoralternativestorage host. Thissetupcaneliminatetheneedfor PC todownloadbootcodefromaremote boot capabilityenablingtheembedded programmed byapplicationsoftware. able thisOEMareatobereadand BIOS side,servicesarenecessarytoen- bytes ofapplicationparameters.Onthe uses forit.Forexample,itmaystoreafew age), OEMcustomersusuallyfindcreative PROM usedforconfigurationdatastor- memory deviceonboard(e.g.,theEE- access toallextendedsystemfeatures. ware runningunderanRTOStohavefull provides somemeansforapplicationsoft- tion program.Agoodembedded-PCBIOS under pressure. won’t doanygoodiftheBIOSbuckles well theboardhasbeenhardened,it as ruggedizedhardware.Nomatterhow fine-tuned forembeddedenvironments. board supplierstoensurethattheBIOSis considering thePCarchitectureshouldcheck applications. Embedded-systemdevelopers market andknowledgeaboutreal-world needs experienceservingtheembedded effectively, anembedded-PCsupplier puters for nearly ten years, where he has he where years, ten nearly for puters held numerous positions ranging from ranging positions numerous held Software Engineer to Applications Engi- Applications to Engineer Software neering Manager. You may reach him at him reach may You Manager. neering [email protected]. Finally, embeddedPCsgetusedinall Since configurationdatahasbeen Embedded systemsmayoperateunat- A potentiallyusefuloptionisaserial If extrastoragespaceisavailableina A well-designedBIOSisasimportant To addtherequiredenhancements EPC RPC 49 Naturally, this question is tugging at For one thing, it’s freely available and Usually, it’s not a problem. GPL only A real-time extender, which extends your brain. There are several reasons to consider Linux as an embedded operat- ing system for many applications. includes a TCP/IP stack. Also, it has multiarchitecture support for Intel, 68k, requires you to make available the sources for components that are already under GPL. Other components, applications, and modules that you develop can be excluded. the kernel using a dynamically loadable module, is also freely available. It works similar to real-time extenders for OSs like Windows NT, by dividing applications into processes and threads that are real- time aware and standard user processes that go unaffected. There’s more, but I’ll get into Linux’s real-time extension in a later column. WHY LINUX? vi PC and ls PC MBEDDED E ime T 1998 ngo Cyliax eal-

I R 95–96), where he describes the GPL I should note that one of the differences Together, the Linux kernel and the Also, the kernel and a number of NOVEMBER NOVEMBER INK and the issues concerning the embedded- systems integrator. between the Linux kernel and the NetBSD/ FreeBSD kernel is that the Linux kernel is not GPL protected (whereas the others are) and it is subject to a different licensing agreement. Whether GPL is right for your project depends on your requirements. to C and Fortran compilers and even commercial applications. extensive applications that come bundled with it are called distributions. applications are available under the GNU copyright, or GPL. Check out Pat Villani’s series of excellent articles on FreeDOS ( Linux—the kernel, which is the true Linux component, and the applications that have been developed and ported to Linux. The applications range from clones of simple Unix command-line utilities like

Part 1: General Introduction 1: General Part

mbedded RT-Linux mbedded E

Linux is an alternative OS for PC (and I’ve been a Linux user and developer But, Linux has such a huge following, I

n past columns dealing with real-time non-PC) platforms. There are really two aspects to what is generally considered INTRODUCING LINUX

for about two years. I’m also a fan of other freely distributed Unix-like OSs, like Net- BSD and FreeBSD. Both are direct descen- dents of the BSD (Berkeley Software Dis- tribution) operating systems. I still use them for other projects. For example, my web and mail server runs FreeBSD. wanted to make sure you had the latest information. I also discuss some differences between Linux and FreeBSD/NetBSD. I operating systems, I’ve mentioned Linux and explained how I use it as a develop- ment system and the primary OS on my laptop. Starting this month, I want to show you how to use Linux as an embedded OS—even as a real-time embedded OS. Ingo kicks off this miniseries on using Linux as an embedded operating system on using Linux as an embedded operating Ingo kicks off this miniseries we start comparison to other freely available OSs. As with an overview and a projects that use Linux, it’llseeing more and more why they do. be pretty clear Ethernet Controllers SCSI Host Adapters 3Com 3c501 (throw it away!) SCSI driver for Symbios/NCR 53c700 series and 3Com EtherLink II 53c800 series host adapters 3Com Etherlink Plus BusLogic MultiMaster (NOT Flashpoint) SCSI 3Com EtherLink16 host adapter driver 3Com EtherLink III NCR53c406a-based SCSI host adapter driver 3Com 3c590/3c595 Vortex AdvanSys SCSI host adapter driver Ansel Communications Model 3200 EISA Adaptec AHA-152x host adapter driver Ethernet adapter Adaptec AHA-154x and 631x-based host Apricot 82596 adapter driver ARCnet for IP driver Adaptec AHA-174x host adapter driver Allied Telesis AT1700 Adaptec AHA-2740, 28xx, 29xx, 39xx, aic7xxx- DE425, DE434, DE435, DE450, and DE500 based host adapter driver DEC EtherWORKS cards DTC 3180/3280 host adapter driver D-Link DE-600 Ethernet pocket adapter All DMA-capable DPT SCSI host adapters D-Link DE-620 Ethernet pocket adapter All PIO-capable DPT SCSI host adapters DEC DEPCA and EtherWORKS DE100, Future Domain TMC-16xx SCSI host adapters DE101, DE200, DE201, DE202, DE210, IN2000 SCSI host adapters DE422 Symbios/NCR 53C810, 53C815, 53C820, Digi RightSwitch SE-4, SE-6 53C825 SCSI host adapters Cabletron E2100 Pro Audio Spectrum/Studio 16 EtherExpress Pro/10 IOMEGA PPA3/Parallel ZIP EtherExpress Qlogic FAS408 SCSI host adapter ICL EtherTeam 16i/32 EISA QLogic ISP1020 SCSI host adapter EtherWORKS 3: DE203, DE204, DE205 Seagate ST-01/02, Future Domain TMC-8xx Fujitsu FMV-181/182/183/184 SCSI host adapter HP PCLAN/plus Trantor T128/T128F/T228 SCSI host adapter HP LAN UltraStor 14F/34F (not 24F) SCSI host adapter HP10/100VG ANY LAN: J2577, J2573, 27248B, UltraStor 14F/24F/34F SCSI host adapter J2577, J2573, J2585 WD7000-FASST2/WD7000-ASC/WD7000-AX/ Shared-memory IBM Token Ring 16/4 WD7000-EX SCSI host adapter AMD PCnet32, PCnetPCI NE1000, NE2000, and compatible CD-ROM Drivers NI5210 Ethernet Aztech CD268 CD-ROM driver NI6510 Ethernet Sony CDU-31A CD-ROM driver Parallel Link Internet Protocol Philips/LMS cm20 CD-ROM driver Sangoma S502/S508 series multi-protocol PC GoldStar R420 CD-ROM driver interface card ISP16/MAD16/Mozart soundcard-based CD- SMC Ultra, SMC EtherEZ ISA ROM driver SMC 9000 series Ethernet Mitsumi CD-ROM driver Starmode Radio IP Mitsumi XA/Multisession CD-ROM driver DEC 21040, most 21*40 Ethernet SoundBlaster Pro/Matsushita/Panasonic/ AT&T GIS (nee NCR) WaveLAN Ethernet-like Longshine/CreativeLabs/TEAC/ECS-AT CD- radio transceiver ROM WD8003- and WD8013-compatible ether cards Sanyo CD-ROM device driver Sony CDU-535 CD-ROM driver

Table 1—Here is a list of some of the devices that are typically supported with a standard Linux kernel. In addition to these devices, many peripheral-card vendors also offer Linux-driver modules for their cards.

PowerPC, Alpha, Sparc, SMP, and others. You can download most Linux distribu- So, you can obtain and begin using Linux tions from the Internet. But, this can be with very little trouble. tedious over a slow link, so most of us opt One of the great benefits of using Linux to buy a CD-ROM. Yet, being able to is the large support network that exists for download a distribution over the ’Net is it, and let’s not forget the fact that Linux extremely useful if you’re in the field and supports many devices and bus architec- need to upgrade you embedded system tures right out of the box. Of course, Linux or get a new version of a device driver. is somewhat modular and there are many Linux has a TCP/IP stack built in. The tools and programming languages avail- TCP/IP implementation is very robust, able. With features like this, Linux starts to since many Internet-service providers use make more sense, huh? Linux for their high-throughput web serv- Let’s talk about these points in more ers. The programming interface for the detail. I already mentioned that Linux is TCP/IP stack is the standard Socket API. freely available. Obviously, that’s nice Linux runs on a multitude of architectures. because you won’t pay royalties for em- I’m only going to talk about the Intel port, bedding Linux in your product. But, you but it’s good to know that you’re not stuck need to make sure all of the modules and with Intel. Some of the details in each port components you plan to use for your are different, but for the most part, Linux is project are freely available. Most are. Linux, at least at the application level.

50 CIRCUIT CELLAR INK NOVEMBER 1998 VME bus,S-bus,andothers. chitectures, likeISAbus,PCMCIA,PCI, architectures, itsupportsvariousbusar- has beenportedtosomanydifferent drivers availableforLinux.BecauseLinux stay freelyavailablewiththeGPL. compelling reasonwhymuchofLinuxwill level. That’sgoodnews,andperhapsone and they’reevenproficientatthekernel engineers familiarwithLinuxisgrowing, enter thejobmarket. the Linuxkernel,andthey’lleventually have learnedOSinternalsbyobserving and-glory developersarestudentswho large supportgroup.Manyofthefame- into theLinuxkerneldevelopmenteffort. ten, thesecompaniesreintegratethefixes viding commercialsupportforLinux.Of- are alsoseveralcompaniesthatpro- in anefforttoattainfameandglory,there writing orportingapplicationsanddrivers many peopleprovideLinuxsupportby there’s alargesupportnetwork.Although Intel processors,likethe80188. work inprogresstoportLinuxsmaller 68328 Dragonballprocessor.There’salso ported for.It’saPDAbasedonMotorola’s 52 be thesmallestsystemthatLinuxis There areagreatnumberofdevice Consequently, thenumberofsoftware There isyetanothersideeffecttothis Since Linuxhassuchagreatfollowing, Listing 1—You need this minimum set of files to boot Linux and start an application an start and Linux boot to files of set minimum this need 1—You Listing /linuxrc /dev/tty4 /dev/tty3 /dev/tty2 /dev/tty1 /dev/systty /dev/ram /dev/null /dev/console /dev /etc/ld.so.cache /etc /bin/insmod /bin/sh /bin /lib/ld-linux.so.1 /lib/libc.so.5 /lib program. Of course, you need to add more device-driver entries in the the in entries device-driver more add to need you course, Of program. if your application needs to access other devices besides the screen and the RAM disk. RAM the and screen the besides devices other access to needs application your if RPC The USRoboticsPalmPilotmay in progressforMIPSprocessors. PowerPCs. And,there’saport bus modules,Alpha,and 68k, whichincludesVME- 68k, Linux isportedto CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR can stillconfigureaLinuxkerneltobe are loadedwhenneeded.Ofcourse,you use, sinceonlytherequireddevicedrivers file. Thisconstructionalsoimprovesmemory configurations bychangingaconfiguration configured todealwithdifferentdevice but theydomakeconfigurationeasy. kernel. Dynamicmodulesarenothingnew, time toextendthebasefunctionalityof ers canbeloadedbytheOSafterboot which meanslibrariesanddevicesdriv- these issuesindetailwhenIembedLinux. like aIDEdrive.Nextmonth,I’lllookat vices, workunderLinuxbecauseitactsjust disks, likeSanDisk’sCompactFlashde- boot Linuxfromaflashfilesystem.Flash Hopefully, someoneisworkingonit. nice forworkingwithembeddedsystems. supported. That’sunfortunate.Itwouldbe in anolderdistributionofRedHat. shows alistofdevicesthataresupported and SCSIdevicesaresupported.Table1 many VGAchipsets.Also,CD-ROMs peripherals (COM,IDE,floppy,etc.),and of theEthernetchipsets,allstandardAT able formostdevicedrivers. your purposes,sincesourcesareavail- fixing oradaptingthedevicedriverfor well supported.Also,there’shopeof many popularcardsandchipsetsare quality ofdevicedriversforLinuxvaries, have Linuxdriversavailable.Whilethe You buildasimplekernelthatcanbe Linux supportsdynamicmoduleloading, But, allisnotlost—it’sstillpossibleto However, aflashfile-systemdriverisn’t Drivers areavailableforjustaboutall Many vendorsofPC-compatiblecards /dev directory 1998 and youcanfindothersinthe listed onecompilervendorinmysources, compiler anddevelopmentenvironments.I and relatedtools,you’llfindcommercial on theconsoleofembeddedsystem. Of course,youcanalsorunthedebugger from adesktopor,inmycase,laptop. can debugyourembeddedsystemremotely or serialport.Thiscapabilitymeansthatyou deal withremotedebuggingviaEthernet debugger (gdb)isflexibleandcaneven and ObjectiveCcompiler).Thecompanion the GNUCcompiler(acompleteC,C++, development system. have accesstoalltheapplicationsonyour ing embeddedsystems,butit’sniceto feature mightnotbeimportantforbuild- languages areavailableforLinux.This it needsforaparticularapplication. static bycompilinginallthedevicedrivers size kernelthatshouldworkinabout2MB. possible toconfigureandbuildaminimum able todosomethingis4MB.Itshouldbe load astandardLinuxkernelandhaveitbe that’s notthepointofaminimumsystem. gram orrunanXserveronit.Butthen, probably don’twanttocompileapro- MB ofmemory.Itrunsfine,although you 5 Linux onmy16-MHz’386SXlaptopwith out thereshouldrunLinuxjustfine. mode. Severalembedded’386boards cause Linuxhastorunin32-bitprotected from flashmemory ifyoucan’taccessthe boot flash-memorydiskonceit’s loaded. memory afterall,butitcan’t access the So, it’spossibletobootLinuxfrom aflash kind ofbootdevicetheBIOScan handle. load andinitializethekernel usingany but itcanbootfromit.Infact, Linuxcan boot Linux,weneedadevice. memory, whatelsedoweneed?Well,to RUNNING SUPPORT need atleastan minimum configurationweneed? Linux inanembeddedsystem.Whatisthe usually 8–16MB,it’soverkillforrunning size forrunningLinuxwithX-Windowsis In conjunctionwiththeGNUCcompiler The normalcompilerusedforLinuxis Many applicationsandprogramming Now wehavean The minimummemoryconfigurationto In fact,Iwasevenabletobootandrun You mayask,what goodisittoboot Linux can’tuseflashmemoryasdisks, To runLinuxonaPCarchitecture,we Although therecommendedminimum i 386-class machinebe- i 386 and4MBof Linux Journal Linux . disk after booting? Well, there are at least The motherboard contains everything two techniques you can use to initialize an needed to build a system and run an initial RAM disk while booting, and this embedded application. It has a 233-MHz RAM-disk image can contain the essentials Pentium MMX CPU, slots for two DIMM of what’s needed to run Linux. modules, 10-/100-Mbps Ethernet control- What do we need to run Linux once the ler, dual-IDE controller, floppy control, kernel has booted? By incorporating our and SVGA controller. It also contains a system into one Linux program, we can flash-card socket on the motherboard. get away with a small set of files. Listing 1 SanDisk’s CompactFlash is a flash- has the details. based media that contains an IDE control- The most critical components are the ler on the card itself. To the system, it looks console device entry /dev/console and just like another IDE drive. Motorola also whatever device entries that are needed. sells a starter system that includes a case Once booted, the kernel opens and runs and power supply as well as a standard whatever program or command script is IDE drive for development. contained in /linuxrc. That’s about all With this system, you can develop you need for a minimal configuration. embedded applications while running off Even though Linux wasn’t designed as the hard disk and build a flash-card an embedded OS, it ended up having module of our embedded system. Then, features like small initial size and capability just reboot, change the boot sequence in for RAM disks and modular device drivers. the BIOS setup, and have the system boot These features are there because the devel- from the flash card to test your applica- opers wanted Linux to be easy to install. tion. Next month, I’ll use it to build a flash A single floppy can hold a complete card-based Linux installation. mini-Linux system, complete with enough utilities to format and initialize the file INSTALLING LINUX system on a hard disk and do a bootstrap Obtaining Linux is easy. As I said, you install of Linux from another medium. We can get most Linux distributions from the can use this to our advantage by including ’Net for free. All you need is patience our embedded applications, instead of while downloading it. You can also pur- the installation utilities to build an embed- chase a CD-ROM of various distributions. ded Linux system. Most commonly available distributions Now let’s look at a system I’ve been have enough of the basic components using to play around with embedded Linux. necessary to allow you to embed Linux. It’s based on Motorola’s embedded Pentium Once you have an installation, you SBC, the NLX 55, shown in Photo 1. should build a desktop system to serve as

rtf_create(unsigned int fifo, int size) create a FIFO rtf_destroy(unsigned int fifo) get rid of the FIFO rtf_resize(unsigned int minor, int size) change the size of the FIFO rt_fifo_put(unsigned int fifo, char * buf, int count) write to FIFO rt_fifo_get(unsigned int fifo, char * buf, int count) read from FIFO rtf_create_handler(unsigned int fifo, create a handler that is called when a int (*handler)(unsigned int fifo)) user process reads or writes to a FIFO device rt_task_init(RT_TASK *task, void (*fn) create a task (int data), int data, int stack_size, int priority); rt_task_make_periodic(RT_TASK arrange so that the task is *task, RTIME start_time, RTIME period); called at a periodic interrupt rt_task_delete(RT_TASK *task); get rid of task rt_task_wait(void); give up time slice, wait until next time slice rt_task_suspend(RT_TASK *task); suspend any task rt_get_time(void); read the current time rt_request_timer(void (*fn)(void)); allocate a timer, which will call a handler when it expires rt_free_timer(void); return timer rt_set_timer(RTIME time); set the timer to go off at a specific time rt_no_timer(void); clear timer

Table 2—The real-time extension to Linux (RT-Linux) provides this API for programs that are written to run in this mode. Most of the services are pretty standard interfaces you’d see in a bigger RTOS. But, the FIFO interface can be used to communicate with non-real-time threads.

54 CIRCUIT CELLAR INK NOVEMBER 1998 WHAT’S NEXT I’ve given you an overview of Linux and RT-Linux as well as how you can use it as an embedded OS. I’ll concentrate on the details of Linux in upcoming articles. Next month, I’ll show you how to embed a minimal Linux configuration into a small system. After that, you’ll learn more about Linux embedded software development and how to use RT-Linux. You’re also likely to see Linux in some of my projects. It may not be the answer for every embedded-systems problem, but it’s another tool in the toolbox. And since it’s still being developed and is constantly evolving, Photo 1—The Motorola NLX55 motherboard it will be interesting to see what problems features a Pentium MMX CPU, graphics con- people end up solving with Linux. RPC.EPC troller, and 10-/100-Mbps Ethernet control- ler. Unique to this board, it also includes a socket for a SanDisk flash-based ATA card. Ingo Cyliax has been writing for INK for two years on topics such as embedded your development platform. This process systems, FPGA design, and robotics. He is relatively painless and there are a lot of is a research engineer at Derivation Sys- resources on the ’Net. If your target system tems Inc., a San Diego–based formal is capable enough to serve as a develop- synthesis company, where he works on ment environment, you can install it there. formal-method design tools for high-assur- ance systems and develops embedded-sys- RT EXTENSION OF LINUX tem products. Before joining DSI, Ingo worked The standard Linux kernel doesn’t pre- for over 12 years as a system and re- tend to be real time in the traditional way. search engineer for several universities Like many Unix kernels, the kernel is not and as an independent consultant. You preemptive and thus can’t be relied on for may reach him at [email protected]. predictable interrupt response. But, some REFERENCES clever people developed a real-time ex- www.linux.org tender for Linux that turns it into RT-Linux. RT-Linux project at NASA, aol11.wff.nasa.gov/rtlinux/ RT-Linux has a layer added between SOURCES the Linux kernel and the hardware timer C/C++/F77 compilers for Linux interface. After installing the RT extension, The Portland Group (503) 682-2806 the Linux kernel and its processes turn into Fax: (503) 682-2637 a single real-time task that always runs at www.pgroup.com the lowest priority. NLX55 motherboard Real-time applications are loaded into Motorola Computer Group (800) 759-1107, ext. PR the kernel memory space using the Linux (512) 434-1526, ext. PR module facility. Once the application has www.mcg.mot.com loaded and started real-time tasks, the OpenLinux tasks have control of all the hardware and (801) 765-4999 Fax: (801) 765-1313 memory in the system. RT-Linux provides www.caldera.com calls to start, suspend, and destroy tasks. RT-Linux There’s also a timer facility to set up timers r52h146.res.gatech.edu/~bdixon/rtlinux with real-time responses. Linux distributions A FIFO is used for real-time tasks to RedHat communicate with regular user processes. www.redhat.com The FIFOs appear as standard Unix char- S.u.S.E., Gmbh acter devices that a user process opens +49 911 7405331 Fax: +49 911 7417755 and then reads and writes to. Table 2 shows www.suse.de the basic API available in the RT extender. Linux Journal Although, RT-Linux is rather primitive in (888) 66-Linux its implementation, it has the essentials you (281) 261-2581 Fax: (281)-261-5999 need to implement real-time applications. www.linuxjournal.com NOVEMBER 1998 EMBEDDEDPC 55 APC 57 VIEW ′ ′ ′ ′ ′ As you can see, the control-by-the-web I really struggled coming up with a It’s going to take a couple of passes, The newest release from emWare takes marketplace is growing rapidly. I intend to explore as much of it for you as possible, but for now, let‘s concentrate on another contender in this area, emWare. way to convey the new features of em- Ware’s latest release. After a few days of reading and thought, I figured the best way was to show you what I saw on the screens and describe the code that was generated by interacting with those screens. but by the time we realize our goal, you will have generated your own ideas as to how to integrate EMIT technology in your own projects. And, you’ll garner enough basic EMIT knowledge to implement the package on your own. advantage of today’s object-oriented soft- ware technology to ease the emWare application-development process. Syman- A 5000 PC s PC MBEDDED E 1998 red Eady pplied pplied F A Another web runner comes from NOVEMBER NOVEMBER Phar Lap’s version of web control comes wrapped within a very comprehensive development package that is now ca- pable of using Bill’s latest C++ compiler package. Agranat. EmWeb’s claim to fame is the elimination of the CGI and the melding of C and HTML. If you include EmStack, a TCP/IP stack, you don’t even need an OS to implement EmWeb.

Photo 1—Everything’s here. One CD does it all.

Part 1: Monitoring via thePart Internet

mWare Top to Bottom Top mWare

e

emember getting that first program-

Remember that first contact with a Well, pretty soon, if not already, you I’m going to change all of that here. A Before I begin, I want to point out that The first—Phar Lap’s HTML-On-The-Fly, R BBS? The Internet makes all that look a little silly now, doesn’t it? will be making first contact with your first web appliance. If you keep up with the movies, all of the “first contacts” were pretty much unexpected. Some were cata- strophic. beginning look at what it takes to control and monitor your application via web browsers is right behind this paragraph. there are at least two other products out there that are similar in nature to the one I’m going to discuss in this article. which is included with the Embedded ToolSuite—is a unique implementation that enables you the programmer to as- semble web pages as they are requested. mable calculator? Beat the crap out of that old slide rule, huh? There may have been some good old days, but Fred’s not necessarily one to good old days, but Fred’s not necessarily There may have been some future into the future, and it’s looking like the live in the past. He’s reaching via the web. Join him for a look at emWare’s offering. relies heavily on control Photo 3—Hmm looks alotlikeBill’sVisualBasic. Photo 1iswhereitallbegins. version ofEMITandallitsco-hosts. Let’s getstartedbyinstallingthenew ments inthelatesteditionofemWare. had asayinthisone.) ers. (Idon’tthinktheJusticeDepartment brows- enhanced Netscapeasend-user Internet Explorer,aswellaplug-in– structure doesallofthatworkforyou. utility thatusesastandard days ofEMIT,anupgradedpackage emWARE COMPONENTS a relieftoseethebrowser-installbuttons Internet todownloadthebrowsers.Itwas looking forwardtohookingupthe emWare andEMITareallabout. Ethernet isaprettygoodclueastowhat install buttonsalludingtotheuniversal things asthe“E”word. are asjustimportantintheschemeof but beawarethatthe“I”and“M”words what youwillwiththeremainingwords, makes EMITatopicofinteresttous.Do internetworking technology.Thatfirstword the firstbutton,InstallEMIT2.5. thing conjuredlikewebbrowsers.Notice something physicalandlogicaltosome- Visual Caféasatoolforintegrating 58 tables byhandaswedidintheearly These arejustafewoftheenhance- And now,thedevelopercanuseBill’s Before divingintotheinstall,Iwasnot By theway,signtoleftof EMIT isshortforembeddedmicro As youseeinPhoto1,emWareuses APC intuitive. Also, insteadofbuildingemWare design mucheasierandmore make emWare’sinterface been incorporatedto tec’s VisualCaféhas .ini file CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR AT YOURSERVICE server, gateway,andclientcodes. consists ofthreemajorcomponents: emWare isanapplicationsetthat a momentandI’lltellyouwhy. climb backuptothe5000 code. Don’tworry.That’sOK.Let’s and gatewaycodebutnoserver dialog boxinPhoto2ispresented. dard “whoareyou”screens,the the installprocess.Afterstan- Clicking theEMIT2.5buttonstarts body wasontheballwiththatone. when IfiredupthetoolkitCD.Some- are compressedreferencestointerface emMicro isitsuseofmicrotags.Microtags telecommunications interface. is alldoneviatablesandacommon to thegatewaydevice.Asyou’llsee,this variable informationfromthetargetserver server codeisresponsibleforrelaying emMicro codeisnotlengthy.It’snot.The would belogicaltoassumethatthe PC andPICemWareapplication. EMIT knowledgetoworkonanembedded of emWare,I’llputthisnewlyacquired fact, onceIfinishwiththehowsandwhys Microchip PICcouldn’tbeatarget.In reason whyanembeddedPCorevena ships withtheEMITSDK.There’sno 8051 based,mainlybecausethat’swhat to afull-blownPentium-basedboard. target canbeanythingfroman8-pinPIC your targetmicroprocessorplatform.The web-server applicationthatresideson Notice thatyoucaninstallclient Let’s startfromthetopdown. One ofthemostinterestingaspects Judging fromthetargetmaterial,it For thisdiscussion,myplatformwillbe The servercode—emMicro—isatiny machine and the gate- tion betweenthe server way code. cessing loadtothegate- offloads someofthepro- server machineand siderable spaceonthe cess oftaggingsavescon- when needed.Thispro- (with emGate by thegateway device vice andareexpanded found ontheserverde- Normally, objects or All ofthisconversa- ′ microtags are levelfor device states. way code) 1998 load allofEMITorjustthepiecesyouneed. Photo 2—Dependingonyourapplication,youcan cation usingthe emMicrocode. server machine andaweb-browserappli- transported bidirectionallybetween the gram productsaregiventheability tobe you wouldwrite. environment thaninanyother program ables, anddocumentsinthe emWare real differenceinfunctions,events,vari- served ondemand.Inasense,there’sno the serverdeviceorHTMLpagesthatare pages thatcontaineitherinformationabout numeric valueofathermistorreading. store thestateofalogicalswitchor or logicalobjects.Forexample,variables sensor inyourbasement. event wouldbethetrippingofaflood particular stateoccurs.Anexampleofan states thatmustbereportedwhen code intoanyapplication. are thestandardjobsorproceduresyou that thedeviceperforms.Thesefunctions Micro codetoeffecttheEMITfunctionality. it toohastobeintertwinedwiththeem- the mainuserapplicationisboss,but emMicro serverinstallation.Ofcourse, ments areallcomponentsofacomplete all ofthelow-levelcommunications. considerations. Inanutshell,emNethandles dard EthernetandRS-485arealsovalid employs. Forlocalimplementations,stan- serial linkisthedefaultmethodthatemNet emMicro andemGateway. handling thecommunicationpathbetween network, emNet.emNetisresponsiblefor way machineisdoneviaalightweight The keyhereisthatallofthese pro- Documents inthiscontextareHTML Variables containthestateofphysical Events consistofatablepredefined Functions aredefinedastheprocesses Functions, events,variables,anddocu- Due toEMITtargetingtheInternet,a THE GATEKEEPER agement. Thegatewaycodeisrespon- provide Internetaccessanddeviceman- another component—emGateway—to data intoabitbucket,emWareuses 60 Rather thansiphonallthatgoodserver APC ware toEMIT. physical hard- that bindsthe is theglue 1—EmitJri Figure Green variable Knob variable Red variable SDK Board CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR server byactingasarepositoryforlarger offload someoftheserviceloadfrom server. mands anddatatofromtheemMicro sible forgatheringanddeliveringcom- EmitJri The gatewaycanalsobeconfiguredto GreenVariable RedVariable PotVariable Green Red Pot Simple applet emAnalogMeter1 emBarDisplay1 emSlider 1 1998 Java filestoeffect thiscommprocess. browser usesemObjects andEMIT-specific from thebrowser.TheemWare-enabled vices areinitiatedviaHTTP commands emMicro serverdevice.emGateway ser- which theusercommunicates withthe server throughaJavaapplet. objects aredefinedandlinkedtothe see alittlelater,controlandmonitorvisual most oftheclientcode.Again,asyouwill conjunction withawebbrowserconstitute Visual Café-definedobjectsrunningin a peekattheclientsideofthisoperation. take usdownafewthousandfeetto emNet toandfromtheemMicroserver. pass dataviatheDLMstructureand included inemWaretoenableDAS browser-based, acommand-lineoptionis the browserlevel. of HTMLandJavaobjectsnotinstalledat objects aswell.TheseemObjectsconsist emGateway canholdandservethese are notpresentatthebrowserlevel, browser. Optionally,ifsomeemObjects server thatservesHTTPrequestsfromthe data toandfromthedevicebrowser. manages theexternalcommunicationof is DeviceAccessService(DAS),which called intoaction.Therecruiterinthiscase for eachprotocolanddeviceis uses RS-232andEthernetservers,aDLM each incomingdevice.Ifyourapplication external device’snetworkconnection. vides port-managementservicesforeach Device LinkModule(DLM).TheDLMpro- emGateway andthisisdoneusingthe server devicemustbemanagedby a lowlevelusingemNet.Eachexternal emMicro, emGatewaycommunicatesat code tootheremWarecomponents.Like tains buildingblocksthatinterfaceits environment you’reworkingwith. able serverresourcesandthenetwork the gatewaycodedependsonyouravail- on theemClientmachine.Whereyouput there. Thegatewaycodecanalsoreside resources, emGatewaycanbeembedded server devices.Ifthehasenough host thatisnetworkedtotheembedded the smallerserverprocessormemoryarea. pieces ofdatathatcan’tbecontainedin The web-browserclientisthemeans by I’m gonnapushthestickforwardand If yourparticularapplicationisn’t emGateway alsocontainstheHTTP A separateDLMcodesetisusedfor As withemMicro,emGatewaycon- emGateway normallyresidesona APC 61 All of the objects are chosen from menu All of the objects are to the later versions of later versions to the Before Visual emWare. in the SDK, Café was included interface and user all of the user by had to be done interface code like. HTML tags and the hand with Visual Café is a lot like using Using Visual Basic. of each object bars, and the properties via a property sheet. can be manipulated are placed, Visual Once the GUI objects code needed Café creates the appropriate to define the objects. PC MBEDDED E 1998 Oops! The next panel states Oops! The want to show as much code as as much code to show want possible. in- have Visual Café that I must use the client develop- stalled to the OK, I just exit ment package. and select the Visual EMIT install I’ll Café install button. Eventually, where we come back and finish install. left off on the EMIT 2.5 COFFEE BREAK Personally, the addition of Visual Café Personally, the addition NOVEMBER NOVEMBER is one of the biggest improvements made is one of the biggest A URL is sent from the browser to the Typically, host, port, device, and docu- At this point, the emMicro-enabled Communication between emGateway’s Of course, the HTTP requests are logi- As we descend, I’ve chosen to select To be a full-fledged emClient, the To be a full-fledged Photo 4—Just think. This all used to be done “by hand.” Photo 4—Just think. This emGateway device. Nothing is different about this URL. It contains address infor- mation needed to target a specific emMicro device in the network. ment names are included in the requesting URL. emGateway’s HTTP server receives the URL request and initiates a connection with the targeted server device. server device responds with the requested document. This document may be micro- tagged. If so, it’s expanded by the microtag expansion services within the emGateway structure. If any of the necessary or re- quested emObjects aren’t on the local browser machine, emGateway serves them, too. DAS and the web browser are arbitrated by EMIT’s Java run-time interface (EmitJri). This link is established via HTTP info from emGateway. The client HTTP module is linked to the emGateway module for HTTP traffic, and a link is formed between the client’s EmitJri interface and the emGateway DAS interface to transfer data to and from the server device. cally linked with the DAS requests so that the two data conduits work together get- ting the requested documents from the emMicro server machine. Looks like the install can continue now, so let’s move on. all of these components offered because I emObjects and the Java-class files must emObjects and the browser machine. reside on the local components Otherwise, if the emWare remote emGateway are located on a machine, the client is no more than a standard web-browser configuration. Now that all the emWare players have been introduced, here’s how it works. name it assign avariablelabeland vice. Tokeepitsimple,Iwill represented ontheserverde- resent thisvariablejustasitis application code.Imustrep- ables sentandreceivedfromtheserver control onthepanel. properties. That’sallthereistoputtinga clicking onitandsettheappropriate Designer window.Selectthesliderby select aslideranddragitontotheForm is toclickontheemSliderstab.Then, walk throughaslidersetup.Thefirststep at thebusinessendofVisualCafé. variables ontheserver.Photo3isalook nism forlinkingthedisplayobjectswith process. Themacrosprovideamecha- are alsopartoftheinitialsetupandinstall initial installofVisualCafé. sual Café,andtheseareinstalledwiththe emWare suppliestheemObjectsforVi- log ordigitalmeters,LEDdisplays. Objects canbeswitches,slidepots,ana- ing objectontheemMicroserver.em- associate eachobjectwithacorrespond- I’ll callthisvariable select itandset its properties. window. Onceitisplaced,I leave itontheFormDesigner is hidden,butforclarityI’ll variable ontheserver. between thesliderandits think ofitasaconduitorpath defined EmitJri,sofornow device usingEmitJri.Ihaven’t the variablesonserver to communicateandfrom 62 Remember theemWareworksonvari- Take agoodlookatPhoto3andlet’s An EMITtemplateandmacros At thispoint,thedeveloperneedonly Usually, thevariablelabel The variablelabelisused APC this screenisallabout. Red physical iswhat . with thevirtual ing thelogical 5—Connect- Photo Red- places. Photo 6—Asyou wouldexpect,thepointandclick generatescodeinalltheright CIRCUIT CELLAR INK NOVEMBERCIRCUIT CELLAR Café tosetupthecodesothat said anddoneinPhoto5,ItoldVisual make mysliderinteractwithit.Afterallis Variable like Bill’sstuff,awizardisconjuredup. and defined,IselectAddInteraction.Just right? OK,let’sfinishwiththelinkup. LEDs isredanditsvariablename EEPROM. Itjustsohappensthatoneofthe LEDs, apot,anRS-232interface,and based platformthatconsistsofacouple will control,I’lltellyou. where time tolinkthem.Ifyou’rewondering and hasbeenassignedavariable,it’s displayed asthe called Red Variable As youseeinPhoto4,Iselected After clickingonthesliderIjustplaced Now itmakesalittlemoresense, The emWareSDKcomeswithan8051- Now thatthephysicalsliderisdefined . Fromnowon,thisvariablewillbe Red RedVariable islocatedandwhattheslider andinstructedVisualCaféto andsetthetextattributeto RedVariable and Red willbe label. 1998 Red- Red- Red . There’s amacroforthat,too— an updatetoEmitJri.The is usedwhenadevicevariableprovides here, butforinquiringminds, the ing theoppositewaythroughEmitJrilike thing Iclickedonordraggedisnowcode. where. Well,checkoutPhoto7.Every- you mightthinkthere’scodeouttheresome- the resultsofactionsIjustperformed. control. Figure1isagoodlogicalviewof Variable Variable SDK boardtogetvaluesfrom code thatenablesthe between EmitJriand pleted. Actually,Iamsettingupalink is whatIsawbeforethecommandcom- Embedded EventListener the serverdeviceandbrowser. external communicationofdatabetween The deviceaccessservicemanagesthe the deviceaccessserviceonemGateway. tween theappletresidesonclientand EmitJri. ThisJavarun-timeinterfacebe- was installedwithVisualCafé. by runningoneoftheEMITmacrosthat on theSDKboard.Thispathisestablished path betweenthesliderandvariable the slidercontrol. Variable For simplicity,Ididn’tgobothways You’re probablywonderingaboutgo- With allthatclickinganddragging, The I shouldtellyoualittlemoreabout For mypurposes,thatmacrois All that’slefttodonowisestablishthe Green Listener or getsitsvaluesfromtheslider wouldgetitsinformationfrom intheclientapplet. Knob that link,allIneed isto way software. To create to connecttheemGate- sary componentsneeded ready hasalloftheneces- this shouldbeasnap. of thepredefinedvariables, plied SDKboardandone it. BecauseIusedthesup- the nextthingtodoisrun simple appletisinplace, code andGUIinfoforour applet’s emObjects. reflected intheclient server tobeautomatically in thevariableson that enablesanychanges macro providesJavacode macroproducesJava The SDKfirmwareal- Now thatallofthe variablesinFigure1. Red RedVariable variableonthe subscribe subscribe subscribe . Photo6 Red- Red- Add . . APC 63 APC.EPC I’ve introduced you to some I’ve introduced the EMIT install By the way, I did finish SOURCE emWare emWare (801) 256-3883 Fax: (801) 256-9267 www.emware.com an embedded-PC gate- an embedded-PC a remote web way serving browser. high concepts at a of the emWare tree- time, I’ll drop to the level. Next it takes turkey about what tops and talk put our PIC on the under the covers to network. at Visual Café. while you were looking technology from Thus, modern software again proven that it emWare has once complicated to be doesn’t have to be embedded. years’ experience Fred Eady has over 20 He has worked as a systems engineer. with computers and communication sys- tems large and small, simple and com- plex. His forte is embedded-systems de- sign and communications. Fred may be reached at [email protected]. PC MBEDDED E 1998 The final product of this discussion will NOVEMBER NOVEMBER be a PIC-based micro server attached to PICING UP WHERE WE LEFT OFF then other parts of the program could lose or miss information they need to make their program-related decisions. If a pro- gram segment was waiting for incoming asynchronous data and the switch seg- ment was looping…well, you can guess what happens. Photo 7—You want code? There it is. Photo 7—You want code? The basis to any emWare appli- The basis to any emWare For example, let’s say your application Although the emWare 101 Although the emWare cation is round-robin multitasking. cation is round-robin Simply put, this scheme gives all the parts of an application equal access to the processor resources. It means that no one part of the application should seize the processor resources for any abnormal length of time. had to read some push-button switches to make a decision. If your program polled the switches in such a manner that the routine loops until a switch was released, course you just took was very rudi- course you just took can see the mentary, I think you emWare is possibilities that exist. into your ap- designed to integrate a layer by plication and provide over virtu- which you can connect network. ally any TCP/IP-based PREPARING TO PROGRAM PREPARING start the emGateway application. the emGateway start the is started and Once emGateway up, I can execute SDK is powered directly from the Visual my applet Café application. DEPARTMENTS Digital MICRO 64 MicroSeries Processing in SERIES

David Tweed 72 From the Bench an Analog World 78 Silicon Update Technology Choices

n Part 1 of this i series, I covered some of the basic concepts associated with analog-to-digital and digital- This month, to-analog conversion, including quanti-

Part 22 zation and sampling, plus some of the of David dis- things that make a real-world converter 3 deviate from the ideal performance. 3 cusses the This time, I take a look at several converter technologies and compare pros and cons of several their strengths and weaknesses in terms of the performance characteristics I converter technologies discussed, as well as other consider- ations such as cost and complexity. in terms of performance, I’ll start with the conceptually simpler technologies such as flash cost, and complexity. ADCs and R-2R DACs and then move on through switched current, dual- He covers everything slope, successive approximation, and pulse-width modulation. Along the from basic flash ADCs way, you should develop a feel for where and why each technology has to PWM, so we know traditionally been applied and which where to turn for our one is best suited to your application. FLASH ADC applications’ needs. The flash ADC is basically a brute- force implementation of the theoretical ADC, because for an n-bit converter, 2n – 1 analog comparators are used to compare the analog input directly and simultaneously to voltages representing the decision points. The decision-point voltages are generated by a resistive divider of 2n resistors connected between two voltage sources representing the lower and

64 Issue 100 November 1998 Circuit Cellar INK® upper limits of the desired conversion b) range. The basic structure is shown in a) T7 T6 T5 T4 T3 T2 T1 b2 b1 b0 Input 0 0 0 0 0 0 0 0 0 0 Figure 1a. 2n – 1 0 0 0 0 0 0 1 0 0 1 +V comparators The comparators generate 2n – 1 bits ref 0 0 0 0 0 1 1 0 1 0 T(2n) of information in what’s commonly R + 0 0 0 0 1 1 1 0 1 1 – 0 0 0 1 1 1 1 1 0 0 called thermometer code—all of the 0 0 1 1 1 1 1 1 0 1 R + T(2n –1) comparators below the input voltage 0 1 1 1 1 1 1 1 1 0 – 1 1 1 1 1 1 1 1 1 1 produce ones, and all of the comparators R + T(2n – 2) above produce zeros. A table of this n-bit – encoder binary triple code for a three-bit converter is shown 2n c) 2:1 mux resistors in Figure 1b. Logic is required to reduce T7 + T(2) T6 this code to the n-bit binary code that R 2:1 mux – T5 is desired. T4 R + T(1) The logic to perform the conversion T3 – T is quite simple, as you see in Figure 1c. 2 R T1 Note that the middle column of the B –Vref 2 table is identical to the most significant B1 output bit you want to generate. This B0 bit splits the table into two halves, each of which contains a copy of a Figure 1a—Here is the block diagram of a flash ADC that directly implements decision levels. b—The thermometer- to-binary conversion table shows the symmetry that leads to the conversion logic. c—The conversion circuit is a smaller table with half as many rows. series of multiplexers, with optional pipelining shown by the dashed lines. The middle column of this new table is the same as the next most mitigated somewhat by carefully laying R-2R DAC significant output bit, and so on. Repeat out the resistors on the chip so that One of the simplest forms of DAC this process until the last multiplexer manufacturing tolerance issues (e.g., is known as the R-2R network, shown is just one bit wide, and outputs the mask alignment) affect all of them in in Figure 2a. An n-bit converter can be least significant bit. The output logic the same way. built from 3n resistors of all the same is a series of 2:1 multiplexers, each Because this type of converter typi- value, making it quite attractive for one controlled by the middle output cally only makes sense in very high- low-cost discrete implementations. bit of the previous stage. speed applications, several dynamic To understand how the R-2R net- The biggest advantage of this tech- issues come into play. One issue is work operates, recall how a voltage nology is its extremely high speed. If the problem of distributing the input divider (a voltage source and two you put pipeline registers at the outputs signal to all of the comparators. resistors) is exactly equivalent to a of the comparators and multiplexers, The capacitive load of all those circuit consisting of a single voltage the cycle time is limited only by the inputs is considerable, and any buffer source in series with a single resistor. time it takes the comparators to settle amplifier that gets inserted into the This equivalency is known as the and the registers to capture the outputs. path must be fast, stable, and capable Thevenin equivalent of the original The data reduction takes n – 1 addi- of driving large currents. Also, the circuit. (There is also a Norton equiv- tional clock cycles for n output bits, propagation delay of the comparators alent, in which the original circuit is but this affects only the converter’s must be well matched, and the pipeline replaced by a current source in parallel latency (delay), not its throughput. clock must be distributed to all of the with a resistor.) Flash converters usually operate in the registers with low skew. The Thevenin voltage is calculated 100-MHz to several-GHz range, provid- As a designer of a system incorpo- by the normal voltage divider equation. ing between 6 and 10 bits of resolution. rating these converters, you should be The Thevenin resistance is calculated The big disadvantage to flash con- prepared to deal with the huge volume as the parallel combination of the two verters is the circuit complexity. Be- of data they produce. This means wide original resistors, as shown in Figure 2b. cause of the complexity and the heavy buses running at extremely high speeds. Now, consider the first bit of the reliance on perfectly matched compo- Board-level signal integrity is of para- R-2R network, shown in Figure 2c. nents, only monolithic (single chip) mount importance. Depending on the state of the switch, implementations make sense. For Several gigasamples-per-second this bit forms a voltage divider devel- × × each additional bit of resolution, the converters are available (typically oping 0 Vref or ½ Vref. In either number of comparators and latches used in DSOs). Triple 6–8-bit devices case, the Thevenin resistance is the must double, which drives up both are available for TV-resolution video same: chip area and power consumption. applications (typically 14.31818 MS/s 1 =R The linearity of the converter is [mega-samples per second]). Analog 0.5R + 0.5R directly related to how well the indi- Devices announced a triple 8-bit, vidual resistors of the divider chain 300-MS/s device for high-resolution If I now connect this equivalent are matched. This relationship can be video displays that costs about $25. circuit to the next bit, as shown in

Circuit Cellar INK® Issue 100 November 1998 65 Figure 2d, it’s easy to see that this makes it useful in applications like so keeping them operating in a linear forms another voltage divider, again digital volume controls and in op-amp fashion is easy as well. with resistance 2R on each side. The feedback networks. The key to good performance in bottom end of the divider connects to these converters is that all of the × × either 0 Vref or ½ Vref, while the SWITCHED-CURRENT DAC transistors in the current mirror and × × upper end connects to 0 Vref or 1 Vref. The switched-current DAC uses a switching currents must be carefully If you work out all the combinations, technique that is best suited for mono- matched for their performance charac- you find that the Thevenin voltage of lithic (single-chip) implementations. teristics (e.g., threshold voltage and × × × this circuit is 0 Vref, ¼ Vref, ½ Vref, A variation of the R-2R network or a current gain). Also, they need to oper- × or ¾ Vref. Once again, the Thevenin circuit called a current mirror (and ate in the same environment as far as resistance is simply R. You can add as sometimes a hybrid of both techniques) supply voltage and temperature, which many bits as you like, and the output is used to divide a reference current makes monolithic fabrication the resistance will remain R, and the into ever-smaller streams. Then, elec- logical choice. output step size will be: tronic switches combine these streams The main advantage of this kind of to form the desired output value. converter is its relatively low cost, Vref Figure 3 shows the general scheme. which results from the relatively low n 2 A reference current is supplied at complexity and small die size. An- I’ve shown the drivers of the R-2R the top, which gets successively di- other advantage is its relatively high network as switches for simplicity, vided in half. The output currents are speed, controlled mainly by how fast but they could just as well be a set of switched onto one of two rails depend- the switches operate, especially when output bits from a microcontroller. ing on the state of the corresponding bit. the desired output is a current value. The important thing is that the drivers Each rail carries the sum of the However, the high speed can turn should have much less resistance than currents switched onto it, with the Io into a disadvantage when an output 2R. If not, their resistance should be rail carrying a current proportional to voltage is desired, because the current – well matched in both the low state the digital code and the Io rail carrying source has a very high effective output and the high state and to each other, the remaining current, which corre- impedance (an ideal current source and the 2R resistors should be reduced sponds to the complement of the digital has an infinite impedance). If there’s in value to compensate. code. Each current needs to be returned any stray capacitance at the summing

The biggest problem with this kind to ground. Normally, the Io rail drives node of the converter, as shown in of converter is matching the resistor a current-to-voltage converter imple- Figure 3, this becomes a relatively slow – values closely enough—you need mented with an op-amp, while the Io R/C low-pass filter that slows down tolerances on the order of 0.1% for a is returned directly to ground, some- the transition speed of the converter. 10-bit converter. You also need to be times through a load resistor. aware of the output resistance of the Because the currents are flowing DUAL-SLOPE ADC bare resistor network, adding an output through the current-dividing network A dual-slope ADC operates by trans- buffer when necessary. in the same way all the time, regard- lating an unknown amount of current One big advantage of this converter less of the positions of the switches, into a time period and then measuring is that the output is a simple multipli- it’s relatively easy to keep them oper- it. The key element of this kind of cative factor times the input voltage, ating in a stable and accurate manner. converter is an analog integrator that which itself can vary or even change Also, the voltages across the switches integrates the unknown current for a sign if the drivers allow it. That are very low and constant at all times, known amount of time, and then the

a) Vref c) Vref

Gnd Gnd V 0⁄ out 2 × Vref 2R 2R 2R 2R 2R R R R R ½V Vout ref 2R 2R

Figure 2a—The R-2R converter b) d) Vref 300 Ω 120 Ω can be built from switches and + + resistors. b—A network of voltage Gnd Vout + + 0⁄ 4 × Vref sources and resistors can be V Vout 2R 1⁄ R 5 V200 Ω out 2 V 4 × Vref – R 2⁄ reduced to a Thevenin-equivalent – 4 × Vref Vout – – 0⁄ 3⁄4 × V circuit. c—The equivalent of the 2 × Vref ref or R first bit has a constant resistance 1⁄ 2 × Vref R. d—Analyzing the second bit is easier using the Thevenin equiva- lent of the previous bit.

Circuit Cellar INK® Issue 100 November 1998 67 integrator is discharged by a A refinement of this circuit, I known reference current while ref R R known as the triple-slope converter, Iref 2R Iref measuring the time required for ⁄ 8 adds an extra phase between the current I the output to reach zero again. mirror ref⁄2 2R 2R 2R first and second phases during which I current Iref⁄ Iref⁄ ref⁄ A digital counter running at a I 2 4 8 the integrator input is grounded mirror ref⁄4 constant rate measures the time current and the capacitor is connected in mirror period. An unknown voltage is I the opposite polarity. This phase ref⁄2 I Current-to-voltage ref⁄4 Iref⁄ easily turned into a current by 8 converter basically operates the integrator in Iref⁄ R applying it to a precision resistor. 8 FB the same mode as the original I0 Virtual The block diagram of a dual-slope Ground second phase but with the direction + V = –R × I converter is shown in Figure 4a, – out FB 0 of integration reversed. and the corresponding timing is – This phase also lasts as long as I0 Stray shown in Figure 4b. Gnd Capacitance it takes for the counter to overflow. The dual-slope converter oper- It allows the integrator to accumu- ates in three phases. During the Figure 3—The switched-current DAC directs fractions of the late a charge that represents the reference current to one of two summing nodes. The inset shows first phase, the switch SW is offsets and leakage currents in the a how an R-2R network divides a reference current if all outputs are at closed, which resets the integra- ground or virtual ground. analog circuitry, which then cancels tor to zero voltage, and the digital out those same errors in the next counter is reset at this time as well. grator and applying a fixed current of phase—the measurement phase.

During the second phase, SWa is the opposite polarity. The counter When carefully constructed, this opened and SWb is closed, applying starts counting from zero again, and type of converter can yield very high the unknown voltage/current to the its value is latched when the inte- resolution and accuracy. Also, the integrator for a fixed period of time grator’s output reaches 0 V again. relatively simple structure requires controlled by how long it takes the The time for this process is directly relatively low power, which makes it counter to overflow. proportional to the integrator voltage suitable for battery-powered applications

During the third phase, SWb is at the beginning of the third phase, like digital multimeters. opened and SWc is closed, removing which is directly proportional to the So-called 3½-digit meters (2000 the unknown current from the inte- original unknown voltage or current. counts) are quite common and represent

68 Issue 100 November 1998 Circuit Cellar INK® Figure 4a—The schematic of the a) C b) Integrator dual-slope ADC shows the simple voltage SWa To switches analog circuitry. b—The conver- SWb A B C sion is performed in three phases. –Vunknown R + +Vref + SW – Control c – logic

Integrator Overflow Time Comparator Reset Clock Counter Reset Unknown slope, Fixed slope, fixed time measure time

Latch

To display or microprocessor

about 11 bits of binary resolution. One trick is to make sure the inte- is the difference between doing a lin- Laboratory-grade instruments of six or gration period is an exact multiple of ear search versus a binary search—the more decimal digits (1,000,000 counts) 100 ms. Doing so makes the integration time required is 0(log(n)), the number are available and represent about 20 bits period an integer number of periods of of bits, rather than 0(n), the number of of binary resolution. 50 and 60 Hz, canceling out nearly all counts. A block diagram of a succes- One disadvantage is the relatively sources of power-line interference. sive-approximation ADC is shown in long conversion time—on the order of Parts are available with BCD outputs, Figure 5a. hundreds of milliseconds—which which are preferred for direct metering, The concept is simple: The unknown allows only a few measurements per and binary outputs, which are preferred quantity is applied to one side of a second. However, this conversion time for microcomputer applications. comparator, while a known quantity is quite acceptable in a digital meter, generated by a DAC is applied to the and the long integration time has the SUCCESSIVE APPROXIMATION other. Digital logic monitors the results beneficial side effect of filtering out The difference between a dual-slope of the comparison and generates codes most forms of noise. and a successive-approximation ADC to feed to the DAC.

Circuit Cellar INK® Issue 100 November 1998 69 The algorithm divides the con- a)Comparator b) Max verter’s range into two equal halves Vin + by initially setting the DAC to the Successive Start Vref DAC – approximation Clock Done DAC middle of the range. The result of this register (SAR) voltage n bits comparison—a 1 if the unknown is in output Input the upper half, a 0 if it is in the voltage lower—eliminates half of the range from consideration. The DAC is set to the middle of the remaining half of the range, and another comparison is made. As this process 1 0 1 1 1 0 continues, the DAC’s output becomes Output value a better and better approximation of Figure 5a—The successive approximation ADC uses a the unknown value. When the process DAC in a feedback loop to zero in on the unknown input. is complete, the code then being fed b—A binary search successively halves the range in which the unknown can lie. to the DAC is the best approximation 0 V ATimeBCDEF of the input value, and it becomes the output value of the conversion. Figure 5b shows the timing sequence paired up with a sample/hold circuit For example, 8-bit resolution at a of a successive-approximation conver- to address this problem. sample rate of 8 kHz requires a clock sion. At the first step, the DAC is set of 2.048 MHz, and 16-bit resolution at to one-half full scale, and the compara- PWM DAC 44.1 kHz (CD quality) requires a clock tor indicates that the input voltage is The pulse-width modulator (PWM) of 2.89 GHz! So, this type of converter somewhere above that, shown by the is a simple form of DAC with many tends to be used in low-speed applica- shaded region. This setting also means positive features. It works on the prin- tions (e.g., process control) in which that the most significant bit of the ciple that switching rapidly between conservative filters can be used. digital code will be a 1. two fixed values with a variable duty The big advantage of the PWM is At step two, the DAC output is set cycle and then taking the average over that the circuitry is nearly all digital, to the middle of the upper range, and time can generate an analog value. and the analog output filter is often the comparator indicates the voltage Figure 6 illustrates a PWM and the nothing more than a passive R/C low- is less than that. The second bit of the timing of its operation. A free-running pass filter. These qualities enable the result will be a 0, and once again the digital counter feeds one side of a converter to be easily integrated with DAC output is adjusted to the center digital comparator, while the desired other digital logic, and in fact, many of the narrower range. This process digital output code is fed to the other. single-chip microcomputers are avail- continues, subdividing the range con- The comparator’s output is high able with PWMs built in, making it taining the input value until all of the when the counter value is less than the preferred DAC technology in ex- bits of the output code are generated. the code value. Higher codes mean tremely cost-sensitive applications. It’s important that the input voltage you have high output for more of the Another advantage of the all-digital doesn’t change during this process. time. One output pulse is generated active circuitry is that the linearity of Particularly if the voltage moves out for each complete cycle of the counter, the converter is virtually guaranteed. of the range under consideration early so the sample rate is effectively the The only sources of errors are the pas- in the sequence, it becomes impossible counter’s clock frequency divided by sive filter components, which tend for the converter to come up with a 2n, where n is the number of bits in not to have linearity problems, and correct code—the remaining bits will the counter and the code word. the timing of the edges of the PWM be all ones or all zeros as appropriate. Even moderate sample rates and waveform, which is easy to control. This converter technology is often resolution can require high clock rates. One disadvantage is the fact that the raw output has a strong tone or carrier signal at the sample rate and at a)Clock Counter b) 5 harmonics of the sample rate, and the A High when output filter needs to have strong A < B Digital V comparator out attenuation at those frequencies in n bits B 0123456701234567012345670 order to eliminate them. input Time If a simple analog filter is going to Low-pass filter be used, the sample rate must be much higher than the Nyquist limit would imply. Or conversely, the signal band- Figure 6a—A pulse-width modulator is nearly all digital circuitry. b—The PWM generates one output pulse for each full cycle of the counter. Showing the digital values of the counter (stairstep) and input code (dashed line) graphically width must be kept much lower than makes it easy to see how the output waveform (lower trace) is generated. half the sample rate.

70 Issue 100 November 1998 Circuit Cellar INK® CHOOSE A CONVERTER Analog Devices, Inc. Fax: (408) 434-0507 I’ve covered a few basic converter (781) 937-1428 www.linear-tech.com technologies so you can choose the Fax: (781) 821-4273 Maxim Integrated Products right one for your application. I’ll wrap www.analog.com (408) 737-7600 up by looking at delta-sigma converters Analogic Corp. Fax: (408) 737-7194 and why they’re the hot area of devel- (978) 977-3000 www.maxim-ic.com opment these days. I’ll also cover the Fax: (978) 531-7356 I whys and hows of using dither. www.analogic.com National Semiconductor Corp. (800) 272-9959 Burr-Brown Corp. David Tweed has been developing (408) 721-5000 (520) 746-1111 hardware and real-time software for Fax: (408) 739-9803 Fax: (520) 746-7401 microprocessors for more than 22 www.national.com years, starting with the 8008 in 1976. www.burr-brown.com His system design experience includes Cirrus Logic/Crystal Semiconductor NEC Electronics, Inc. computer design from supercomputers (512) 445-7222 (408) 488-6000 to workstations, microcomputers, Fax: (512) 445-7581 Fax: (408) 488-6130 DSPs, and digital telecommunications www.cirrus.com www.nec.com systems. David currently works at Datel, Inc. Philips Semiconductors Aris Technologies developing digital (508) 339-3000 (800) 447-1500 audio watermarking. You may reach Fax: (508) 339-6356 (408) 991-5207 him at [email protected]. www.datel.com Fax: (408) 991-3773 Exar Corp. www.semiconductors.philips.com SOURCES (510) 668-7000 Texas Instruments, Inc. Fax: (510) 668-7001 AKM Semiconductor, Inc. (800) 477-8924, x4500 www.exar.com (408) 436-8580 (972) 995-2011 Fax: (408) 436-7591 Linear Technology Corp. Fax: (972) 995-4360 www.akm.com (408) 432-1900 www.ti.com

Circuit Cellar INK® Issue 100 November 1998 71 output commands any of these notes FROM THE on, the MIDI animator turns the ap- MIDI propriate output on. And, when the MIDI output commands any of these BENCH notes off, the MIDI animator turns the appropriate output off. The third byte of the command holds special information about that Jeff Bachiochi note, known as velocity. Here’s where things get interesting. You can think of velocity as how hard a note is hit. If the note is hit softly, the third byte holds a low value. If it is hit hard, the Part 2: The Show Must Go On third byte holds a large value. In addition to the PIC’s outputs going high or low, the velocity value can indicate an amount of high/low. This analog amount can be output in one of two ways—either PWM based on 60 Hz or a modified PWM used for servo motors. A configuration input determines the type of output used on The ast month, we each of the 14 digital outputs. l were learning a bit show about the MIDI music PWM control protocol and how With most adjustable AC control, must go a bit of hardware can capture the com- you have to be careful. If the control mand sequences, when we suddenly output isn’t in sync with the line, there on, and smashed right into the end of the will be some modulation AC output at column. a rate equal to the difference between so does Remember that the MIDI protocol the line frequency and control output. defines events like note on/off, tim- To eliminate this beating, all 14 Jeff as he finishes his ing, and synthesizer presets to recre- outputs must be in sync with the line’s ate performances that were recorded zero crossings. One of the PIC’s inputs MIDI animator project. live or written as a musical score. (see Figure 1, INK 99, p. 78) is used as Since both timing and note informa- a zero-crossing input providing a rising After discussing MIDI tion is stored in a MIDI file, it seemed and falling edge in which all the timings like a practical front end to a digital can be based. control, Jeff completes control system. Thus was born this Each AC cycle has two crossings, project, the MIDI animator. 8.33 ms apart. Therefore, all control the performance by MIDI files can hold information for must be done within that time frame. up to 16 instruments. So, this project Since the velocity value will be 0–64, showing how lighting has configuration jumpers for selecting we’ll break this 8.33 ms into 65 parts, which of the 16 instrument commands with each part lasting 128 µs. engineers can get in to listen to. The most common AC control Next, only two commands are of device is the triac. The triac can be on the act. interest—the 80H command for note turned on anytime within each half off and the 90H command for note on. cycle, and it turns off automatically at When one of the commands is decoded the next zero crossing (provided the from the MIDI output’s 32,768-Hz gate control has been removed). serial datastream, the following two The velocity value received for any bytes are saved along with the first. specific note (output) determines when The second byte indicates the note (i.e., during which of the 65 cycles) the being turned on or off. Only 14 of the output will be switched high. The 128 possible notes are acted on. The higher the value, the sooner it will be remaining are tossed out. turned on. The PIC16C63 has 14 outputs dedi- When the value is 64, it remains on cated to these notes. When the MIDI throughout all cycles. When the value

72 Issue 100 November 1998 Circuit Cellar INK® is zero, it remains off through- When it overflows, it is out all cycles. When the value reloaded with a value for 30-µs Clamped AC input is 32, it is turned on half way interrupts. The next 33 inter- through each cycle. Potential 64 60 50 40 30 20 10 0 rupts check the velocity values table values Timer2 is used as the PWM stored in the note table. When 128-µs 8.192 ms timer. It restarts at each zero Timer2 the value in the table equals 8.333 ms crossing so the timing stays in interrupts the interrupt count, the appro- sync with the line. When Timer2 PWM output for a table value of 50 priate output is turned off. matches the period register After the thirty-third inter- (every 128 µs), an interrupt is rupt, the next output pair is triggered. Figure 1—The upper trace shows one-half of a 60-Hz cycle. The middle turned on. The correct pulse Depending on how close to trace illustrates the 65–128-µs parts of each half cycle. The bottom trace output is created based on the shows a PWM output of the value of 50. 60 Hz your line frequency re- table entries for these outputs. mains, you can adjust this value to between extremes in tenths of a second. In the meantime, the UART is being assure you remain at less than a half I chose to use the same cycle time as serviced and the note table is being cycle for all 65 periods. Reducing this the previous PWM mode—60 Hz. updated. By the time all seven output number means you can withstand more This task is accomplished by con- pairs are processed, 16 ms have gone deviation in line frequency. However, trolling pairs of outputs in sequence. by and the next zero crossing starts the control at the minimum values It was a trade-off between time within the whole process all over again. will be a bit distorted. the execution loop and waiting time The interrupt routine decrements a for the next loop. Potential characters SERVO MECHANICS time frame count (starting at 65) and could come in every 300 µs. Dividing Servos have three connections— compares it with the velocity values 1 ms into 65 parts gave me only 15 µs power, ground, and control inputs. The for each output (held in a look-up table). between each interrupt. internal circuitry uses a geared-down If the values match, the appropriate I needed to execute through the DC motor to turn an output shaft. A output is set. interrupt loop fast enough to allow feedback potentiometer tells the motor- The outputs are reset after the sixty- plenty of time to process incoming drive circuitry where the shaft is. fifth Timer2 interrupt (see Figure 1). characters and still get back for the The motor-drive circuitry compares Now the code just idles (but not for next interrupt. I found that my inter- the pot’s analog output to the duration long) until the next zero-crossing edge rupt execution took about 20 µs, which of the input pulse. The motor is driven and the pattern is repeated. left –5 µs and no time for the UART until the shaft turns the pot, so the two The circuit I used contains a power handler. I had to compromise. signals obtain equilibrium. Servos are supply running off of 120 VAC. I put I decided to divide the velocity value complicated little modules when the circuit right on the board giving in half and only have 33 parts to the compared to their low cost. They are me access to AC, which enables sync servo’s modified PWM output. This available for about $15–50, each with with the line. decision gave me a 10-µs overhead for torque on the order of 30–200 oz.–in. I used the change of state input to the UART handler and still allowed a Hardware included with the servo create the 120-Hz interrupt clock. If 60° servo control to a resolution of 2° enables it to be used in almost any you don’t need that, the system will (see Figure 2). application where it either pushes or use Timer0 as a 60-Hz source. The Timer2 is for the servo interrupt. pulls through various linkages. You initialization routine looks at the zero- When the zero-crossing interrupt hits, might use servos to animate robots, crossing input to determine whether the first pair of outputs is set high and puppets, props, or kinetic artwork, to stay synchronized to the line or the Timer2 is loaded with a value that and they can control many kinds of internal oscillator. will give the initial 1-ms output. scale-model layouts as well.

SERVO CONTROL Radio-control models gave us low- cost servo control. These servos’ input Clamped AC output Potential is based on a modified PWM output table values 0 8 23 32 0 32 Timer2 pulse. The servo input must be 1–2 ms interrupts 1 ms 30 µs 992 µs in duration. A 1-ms pulse is the mini- 1.992 ms 1.992 ms mum duty cycle, and a 2-ms pulse is a Servo pulse for a table value of 23 Table value of 0 maximum duty cycle. Output 1 (first pair) Output 33 (seventh pair)

You can command the servo to Table value of 8 Servo pulse for a table value of 32 move between minimum and maxi- Output 2 (first pair) Output 14 (seventh pair) mum rotation by varying the duty cycle between 1 and 2 ms at a refresh Figure 2—During each AC cycle (top trace), seven pairs of outputs are updated sequentially based on a 2-ms rate of 30–100 Hz. Most servos rotate maximum time/pair. Servo outputs are on for a minimum of 1 ms.

Circuit Cellar INK® Issue 100 November 1998 73 LINE-SUNK PWM Of course, the digital outputs of the MIDI animator can be used to control a variety of equipment. DC mechanical relays can be driven using a single noninverting open- collector buffer (i.e., 7407). Many times, optocouplers are used with simple single-transistor output for speed or Darlington output for extra drive capability (see Figure 3). Solid-state relays are quite popular in eliminating mechanical bounce and contact pitting. Most useful, however, would be proportional high-voltage control. Not only can solid-state SCR or Figure 3—Here are three ways of controlling a DC voltage: triac drivers be used to turn high- mechanical relay, output transistor, or solid-state relay. voltage AC on and off, but PWM waveforms sunk to the line will give triac drivers (really sensitive gate triacs proportional control. with limited current drive, usually a Although small-signal triacs can be 100-mA maximum) are used to switch driven directly from TTL outputs, most on larger triacs. Triacs are capable of designers use an optocoupled driver to controlling very high currents, and keep the AC and DC circuitry separated because of the power dropped across (see Figure 4). They’re not only small these triacs, heat sinking is a necessity. and inexpensive, but they’re also eas- Let’s look at what happens when ily obtainable and second sourced by triac control is not sunk on the line. many manufacturers. But first, there is a difference between Standard triacs can require 50 mA solid-state relays (triac control with of current to turn on. Optocoupled zero-crossing detection) and control that is sunk to the line. Solid-state relays with zero-crossing detection pay attention to the line voltage and only allow the relay to be turned on at zero crossings. This characteristic prevents large in-rush currents and noise spikes from being produced when the control asks to turn the triac on at other than zero crossings. Fast ∆v/∆t edges are noisy. The built-in zero-crossing detector eliminates these by delaying the turn on until the next zero crossing. The disadvantage of these devices is that they can’t be proportionally controlled. To proportionally control the triac, we must be able to turn it on at any point throughout the cycle. The solid-state relay that has built-in zero crossing prevents this from happening. Now, let’s see what synching to the line gives us. The most obvious result is that we can perform the same kind of zero-crossing hold-off that is built into some opto devices. This Figure 4—Here are three ways of controlling an AC voltage: nonisolated triac, optoisolated triac, and solid- ability is good for turning solid-state state relay. relays on and off quietly.

Circuit Cellar INK® Issue 100 November 1998 75 HVAC

Zero-crossing input line sync 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms Triac control and HVAC result

Internal 120-Hz timer 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms 4 ms Triac control and HVAC result

Figure 5—The second and third traces show a PWM output, which is in sync with the HVAC waveform. The fourth and fifth traces show how the PWM output no longer stays in sync with the line, based on a nonsynchronous oscillator.

But, the main use of this ability is So, I’ve given you a way to play to keep the proportional control signal around with MIDI control using some in sync with the line, so the device is software you may have received with turned on at the same point in each your PC’s sound card and some hard- cycle. Otherwise, you see a beat modu- ware you can easily build from scratch. lation as a pulsing of the output (see If you want more, check out MIDI Figure 5). show control. This spin-off is used for For example, when the control loop controlling theatrical and live perfor- is running at 55 Hz, the beat frequency mances, multimedia displays, audio- is 5 Hz (the difference between 60 and visual displays, and the like. 55 Hz). As the two become closer, the Although the format is quite similar beat frequency drops, but if the two to that of MIDI, tools for experimenting are not exactly the same, you get an with it are expensive. Companies that annoying pulsing. Although this differ- manufacture MIDI show-control hard- ence is mandatory for creating cool ware often have their own tools. You lissajous patterns, it’s unwanted here. can visit the many sites I’ve found to learn more about them. I ENCORE To finish this project, I wanted to Jeff Bachiochi (pronounced“BAH-key- give the people who do stage lighting AH-key”) is an electrical engineer on for concerts a chance to come into the Circuit Cellar INK’s engineering staff. spotlight (so to speak). So, I added opto His background includes product design triac drivers to each of the 14 outputs and manufacturing. He may be reached on the MIDI animator. at [email protected]. Each output drives a separate colored spotlight. The gel filters are arranged REFERENCES such that the lowest notes begin in www.show-control.com/txt/ the violet part of the spectrum, and mscspec.txt the highest notes are at the red end. www.harmony-central.com The notes in between correspond to www.midifarm.com/info/ their respective part of the spectrum. pcutilities.asp Finally, a synthesizer with MIDI out- ourworld.compuserve.com/ put serves as the controller. homepages/jhuntington The lighting engineer can now join the band on stage, performing with SOURCE shades of color that accent the music. Presuming the synthesizer’s sound is PIC16C63 off, the lighting designer can bang on Microchip Technology, Inc. that thing, mixing colors without (602) 786-7200 having to worry about being tone deaf. Fax: (602) 786-7277 That’s real performance art, huh? www.microchip.com

76 Issue 100 November 1998 Circuit Cellar INK® to own and operate, they’re allowed to use the carpool express lanes, and you SILICON can always find a parking space. But, the most compelling advantage UPDATE is speed! At the time, my 750 was faster off the line than practically any car on the road. The inspiration for this thread is Tom Cantrell the appearance of the SX MCU from startup Scenix Semiconductor. Like a bike, it’s small, relatively inexpensive (under $4 in small quantities), and most important, fast. I’m talking close to Socket Rocket 50 MIPS, which is a good 10–50 times faster than typical 8-bit MCUs.

EASY RIDER It’s no problem finding parking for the SX, which is offered in a variety of small packages from 18 to 28 pins, including DIP, SOIC, and SSOP. It isn’t finicky about fuel either, running The SX ike other places, on anything between 3.3 and 6.25 V. It l Silicon Valley goes gets good mileage, consuming about MCU from through booms and 1 mA/MHz at full throttle and mere busts. The only difference microamps when idling. Scenix is is that single-digit growth is considered Take a close look at the motor (see a bust, while startups routinely post Figure 1). Those of you familiar with fast, runs triple- or even quadruple-digit gains. Microchip PICs will notice a striking The boom of the last few years, similarity. Indeed, the SX goes out of on almost fueled by I-way frenzy and bloatware- its way to offer PIC16C5x socket driven PC upgrades, has been one of compatibility. anything, gets good the strongest ever (even though it’s The novel in-system programming fading a bit in the stretch). It’s a veri- scheme (using the OSC pins) for the mileage, and you can table gold (err…silicon?) rush. onboard 2K × 12 program flash is One of the consequences is traffic supplemented with a parallel program- park it anywhere. with a capital “T”. Ever fly into San ming mode similar to the PIC’s, with Jose at 5:00 P.M., rent a car, and try to a slightly different algorithm. And, Parallax’s SX- go somewhere?—anywhere? I don’t It’s possible to configure an SX as a commute, but I get out enough to see PIC clone, but it probably doesn’t Key makes for some just how ugly the jam-up is. make much sense. Alhough it’s not expensive, there’s no way an SX is easy riding. Will we THE NEED FOR SPEED going to compete price-wise with the In my opinion, the ideal vehicle for much higher volume PIC. be seeing biker bars our dart-and-weave stoplight-to-stop- light jousting is a motorcycle. Now, a in Silicon Valley? bike isn’t suitable for everything— certainly not big jobs like hauling the brood around or moving furniture. I also understand the objections from those of you who live in colder climes. And, there’s the danger factor, though two-wheel advocates argue that slow mummification behind the wheel isn’t a real pleasant way to go either. I rode a bike years ago when I was a commuter for the same reasons I give Photo 1—Like the SX, the SX-Key development tool today. They’re relatively inexpensive from Parallax packs a lot of punch into a small package.

78 Issue 100 November 1998 Circuit Cellar INK® In fact, after considering the plethora a) b) of good 8-bit micros (including flash- based) on the market, two features stand out as compelling advantages for the SX—performance and innovative, low-cost, easy-to-use development tools.

ZIPPING IN AND OUT The secret to SX performance is simple, relying as it does on the tradi- tional technique of pipelining. The four-stage pipe in Figure 2 is a classic, Photo 2—Included in the Master Key packages, Parallax offers a QuickProto board (with Master Key 18 package, or similar to those found in earlier (but $69 separately) and DemoBoard (with Master Key 28, or $99 separately). typically larger, like 32-bit) machines. There is one, and only one, reason Harvard design (separate program and For pins configured as outputs, the to use a pipeline and that’s to boost data memory). SX reads the actual pin level, not the the clock rate, which ultimately is Given the complication involved, output latch. I think the SX approach limited by memory access time. IREAD requires the same number of is superior because it enables the In compatibility mode, the SX clocks (four) in both compatibility and detection of external problems such as reverts to four clocks per instruction turbo mode. But, it’s faster than previ- a shorted or excessively loaded pin. (eight for JMPs and CALLs), same as a ous data-lookup schemes and can It’s easy to confirm that the output- PIC. Flip the turbo switch, and the access the entire code space. pin level is or isn’t what it’s supposed pipeline kicks in. Pipelined machines are also subject to be. By contrast, reading the output Once filled, the pipe delivers close to various hazards that must be obvi- latch, rather than the pin, leaves you to one instruction per clock. However, ated by hardware, software, or both blind to outside interference. as with all pipelined machines, there (e.g., the problem of trying to read As a consequence, a write to a port are some caveats to be aware of. data at the same time it’s being written). may not propagate through to the pin The JMP and CALL penalty is rela- Consider a sequence of instructions in time to be recognized by an imme- tively worse due to the need to refill involving a back-to-back write followed diate read. Depending on the clock rate the pipe. Where such instructions by a read of the same data. Instruction and pin loading, a non-port instruction require two cycles (eight clocks) in n is writing data (write stage) even as should be inserted to split up a back- compatible mode, they need three instruction n + 1 (execute stage) wants to-back port write and read. Similarly, cycles (three clocks) in turbo mode, to read it. the possible difference between output derating the advantage to 2.66× (8 With on-chip RAM, the SX includes latch and pin level calls for care when divided by 3) for those instructions forwarding logic that handles such an using read, modify, and write instruc- versus 4× for most others. obstacle transparently in hardware. tions like SETB and CLRB. Another example is IREAD, one of Thus, one instruction can write to The I/O pins themselves (4-bit Port the ten new instructions added by RAM and the next one can safely read A, 8-bit Port B, and, for 28-pin devices, Scenix (see Table 1). IREAD enables a from the same location. However, for 8-bit Port C) are versatile. Each pin is program to read the instruction mem- I/O ports, there are precautions con- individually programmable as input or ory, something that’s nontrivial in a cerning successive operations. output, with or without an internal pull-up resistor. All inputs are select- able as TTL or CMOS levels, and Port O 2 OSC1 SC B and Port C inputs can be individually MCLR_ OSC 4-MHz defined as Schmitt triggered. Internal IRC driver WDT Brown-out Power-on osc 8-bit reset reset Outputs can sink and source 30 mA Prescaler reset System (subject to overall device power limit), clock I/O Ports A B C In-system with those on Port A featuring sym- Interrupt WDT 8-bit Comparator MIWU Reset Timer 4 bits 8 bits 8 bits debugging metrical drive (i.e., centered about 8 8 8 8 8 8 8 8 8 VDD/2 under any load). This feature is 8 8 8 Write data 8 useful for driving speakers and other W Instruction FSR Address 136-byte 2K × 12 In-system pseudoanalog functions such as using pipeline PC 8 SRAM EEPROM programming a PWM to implement a DAC. Status Option As inputs, pins of Port B can be 8 MBIT 12 12 Read data individually enabled to act as wakeups Instruction (with programmable edge selection) from low-power sleep mode. Or, three Figure 1—Like a motorcycle, the Scenix SX may be small, but at close to 50 MIPS, it’s really fast. pins of Port B can be configured as an

Circuit Cellar INK® Issue 100 November 1998 79 Photo 3a—The Parallax SX development software a) handles configuration and programming of the chip. b—It also handles debug of ASM programs. Notice the Parallax-defined mnemonics and multiword macro instructions.

analog comparator. Two inputs (RB1 and RB2) are compared with the result (greater than or less than) reflected on output RB3. Besides general-purpose I/O, the b) SX includes an 8-bit timer/counter (RTCC) and watchdog timer, either of which (but not both at the same time) can be mated with an 8-bit prescaler.

THROTTLE RESPONSE The inertia of a full-size four- wheeler isn’t a good match with stop-and-go traffic. The only win- ners are OPEC and brake shops. The same goes for chips and inter- only a small set of basic tools. It’s the rupts. The grander the CPU, the more same with the SX, thanks to the SX- energy and time wasted finishing off Key from Parallax. instructions in progress, saving a This nifty gadget, shown in Photo 1, bunch of registers, and making the exploits the fact that the SX has pro- turn toward the handler. Here, bikes— gramming and debug logic onboard, and the SX—have a big advantage. accessed via the OSC pins. In-system Less iron to stop and get going again programming and debugging for any means a quick and efficient response. SX-based design is a simple matter of Interrupt sources include the incorporating a four-pin header (OSC1, RTCC and pins of Port B configured OSC2, power, ground). For program- for wakeup (if the SX isn’t sleeping, a ming, the OSC pins act as a serial wakeup functions as an interrupt). download channel, while during de- Most CPUs require the instruction bug, the SX-Key has explicit clock in progress to complete before anything control. else happens, but not the SX. To cut Three packages are offered for your response time to the bone, the SX riding pleasure. The Skeleton Key aborts instructions in the pipe. It also ($249) is just the SX-Key and software includes a set of shadow registers that tools. The Master Key 18 ($319) adds a automatically capture the critical state. proto-board with buttons and LEDs The end result is a blazing interrupt (see Photo 2a). The Master Key 28 response: only three clocks for an ($349), shown in Photo 2b, comes RTCC interrupt and five clocks for with a fully loaded demo board in- external interrupts. That’s 60/100 ns cluding buttons, LEDs, RS-232, an (RTCC/external) at 50 MHz. Thanks external EEPROM, and a speaker. to the shadow registers, returns from On the roads these days, there’s a an interrupt are equally speedy at remarkable proliferation of SUVs. three clocks. Folks seem to think they need a cross between a Humvee and a Mack truck GRAB THE KEY, HIT THE ROAD to get across town. It’s kind of equiva- Another nice thing about bikes is lent to the bloatware phenomenon they’re easy to work on, requiring that curses our PCs.

80 Issue 100 November 1998 Circuit Cellar INK® carry bit, optional input One open issue involves integration Command Description synchronizers (metastabil- of the Byte Craft and Parallax tools. PAGE n Switch to new instruction page ity insurance at high clock At the time of this writing, they aren’t BANK n Switch to new register bank rates), and so on. really connected. However, both com- RET Return without affecting W The assembler uses the panies are planning a cozier relationship. RETP Return across page boundary Parallax mnemonics popu- RETI Return from interrupt and restore state RETIW Return from interrupt and reload timer larized on their earlier SX APPEAL IREAD Read instruction memory generation of PIC tools The conventionally wise will pro- MOV !M,W Write I/O mode bits (there is a utility available claim the concept of a high-perfor- MOV W,!M Read I/O mode bits to convert existing PIC mance 8-bit MCU as an oxymoron. MOV !rx,#imm Write immediate to port control register code to the SX/Parallax It’s true that the majority of apps are, mnemonics). Also, Parallax and will continue to be, well served Table 1—To ease programming and accomodate new features, Scenix adds 10 new instructions for a still RISCy grand total of 43. has defined a number of by the few MIPS most MCUs can convenient macro-instruc- muster. Yep, don’t expect to see your Not so with the SX-Key software tions that consolidate common se- average commuters crowding the (Win 95 and up), which is blessedly quences of single-word instructions Harley dealer, either. simple, boiling down to three screens: into easier-to-use formats. Fact is, I think Scenix might be one for editing your ASM program, one For those of you so inclined, there’s onto something. With performance to for configuring the SX, and the debug a C compiler from Byte Craft. Data- burn, the SX handles many functions screens in Photo 3. type support is impressive with 8-, in software that might otherwise call The set-up screen offers a good 16-, 24- and 32-bit INTs, and even for extra silicon. opportunity to top off the SX feature IEEE-754 floating point, though I sus- The concept of replacing hardware list. You can see the variety of clock pect it’s easy to bite off more than a with software (Scenix refers to virtual options (crystal, resonator, RC, and 2K-word SX can chew. peripherals) isn’t new. In fact, some of internal 4 MHz with an eight-stage It’s not cheap ($795 DOS, $1495 the earliest micros were used to just divider), configurable brown-out reset, Win 95/98/NT), but I’ve always found such an end. Witness the 8048 called extended stack (eight levels versus the that C compilers embody that old into duty as a keyboard encoder in the usual two), tweaked operation of the axiom “you get what you pay for.” original PC.

82 Issue 100 November 1998 Circuit Cellar INK® The difference is that the SX per- tions required to sample, compare, your tail, you’ve got two choices: formance headroom boosts the specs flag an error (false start bit), and so on. move over or get run over. I of the usual peripheral functions like By contrast, running at 50 MHz Tom Cantrell has been working on serial I/O, software timers, and wave- with five-clock external interrupt chip, board, and systems design and form generation. More speed, more response (i.e., 100 ns) makes 115 kbps marketing in Silicon Valley for more channels, or both. seem like a leisurely Sunday ride. I than ten years. You may reach him by For instance, consider the well- suspect you could hit 1 Mbps before E-mail at tom.cantrell@circuitcellar. known hack of building a UART in going to full throttle. When it comes com, by telephone at (510) 657-0264, software. Transmitting is easy since to interrupts, the SX blows the pins or by fax at (510) 657-5441. timing is under the control of the off regular MCUs. programmer. But, reception is another The extra bandwidth doesn’t mean SOURCES story. Few apps can afford to dedicate doing old stuff faster. It lets the SX all bandwidth to polling the serial accept the challenge of significantly SX MCU line, so interrupts are required. snootier I/O (e.g., music and voice syn- Scenix Semiconductor, Inc. Thus, the achievable data rate is thesis and software video generation). (408) 327-8888 directly related to interrupt latency, Scenix recently announced the Fax: (408) 327-8880 which should be less than half the bit availability of a Bell 202/CCITT V.22- www.scenix.com time. For instance, most 8-bit MCUs compatible 1200-/2400-bps modem SX-Key can handle 9600 bps, which enables a implemented in software, including Parallax, Inc. leisurely 50+ µs from the leading edge not only the raw signal processing (916) 624-8333 of the start bit (that generates the (FSK/DPSK) but also all the accesso- Fax: (916) 624-8003 interrupt) to the first sample. ries (DTMF generation and detection, www.parallaxinc.com But, higher data rates are a dicey call progress detection, and caller ID). proposition. For instance, 115 kbps Yeah, you can stick to your regular C compiler needs an interrupt response of less 8-/16-bit econo-chip for basic transpor- Byte Craft Ltd. than 5 µs. Speed not only becomes an tation, but remember that the fast (519) 888-6911 issue, but jitter (i.e., nondeterminism) lane is for passing. When that dot in Fax: (519) 746-6751 is a factor as well. Consider the 8051, the mirror turns into an SX hugging www.bytecraft.com which can only guarantee response somewhere between 36 and 108 clocks, or 3–9 µs at a 12-MHz clock rate. To be fair, much of the variance is because the ’51, like most MCUs, requires completion of the instruction in progress, including the relatively slow (48 clock) MUL and DIV, which the SX doesn’t have. Banning MUL and DIV would cut 24 clocks (2 µs at 12 MHz), making a worst-case response of 7 µs— still not fast enough. It’s worse than it sounds because I’m just talking about the raw inter- rupt response. More time is needed to save critical state (PSW and any other registers), not to mention the instruc-

I-Fetch D-Fetch Execute Write back PC ALU INST Result Decode

Flash memory SRAM

Figure 2—SX performance is obtained via pipelining using a time honored fetch-decode-execute-writeback design. Since a pipeline can only run as fast as its slowest stage, great attention was paid to the flash- memory design to achieve the 10-ns access time required by the 50-MHz clock rate.

Circuit Cellar INK® Issue 100 November 1998 83 PRIORITY INTERRUPT

What’s PC?

ne issue that I always wrestle with around here is separating hype from reality in the things we publish. My first o thought when we review an article for publication is always, is it real? Up to now, my test for “real” applied to the physical electronic components and usually never to the development platforms or the computers running the application. In my own writing, I went to great pains to maintain cross-platform compatibility. My early BYTE articles always interfaced through a parallel I/O port and frequently ran in high-level languages. There were many brands of computers. Some had dozens of I/O channels and supported many other languages, but they all seemed to have at least one parallel port and BASIC or C. Later, as the technical world standardized on the PC architecture, I adopted it as my universal development tool and application platform. Today, it should be even less of an issue. Everyone has a PC. I should be able to immediately assume that any article employing a PC is usable. Unfortunately, these days, I am having trouble defining exactly what a PC is and what configuration I should assume all of you think it is. The long ball and chain connected to the past has severely hindered PC hardware and software design over the years. It’s a wonder this computer architecture still works given the plethora of design iterations it has had to endure. I mean, look at it. Even with Windows 98, after 18 years, we still have the ISA bus, a 16-IRQ interrupt limit, and a silly 1-MB memory barrier in real mode. Heaven forbid, any of you reading Circuit Cellar INK presumes that an ultra-fast Pentium running a “real-time” process control program under Windows 98 is even remotely real time. About the only thing that seems to have advanced in parallel with its developmental need is graphics. Is this because we all play computer games, or was there a grander goal in mind? Another issue is I/O interfacing. Take a look at the mess hanging off the back of your PC. Just how many peripherals can you attach to two serial ports and a parallel printer port anyway? If your computer is anything like mine, there are a couple switch boxes and a web of cables. Of course, we’ve had innovations that were intended to solve this dilemma. Remember the SCSI bus? I have an HP scanner sitting at the end of a SCSI cable next to my computer. Of course, I never had another peripheral that shared this SCSI bus that didn’t have to be internally mounted because of noise or wasn’t better accommodated through an IDE connection instead. I still haven’t figured out where I’m supposed to find something I want to use with IrDA yet. Software and hardware designers have proposed many new standards to take the PC into the new millenium, including the Universal Serial Bus (USB), FireWire, and more modern operating systems like Windows NT and Linux. But, these new innovations have been a hard sell. Perhaps it’s simply the mentality that if it ain’t broke, don’t fix it. Computer purchasers are resistant to the radical price changes that typically follow revolutionary technical innovation, and hardware manufacturers don’t want to get caught out on a limb offering a product line that’s overpriced or unsupported. Consequently, we end up with the vast majority of PC sales being ever-lower priced versions with the same, albeit higher speed, ingredients. Without innovation in the hardware, how is the industry to move forward? It’s definitely going to take guts from someone to take the initiative. Such innovation is something that should be coming from Intel, but I believe Intel has such a vested interest in the past that it becomes a disincentive for it to break from tradition. Microsoft is a powerful company and I suppose it could unilaterally impose software changes that dictated hardware architectural changes to implement them. Such fanciful wishes ignore the Wintel legacy, however, and Microsoft’s vested interest in the past as well. Of course, I don’t know any other company that has succeeded so completely at convincing customers to pay for the aggravation of changing what ain’t broke on their PC. And, since virtually all the prior operating-system changes seem to obsolete the hardware anyway, it shouldn’t be a problem persuading users that any new OS just involves changing it a little more. I wish I had a crystal ball, but I don’t. Undoubtedly, it will take computer vendors like IBM, Hewlett-Packard, and Compaq to break with tradition and take the high ground in the next generation of chip development. I trust that the embedded-control industry will follow their lead. Whatever the outcome, however, you can count on my continuing to ask “what is real?” when it come to the articles we present.

[email protected]

96 Issue 100 November 1998 Circuit Cellar INK®